<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Faq;
use Illuminate\View\View;
use App\Models\FaqDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\FaqRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class FaqController extends Controller
{

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

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('faqs.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 = Faq::latest()
            ->join('faq_descriptions AS ad', 'faqs.id', 'ad.faq_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.question', 'faqs.*']);

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

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

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


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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('faqs.store');
        $head= __('faqs.new');
        return view( $this->viewDirectory.'form', compact('action', 'head') );
    }

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


        $this->saveData($request, $faq->id);

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


    /**
     * Show the form for editing the specified resource.
     *
     * @param Faq $faq
     * @return View
     */
    public function edit(Faq $faq) :View
    {
        $action= route('faqs.update', $faq->id);

        $query = FaqDescription::where('faq_id', $faq->id)
            ->join('languages', 'languages.id', 'faq_descriptions.language_id')
            ->select(['faq_descriptions.*', 'languages.local']);
        $head= __('faqs.edit');

        $faqDescription= $query->get();

        foreach ($faqDescription as $row) {
            $faq[$row->local]= $row;
        }

        return view( $this->viewDirectory.'form', compact('faq', 'action','head') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param FaqRequest $request
     * @param Faq $faq
     * @return RedirectResponse|Redirector
     */
    public function update(FaqRequest $request, Faq $faq) :RedirectResponse
    {

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

        // update image to youtube api thumbnail if request have not image


        // Delete old description
        FaqDescription::where('faq_id', $faq->id)->delete();


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

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

    /**
     * Handle Save form data
     *
     * @param FaqRequest $request
     * @param int $faq_id
     * @return void
     */

    private function saveData(FaqRequest $request, int $faq_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'faq_id'=> $faq_id,
                'language_id'=> $lang->id,
                'answer'=> $requestData['answer_'.$lang->local],
                'question'=> $requestData['question_'.$lang->local],

            ];
            FaqDescription::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
    {
        $faq = Faq::withTrashed()->find($id);
        if ($faq) {
            if ($faq->deleted_at) {
                $faq->forceDelete();
            } else {
                $faq->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) {
            Faq::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Faq::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
    {
        $faq = Faq::withTrashed()->find($id);

        if ($faq){
            $faq->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
    {
        $faq = Faq::whereIn('id', $request->ids)->onlyTrashed();
        if ($faq){
            $faq->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.saveDone')]);
    }
}
