<?php

namespace App\Http\Controllers\Admin;

use App\City;
use App\Flight;
use App\Http\Controllers\Controller;
use App\Http\Requests\MemberRequest;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class FlightController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/flights';
    /** View folder */
    private $viewDirectory = 'admin.flights.';

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

    /**
     * return data of the flights.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = Flight::orderBy('flights.created_at', 'DESC')
            ->join('cities as departureCity', 'departureCity.id', 'flights.departure_city')
            ->join('city_descriptions as departureDesc', 'departureDesc.city_id', 'departureCity.id')
            ->where('departureDesc.language_id', $language_id)
            ->join('cities as arrivalCity', 'arrivalCity.id', 'flights.arrival_city')
            ->join('city_descriptions as arrivalDesc', 'arrivalDesc.city_id', 'arrivalCity.id')
            ->where('arrivalDesc.language_id', $language_id)
        ->select(
            [
                'flights.*',
                'departureDesc.name as departure_city',
                'arrivalDesc.name as arrival_city',
            ]
        );

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

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

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

        if ($request->phone) {
            $query->where('flights.phone', 'LIKE', '%'.$request->phone.'%');
        }
        if ($request->departure_city) {
            $query->where('flights.departure_city', $request->departure_city);
        }
        if ($request->arrival_city) {
            $query->where('flights.arrival_city', $request->arrival_city);
        }
        if ($request->trip_type) {
            $query->where('flights.trip_type', $request->trip_type);
        }
        if ($request->class_type) {
            $query->where('flights.class_type', $request->class_type);
        }


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

        $flights= $query->paginate(1000);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('flights.store');
        $head = metaFields('flights', 'add_new', getCurrentLocale()) ?? __('flights.new');
//        $regions = Region::withDescription();
        $cities = City::withDescription();
//        $sectors = [];
        $local = getCurrentLocale();


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

    /**
     * Store a newly created resource in storage.
     *
     * @param MemberRequest $request
     * @return JsonResponse
     */
    public function store(MemberRequest $request) :JsonResponse
    {
        $data = $request->all();
        $data['password'] = bcrypt($request->password);
        $data['role'] = 'user';
        Flight::create($data);
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('flights.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Flight $flights
     * @return View
     */
    public function edit(Flight $flight)
    {
        $head = metaFields('flights', 'edit', getCurrentLocale()) ?? __('flights.edit');
        $local = getCurrentLocale();
        $language_id = currentLanguage()->id;

        $flight = Flight::where('flights.id', $flight->id)
            ->join('cities as departureCity', 'departureCity.id', 'flights.departure_city')
            ->join('city_descriptions as departureDesc', 'departureDesc.city_id', 'departureCity.id')
            ->where('departureDesc.language_id', $language_id)
            ->join('cities as arrivalCity', 'arrivalCity.id', 'flights.arrival_city')
            ->join('city_descriptions as arrivalDesc', 'arrivalDesc.city_id', 'arrivalCity.id')
            ->where('arrivalDesc.language_id', $language_id)

            ->join('airports as departureAir', 'departureAir.id', 'flights.departure_airport')
            ->join('airport_descriptions as departureAirDesc', 'departureAirDesc.airport_id', 'departureAir.id')
            ->where('departureAirDesc.language_id', $language_id)
            ->join('airports as arrivalAir', 'arrivalAir.id', 'flights.arrival_airport')
            ->join('airport_descriptions as arrivalAirDesc', 'arrivalAirDesc.airport_id', 'arrivalAir.id')
            ->where('arrivalAirDesc.language_id', $language_id)
            ->select(
                [
                    'flights.*',
                    'departureDesc.name as departure_city',
                    'arrivalDesc.name as arrival_city',
                    'departureAirDesc.name as departure_airport',
                    'arrivalAirDesc.name as arrival_airport',
                ]
            )->first();

//        dd($flight);

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

    /**
     * Update the specified resource in storage.
     *
     * @param MemberRequest $request
     * @param Flight $flights
     * @return JsonResponse
     */
    public function update(MemberRequest $request, Flight $flights) :JsonResponse
    {
        $data = $request->all();
        $data['password'] = $request->password ? bcrypt($request->password) : $flights->password;
        $data['role'] = 'user';
        $flights->update($data);
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('flights.index')]);

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


    public function activeMember(Flight $flights)
    {
        if ($flights->status){
            $flights->update(['status' => 0]);
            return response()->json(['message' => __('flights.de_active_success')]);
        } else {
            $flights->update(['status' => 1]);
            return response()->json(['message' => __('flights.active_success')]);
        }

    }

    public function getCityAndSector(Request $request)
    {
        if ($request->ajax()){
            $data = [];
            $status = false; // to specify which request returned city or sectors
            if ($request->region_id){
                $status = 'city';
                $data = City::withDescription($request->region_id);
            }
            if ($request->city_id){
                $status = 'sector';
                $data = Sector::withDescription($request->city_id);
            }

            return ['data' => $data, 'status' => $status];
        }
    }



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

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