<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Way;
use Illuminate\View\View;
use App\Models\WayDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\WayRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class WayController extends Controller
{

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

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

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

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

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

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

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

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

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


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

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

        $way = Way::create($data);

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

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


    /**
     * Show the form for editing the specified resource.
     *
     * @param Way $way
     * @return View
     */
    public function edit(Way $way) :View
    {
        $action= route('ways.update', $way->id);
        $head= metaFields('ways', 'edit', getCurrentLocale()) ?? __('ways.edit');

        $query = WayDescription::where('way_id', $way->id)
            ->join('languages', 'languages.id', 'way_descriptions.language_id')
            ->select(['way_descriptions.*', 'languages.local']);

        $wayDescription= $query->get();

        foreach ($wayDescription as $row) {
            $way[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param WayRequest $request
     * @param Way $way
     * @return RedirectResponse|Redirector
     */
    public function update(WayRequest $request, Way $way) :RedirectResponse
    {
        $data = $request->all();

        $way->update($data);

        // Delete old description
        WayDescription::where('way_id', $way->id)->delete();


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

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

    /**
     * Handle Save form data
     *
     * @param WayRequest $request
     * @param int $way_id
     * @return void
     */

    private function saveData(WayRequest $request, int $way_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'way_id'=> $way_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];
            WayDescription::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
    {
        $way = Way::withTrashed()->find($id);
        if ($way) {
            if ($way->deleted_at) {
                $way->forceDelete();
            } else {
                $way->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) {
            Way::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Way::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
    {
        $way = Way::withTrashed()->find($id);

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