<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Choice;
use Illuminate\View\View;
use App\Models\ChoiceDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Services\Response\ResponseService;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ChoiceRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ChoiceController extends Controller
{

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

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

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

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

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

        if ($request->description) {
            $query->where('ad.description', 'LIKE', '%'.$request->description.'%');
        }
        if ($request->link) {
            $query->where('link', 'LIKE', '%'.$request->link.'%');
        }
        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

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

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

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

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

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

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }


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

        $head= __('choices.edit');

        $query = ChoiceDescription::where('choice_id', $choice->id)
            ->join('languages', 'languages.id', 'choice_descriptions.language_id')
            ->select(['choice_descriptions.*', 'languages.local']);

        $choiceDescription= $query->get();

        foreach ($choiceDescription as $row) {
            $choice[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param ChoiceRequest $request
     * @param Choice $choice
     * @return RedirectResponse|Redirector
     */
    public function update(ChoiceRequest $request, Choice $choice) 
    {
        // Update image and category id if request has it

        $choice->update($request->all());

        // Delete old description
        ChoiceDescription::where('choice_id', $choice->id)->delete();

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

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }

    /**
     * Handle Save form data
     *
     * @param ChoiceRequest $request
     * @param int $choice_id
     * @return void
     */

    private function saveData(ChoiceRequest $request, int $choice_id ):void
    {

        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'choice_id'=> $choice_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];
            ChoiceDescription::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
    {
        $choice = Choice::withTrashed()->find($id);
        if ($choice) {
            if ($choice->deleted_at) {
                $choice->forceDelete();
            } else {
                $choice->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) {
            Choice::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Choice::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
    {
        $choice = Choice::withTrashed()->find($id);

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