<?php

namespace App\Http\Controllers\Admin;

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

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

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('package_reservations.head');
        $request= $request->toArray();
        $hotelAndCities = $this->tripAnsCities();

//        $trips = $hotelAndCities['packages'];
        $cities = $hotelAndCities['cities'];

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


    /**
     * return data of the package_reservations.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = PackageReservation::orderBy('package_reservations.id', 'DESC')
            ->leftJoin('users', 'users.id', 'package_reservations.user_id')

            ->join('packages', 'packages.id', 'package_reservations.package_id')
            ->join('package_descriptions as tripDesc', 'tripDesc.package_id', 'packages.id')
            ->where('tripDesc.language_id', $language_id)

            ->join('cities as departureCity', 'departureCity.id', 'package_reservations.departure_city')
            ->join('city_descriptions as departureDesc', 'departureDesc.city_id', 'departureCity.id')
            ->where('departureDesc.language_id', $language_id)

            ->join('cities as arrivalCity', 'arrivalCity.id', 'package_reservations.arrival_city')
            ->join('city_descriptions as arrivalDesc', 'arrivalDesc.city_id', 'arrivalCity.id')
            ->where('arrivalDesc.language_id', $language_id)

        ->select(
            [
                'package_reservations.*',
                'users.name as user_name',
                'users.email as user_email',
                'users.phone as user_phone',
                'tripDesc.name as trip_name',
                'departureDesc.name as departure_city',
                'arrivalDesc.name as arrival_city',
            ]
        );

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

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

        if ($request->user_name) {
            $query->where('package_reservations.name', 'LIKE', '%'.$request->user_name.'%')
                ->orWhere('users.name', 'LIKE', '%'.$request->user_name.'%');
        }
        if ($request->user_email) {
            $query->where('package_reservations.email', 'LIKE', '%'.$request->user_email.'%')
                ->orWhere('users.email', 'LIKE', '%'.$request->user_email.'%');
        }

        if ($request->trip_type) {
            $query->where('package_reservations.trip_type', $request->trip_type);
        }

        if ($request->trip_date) {
            $query->where('package_reservations.trip_date',$request->trip_date);
        }

        if ($request->departure_city) {
            $query->where('package_reservations.departure_city', $request->departure_city);
        }
        if ($request->arrival_city) {
            $query->where('package_reservations.arrival_city', $request->arrival_city);
        }

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

        $package_reservations= $query->paginate(10);

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
//    public function create() :View
//    {
//        $action= route('package_reservations.store');
//        $head = metaFields('package_reservations', 'add_new', getCurrentLocale()) ?? __('package_reservations.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';
//        PackageReservation::create($data);
//        session()->flash('message', __('dashboard.saveDone'));
//        return response()->json(['url' => route('package_reservations.index')]);
////        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
//    }

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

        $packageReservation = PackageReservation::where('package_reservations.id', $package_reservation->id);

        if ($package_reservation->user_id){
            $packageReservation->join('users', 'users.id', 'package_reservations.user_id');
        }
            $packageReservation->join('packages', 'packages.id', 'package_reservations.package_id')
                ->join('package_descriptions as tripDesc', 'tripDesc.package_id', 'packages.id')
                ->where('tripDesc.language_id', $language_id)

                ->join('cities as departureCity', 'departureCity.id', 'package_reservations.departure_city')
                ->join('city_descriptions as departureDesc', 'departureDesc.city_id', 'departureCity.id')
                ->where('departureDesc.language_id', $language_id)

                ->join('cities as arrivalCity', 'arrivalCity.id', 'package_reservations.arrival_city')
                ->join('city_descriptions as arrivalDesc', 'arrivalDesc.city_id', 'arrivalCity.id')
                ->where('arrivalDesc.language_id', $language_id);

        if ($package_reservation->user_id){
            $packageReservation->select(
                [
                    'package_reservations.*',
                    'users.name as user_name',
                    'users.email as user_email',
                    'users.phone as user_phone',
                    'tripDesc.name as trip_name',
                    'departureDesc.name as departure_city',
                    'arrivalDesc.name as arrival_city',
                ]
            );
        } else {
            $packageReservation->select(
                [
                    'package_reservations.*',
                    'tripDesc.name as trip_name',
                    'departureDesc.name as departure_city',
                    'arrivalDesc.name as arrival_city',
                ]
            );
        }

        $packageReservation = $packageReservation->first();
        $packageReservation->rally_point_info = is_string($packageReservation->rally_point_info) ? json_decode($packageReservation->rally_point_info, true) : $packageReservation->rally_point_info;

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


    /**
     * Return cities and hotel that have hotel reservations
     * @return array
     */
    private function tripAnsCities()
    {
        $languageId = currentLanguage()->id;
        $cities = City::join('city_descriptions as cd', 'cd.city_id', 'cities.id')
                ->where('cd.language_id', $languageId)->select([
                    'cities.*',
                    'cd.name',
                ])->cursor() ?? [];

        $packages = Package::whereHas('reservations')
                ->join('package_descriptions as pd', 'pd.package_id', 'packages.id')
                ->where('pd.language_id', $languageId)->select(
                    [
                        'packages.*',
                        'pd.name',
                    ]
                )->cursor() ?? [];

        return ['cities' => $cities, 'packages' => $packages];
    }


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


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




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

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