<?php

namespace App\Http\Controllers\Admin;

use App\FlavorType;
use Exception;
use App\Article;
use Illuminate\View\View;
use App\ArticleDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\ArticleRequest;
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.';

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

    /**
     * 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',get_defined_vars());
    }

    /**
     * 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', 'new', getCurrentLocale()) ?? __('articles.new');
        $title = $head;
        $flavorTypes = FlavorType::with('currentDescription')->cursor();
        return view( $this->viewDirectory.'form', get_defined_vars());
    }

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

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

        $this->saveData($request, $article->id);
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('articles.index')]);
//        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');
        $title = $head;


        $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;
        }
        $flavorTypes = FlavorType::with('currentDescription')->cursor();
        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param ArticleRequest $request
     * @param Article $article
     * @return JsonResponse
     */
    public function update(ArticleRequest $request, Article $article) :JsonResponse
    {

        $data = $request->all();

        // Update image and category id if request has it
        $article->update($data);

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

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

        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('articles.index')]);

//        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=[
                'name'=> $requestData['name_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'article_id'=> $article_id,
                'language_id'=> $lang->id,
            ];
            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')]);
        }
    }
}
