<?php

namespace App\Http\Controllers\Admin;

use App\Method;
use Exception;
use App\Language;
use App\MethodDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\MethodRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class MethodController extends Controller
{

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

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

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

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

        if ($request->date_to) {
            $query->whereDate('methods.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();
        }

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

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

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

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

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


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

        $query = MethodDescription::where('method_id', $method->id)
            ->join('languages', 'languages.id', 'method_descriptions.language_id')
            ->select(['method_descriptions.*', 'languages.local']);

        $MethodDescription= $query->get();

        foreach ($MethodDescription as $row) {
            $method[$row->local]= $row;
        }

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

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

        // Delete old description
        MethodDescription::where('method_id', $method->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param MethodRequest $request
     * @param int $method_id
     * @return void
     */

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

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

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

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

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