<?php

namespace App\Http\Controllers\Admin;

use App\Airport;
use App\City;
use App\Country;
use App\Http\Requests\AirportRequest;
use Exception;
use App\AirportDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class AirportController extends Controller
{

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

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('airports.head');
        $request= $request->toArray();
        $language_id = currentLanguage()->id;
        $countries = Country::whereHas('airports')
            ->join('country_descriptions as cd', 'cd.country_id', 'countries.id')
            ->where('cd.language_id', $language_id)
            ->select([
                'countries.*',
                'cd.name',
            ])->cursor();

        $cities = City::whereHas('airports')
            ->join('city_descriptions as cd', 'cd.city_id', 'cities.id')
            ->where('cd.language_id', $language_id)
            ->select([
                'cities.*',
                'cd.name',
            ])->cursor();

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

    /**
     * return data of the courses.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = Airport::join('airport_descriptions AS airDesc', 'airports.id', 'airDesc.airport_id')
            ->where('airDesc.language_id', currentLanguage()->id)
            ->join('countries', 'airports.country_id', 'countries.id')
            ->join('country_descriptions as countryDesc', 'countryDesc.country_id', 'countries.id')
            ->where('countryDesc.language_id', $language_id)

            ->join('cities', 'airports.city_id', 'cities.id')
            ->join('city_descriptions as cityDesc', 'cityDesc.city_id', 'cities.id')
            ->where('cityDesc.language_id', $language_id)

            ->select([
                'airDesc.name',
                'countryDesc.name as country_name',
                'cityDesc.name as city_name',
                'airports.*'
            ]);

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

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

        if ($request->name) {
            $query->where('airDesc.name', 'LIKE', '%'.$request->name.'%');
        }
        if ($request->code) {
            $query->where('airports.code', 'LIKE', '%'.$request->code.'%');
        }
        if ($request->country_id) {
            $query->where('airports.country_id', $request->country_id);
        }
        if ($request->city_id) {
            $query->where('airports.city_id', 'LIKE', $request->city_id);
        }


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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('airports.store');
        $head = metaFields('airports', 'add_new', getCurrentLocale()) ?? __('airports.new');
        $local = getCurrentLocale();
        $countries = Country::withDescription();
        $cities = [];
        return view( $this->viewDirectory.'form', compact('action', 'head', 'local', 'countries', 'cities'));
    }

    /**
     * Store a newly created resource in storage.
     * @param AirportRequest $request
     * @return JsonResponse
     */
    public function store(AirportRequest $request)
    {
        $airport = Airport::create($request->all());
        $this->saveData( $request, $airport->id );
        session()->flash('message', __('dashboard.saveDone'));
        return  response()->json(['url' => route('airports.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


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

        $query = AirportDescription::where('airport_id', $airport->id)
            ->join('languages', 'languages.id', 'airport_descriptions.language_id')
            ->select(['airport_descriptions.*', 'languages.local']);

        $airportDescription= $query->get();

        foreach ($airportDescription as $row) {
            $airport[$row->local]= $row;
        }

        $local = getCurrentLocale();
        $countries = Country::withDescription();
        $cities = City::withDescription($airport->country_id, $airport->city_id);

        return view( $this->viewDirectory.'form', compact('airport', 'action', 'head', 'local', 'countries', 'cities'));
    }

    /**
     * Update the specified resource in storage.
     * @param AirportRequest $request
     * @param Airport $airport
     * @return JsonResponse
     */
    public function update(AirportRequest $request, Airport $airport)
    {
        $airport->update($request->all());
        // Delete old description
        AirportDescription::where('airport_id', $airport->id)->delete();
        $this->saveData( $request, $airport->id );
        session()->flash('message', __('dashboard.saveDone'));
        return  response()->json(['url' => route('airports.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Handle Save form data
     *
     * @param AirportRequest $request
     * @param int $airport_id
     * @return void
     */

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

    }


    public function getCity(Request $request)
    {
        if ($request->ajax()){
            $cities = City::withDescription($request->country_id);
            if (count($cities)){
                return response()->json(['cities' => $cities]);
            } else {
                return response()->json(['cities' => false]);
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $airport = Airport::withTrashed()->find($id);
        if ($airport) {
            if ($airport->deleted_at) {
                $airport->forceDelete();
            } else {
                $airport->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) {
            Airport::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Airport::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
    {
        $airport = Airport::withTrashed()->find($id);

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