<?php

namespace App\Http\Controllers\Admin;

use Exception;
use App\Models\Country;
use App\Models\City;
use Illuminate\View\View;
use App\Models\CityDescription;
use Illuminate\Http\Request;
use App\Services\Response\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CityRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class CityController extends Controller
{

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

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

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

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

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

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

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

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

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


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

        $query = CityDescription::where('city_id', $city->id)
            ->join('languages', 'languages.id', 'city_descriptions.language_id')
            ->select(['city_descriptions.*', 'languages.local']);

        $cityDescription= $query->get();
        foreach ($cityDescription as $row) {
            $city[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param CityRequest $request
     * @param Country $city
     * @return RedirectResponse|Redirector
     */
    public function update(CityRequest $request, City $city)
    {
        // Update image and category id if request has it
        $city->update($request->all());
        // Delete old description
        CityDescription::where('city_id', $city->id)->delete();
        // Insert new description
        $this->saveData( $request, $city->id );

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

    /**
     * Handle Save form data
     *
     * @param CityRequest $request
     * @param int $city_id
     * @return void
     */

    private function saveData(CityRequest $request, int $city_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'city_id'=> $city_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],

            ];
            CityDescription::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
    {
        $city = City::withTrashed()->find($id);
        if ($city) {
            if ($city->deleted_at) {
                $city->forceDelete();
            } else {
                $city->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) {
            City::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            City::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
    {
        $city = City::withTrashed()->find($id);

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