<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Article;
use Illuminate\View\View;
use App\Models\ArticleDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ArticleRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ArticleController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/articles';
    /** View folder */
    private $viewDirectory = 'admin.articles.';

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('articles.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Article::latest()
            ->join('article_descriptions AS ad', 'articles.id', 'ad.article_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.name', 'articles.*']);

        if ($request->date_from) {
            $query->whereDate('articles.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('articles.created_at', '<=', $request->date_to);
        }

        if ($request->name) {
            $query->where('ad.name', 'LIKE', '%'.$request->name.'%');
        }

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $articles= $query->paginate(100);

        return view($this->viewDirectory.'grid',compact('articles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('articles.store');
        $head= metaFields('articles', 'add_new', getCurrentLocale()) ?? __('articles.new');


        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param ArticleRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ArticleRequest $request) :RedirectResponse
    {
        $data = $request->all();

        $article = Article::create($data);

        // Insert Description
        $this->saveData($request, $article->id);

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Article $article
     * @return View
     */
    public function edit(Article $article) :View
    {
        $action= route('articles.update', $article->id);
        $head= metaFields('articles', 'edit', getCurrentLocale()) ?? __('articles.edit');

        $query = ArticleDescription::where('article_id', $article->id)
            ->join('languages', 'languages.id', 'article_descriptions.language_id')
            ->select(['article_descriptions.*', 'languages.local']);

        $articleDescription= $query->get();

        foreach ($articleDescription as $row) {
            $article[$row->local]= $row;
        }

        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param ArticleRequest $request
     * @param Article $article
     * @return RedirectResponse|Redirector
     */
    public function update(ArticleRequest $request, Article $article) :RedirectResponse
    {
        $data = $request->all();

        $article->update($data);

        // Delete old description
        ArticleDescription::where('article_id', $article->id)->delete();


        // Insert new description
        $this->saveData( $request, $article->id );

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param ArticleRequest $request
     * @param int $article_id
     * @return void
     */

    private function saveData(ArticleRequest $request, int $article_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'article_id'=> $article_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];
            ArticleDescription::create($data);
        }


    }


    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $article = Article::withTrashed()->find($id);
        if ($article) {
            if ($article->deleted_at) {
                $article->forceDelete();
            } else {
                $article->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Article::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Article::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $article = Article::withTrashed()->find($id);

        if ($article){
            $article->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $article = Article::whereIn('id', $request->ids)->onlyTrashed();
        if ($article){
            $article->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.saveDone')]);
    }
}
