<?php

namespace App\Http\Controllers\Admin;

use App\Reason;
use Exception;
use App\Language;
use App\ReasonDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\ReasonRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ReasonController extends Controller
{

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

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('reasons.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the reasons.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Reason::latest()
            ->join('reason_descriptions AS pd', 'reasons.id', 'pd.reason_id')
            ->join('languages', 'languages.id', 'pd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['pd.name', 'reasons.*']);

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

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

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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param ReasonRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ReasonRequest $request) :RedirectResponse
    {
        $reason = Reason::create($request->all());
        // Insert Description
        $this->saveData( $request, $reason->id );

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


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

        $query = ReasonDescription::where('reason_id', $reason->id)
            ->join('languages', 'languages.id', 'reason_descriptions.language_id')
            ->select(['reason_descriptions.*', 'languages.local']);

        $reasonDescription= $query->get();

        foreach ($reasonDescription as $row) {
            $reason[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param ReasonRequest $request
     * @param Reason $reason
     * @return RedirectResponse|Redirector
     */
    public function update(ReasonRequest $request, Reason $reason) :RedirectResponse
    {
        // Update image if request has it
        $reason->update(['image' => $request->image??null]);

        // Delete old description
        ReasonDescription::where('reason_id', $reason->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param ReasonRequest $request
     * @param int $reason_id
     * @return void
     */

    private function saveData(ReasonRequest $request, int $reason_id ):void
    {
        $requestData= $request->all();
        $languages= Language::where('status', 1)->cursor();

        foreach ($languages as $lang) {
            $data=[
                'reason_id'=> $reason_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];
            ReasonDescription::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
    {
        $reason = Reason::withTrashed()->find($id);
        if ($reason) {
            if ($reason->deleted_at) {
                $reason->forceDelete();
            } else {
                $reason->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several reasons by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Reason::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Reason::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
    {
        $reason = Reason::withTrashed()->find($id);

        if ($reason){
            $reason->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several reasons by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $reasons = Reason::whereIn('id', $request->ids)->onlyTrashed();
        if ($reasons){
            $reasons->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}