<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\FaqRequest;
use App\Language;
use App\Module;
use App\Faq;
use App\FaqDescription;
use App\Lesson;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use Illuminate\Http\Request;

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.
     *
     * @return View
     */
    public function index() :View
    {
        $title= __('faqs.head');
        return view($this->viewDirectory.'index',compact('title'));
    }


    /**
     * return data of the faqs.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {

        $query = Faq::join('faq_descriptions AS fd', 'fd.faq_id', 'faqs.id')
            ->where('fd.language_id', currentLanguage()->id)
            ->select(['faqs.*', 'fd.question']);

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

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


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


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

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


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


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $action= route('faqs.store');
        $head = metaFields('faqs', 'add_new', getCurrentLocale()) ?? __('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
    {
        // Create Records
        $this->saveData($request);

        // Return Redirect Response
        return redirect($this->redirectSuccessPath)->withMessage(__('dashboard.saveDone'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Faq  $faq
     * @return view
     */
    public function edit(Faq $faq): View
    {
        $action= route('faqs.update', $faq->id);
        $head = metaFields('faqs', 'edit', getCurrentLocale()) ?? __('faqs.edit');
        $faqDescription = FaqDescription::GetByFaqId($faq->id);

        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
    {
        $faq->touch();
        // Delete old answer
        FaqDescription::where('faq_id', $faq->id)->delete();

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

        // Return Redirect Response
        return redirect($this->redirectSuccessPath)->withMessage(__('dashboard.saveDone'));
    }


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

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

             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')]);
        }
    }
}
