<?php

namespace App\Http\Controllers\Admin;

use App\City;
use App\CityDescription;
use App\Http\Requests\CityRequest;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class CityController extends Controller
{

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

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

    /**
     * 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', get_defined_vars());
    }

    /**
     * return data of the courses.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = City::join('city_descriptions AS city_desc', 'cities.id', 'city_desc.city_id')
            ->where('city_desc.language_id', $language_id)
//            ->leftJoin('countries', 'countries.id', 'cities.country_id')
//            ->leftJoin('country_descriptions AS country_desc', 'countries.id', 'country_desc.country_id')
//            ->where('country_desc.language_id',$language_id)
            ->select(['city_desc.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('city_desc.name', 'LIKE', '%'.$request->name.'%');
        }

//        if ($request->country_id) {
//            $query->where('cities.country_id', $request->country_id);
//        }


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

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

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

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

    /**
     * Store a newly created resource in storage.
     * @param CityRequest $request
     * @return JsonResponse
     */
    public function store(CityRequest $request)
    {
        $city = City::create($request->all());
        $this->saveData( $request, $city->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


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

        $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', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     * @param CityRequest $request
     * @param City $city
     * @return JsonResponse
     */
    public function update(CityRequest $request, City $city)
    {
        $city->update($request->all());
        CityDescription::where('city_id', $city->id)->delete();
        $this->saveData( $request, $city->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * 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 courses 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 courses by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $cities = City::whereIn('id', $request->ids)->onlyTrashed();
        if ($cities){
            $cities->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
