<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Choise;
use Illuminate\View\View;
use App\Models\ChoiseDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ChoiseRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ChoiseController extends Controller
{

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

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

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

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

        if ($request->title) {
            $query->where('ad.name', 'LIKE', '%'.$request->title.'%');
        }
        if ($request->type) {
            $query->where('choises.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();
        }

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

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

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

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

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

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


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

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

        $query = ChoiseDescription::where('choise_id', $choise->id)
            ->join('languages', 'languages.id', 'choise_descriptions.language_id')
            ->select(['choise_descriptions.*', 'languages.local']);

        $choiseDescription= $query->get();

        foreach ($choiseDescription as $row) {
            $choise[$row->local]= $row;
        }

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

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

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

        // Delete old description
        ChoiseDescription::where('choise_id', $choise->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param ChoiseRequest $request
     * @param int $choise_id
     * @return void
     */

    private function saveData(ChoiseRequest $request, int $choise_id ):void
    {

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

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