<?php

namespace App\Http\Controllers\Admin;

use App\City;
use App\HotelReservation;
use App\UmrahTripReservation;
use App\Http\Controllers\Controller;
use App\Http\Requests\MemberRequest;
use App\UmrahTrip;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

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

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

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

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


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

            ->join('umrah_trips', 'umrah_trips.id', 'umrah_trip_reservations.umrah_trip_id')
            ->join('umrah_trip_descriptions as tripDesc', 'tripDesc.umrah_trip_id', 'umrah_trips.id')
            ->where('tripDesc.language_id', $language_id)

            ->join('cities as departureCity', 'departureCity.id', 'umrah_trip_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', 'umrah_trip_reservations.arrival_city')
            ->join('city_descriptions as arrivalDesc', 'arrivalDesc.city_id', 'arrivalCity.id')
            ->where('arrivalDesc.language_id', $language_id)

        ->select(
            [
                'umrah_trip_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',
            ]
        )
        ->selectSub("SELECT name FROM users WHERE umrah_trip_reservations.user_id = id LIMIT 1", 'user_name')
        ->selectSub("SELECT email FROM users WHERE umrah_trip_reservations.user_id = id LIMIT 1", 'user_email')
        ->selectSub("SELECT phone FROM users WHERE umrah_trip_reservations.user_id = id LIMIT 1", 'user_phone ');

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

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

        if ($request->trip_name) {
            $query->where('tripDesc.name', 'LIKE', '%'.$request->trip_name.'%');
        }

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

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

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

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

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

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

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

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

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

        $umrah_trip_reservation = UmrahTripReservation::where('umrah_trip_reservations.id', $umrahTripReservation->id);

        if ($umrahTripReservation->user_id){
            $umrah_trip_reservation->join('users', 'users.id', 'umrah_trip_reservations.user_id');
        }
        $umrah_trip_reservation->join('umrah_trips', 'umrah_trips.id', 'umrah_trip_reservations.umrah_trip_id')
                ->join('umrah_trip_descriptions as tripDesc', 'tripDesc.umrah_trip_id', 'umrah_trips.id')
                ->where('tripDesc.language_id', $language_id)

                ->join('cities as departureCity', 'departureCity.id', 'umrah_trip_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', 'umrah_trip_reservations.arrival_city')
                ->join('city_descriptions as arrivalDesc', 'arrivalDesc.city_id', 'arrivalCity.id')
                ->where('arrivalDesc.language_id', $language_id);

        if ($umrahTripReservation->user_id){
            $umrah_trip_reservation->select(
                [
                    'umrah_trip_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 {
            $umrah_trip_reservation->select(
                [
                    'umrah_trip_reservations.*',
                    'tripDesc.name as trip_name',
                    'departureDesc.name as departure_city',
                    'arrivalDesc.name as arrival_city',
                ]
            );
        }

        $umrah_trip_reservation = $umrah_trip_reservation->first();

        $umrah_trip_reservation->rally_point_info = is_string($umrahTripReservation->rally_point_info) ? json_decode($umrahTripReservation->rally_point_info, true) : $umrahTripReservation->rally_point_info;

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


    /**
     * Change all finished reservation status to finished
     * @param Request $request
     * @return array
     */
    public function finishReservations(Request $request)
    {
        if ($request->ajax()){
            $now = Carbon::now('Asia/Riyadh')->format('Y-m-d');
            $reservations = UmrahTripReservation::whereStatus('current')->where('umrah_trip_date', '<', $now)->get();
            if (count($reservations)){
                $found = [];
                foreach ($reservations as $reservation) {
                    $reservationDate = Carbon::make(date('Y-m-d', strtotime($reservation->umrah_trip_date)))->addDays($reservation->umrahTrip->days_counts)->format('Y-m-d');
                    if ($reservationDate <= $now){
                        $reservation->update(['status' => 'finished']);
                        $found[] = true;
                    }
                }

                if (count($found)){
                    return ['message' => __('umrahTripReservations.finish_all_reservation_done')];
                } else {
                    return ['errors' => __('umrahTripReservations.no_reservation_finished')];
                }
            } else {
                return ['errors' => __('umrahTripReservations.no_reservation_finished')];
            }
        }
    }

    /**
     * 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() ?? [];

        $umrah_trips = UmrahTrip::whereHas('reservations')
                ->join('umrah_trip_descriptions as pd', 'pd.umrah_trip_id', 'umrah_trips.id')
                ->where('pd.language_id', $languageId)->select(
                    [
                        'umrah_trips.*',
                        'pd.name',
                    ]
                )->cursor() ?? [];

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


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


//    public function activeMember(PackageReservation $umrah_trip_reservations)
//    {
//        if ($umrah_trip_reservations->status){
//            $umrah_trip_reservations->update(['status' => 0]);
//            return response()->json(['message' => __('umrah_trip_reservations.de_active_success')]);
//        } else {
//            $umrah_trip_reservations->update(['status' => 1]);
//            return response()->json(['message' => __('umrah_trip_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
    {
        $umrah_trip_reservations = UmrahTripReservation::withTrashed()->find($id);
        if ($umrah_trip_reservations) {
            if ($umrah_trip_reservations->deleted_at) {
                $umrah_trip_reservations->forceDelete();
            } else {
                $umrah_trip_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) {
            UmrahTripReservation::onlyTrashed()->whereIn('id', $ids)->where('role', '!=', 'admin')->forceDelete();
        } else {
            UmrahTripReservation::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
    {
        $umrah_trip_reservations = UmrahTripReservation::withTrashed()->find($id);

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