<?php

namespace App\Http\Controllers\Admin;

use App\Faq;
use App\FaqDescription;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\FaqRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;

class FaqController extends Controller
{

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

    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= __('faqs.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index', get_defined_vars());
    }

    /**
     * return data of the banks.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Faq::orderByDesc('faqs.id')
            ->join('faq_descriptions AS pd', 'faqs.id', 'pd.faq_id')
            ->join('languages', 'languages.id', 'pd.language_id')
            ->where('local', getCurrentLocale())
            ->select(['pd.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->question) {
            $query->where('pd.question', 'LIKE', '%'.$request->question.'%');
        }

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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param FaqRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(FaqRequest $request) :RedirectResponse
    {
        $faq = Faq::create();
        $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);
        $head = metaFields('faqs', 'edit', getCurrentLocale()) ?? __('faqs.edit');
        $title = $head;

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

        $faqDescription = $query->get();

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

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

    /**
     * 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 if request has it
        $faq->touch();

        // 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,
                'question'=> $requestData['question_'.$lang->local],
                'answer'=> $requestData['answer_'.$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 banks 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 banks 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')]);
        }
    }
}
