<?php

namespace App\Http\Controllers\Admin;

use App\City;
use App\Hotel;
use App\HotelReservation;
use App\Http\Controllers\Controller;
use App\Http\Requests\MemberRequest;
use App\Jobs\HotelReservationStatusJob;
use App\Room;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;

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

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

        $hotels = $hotelAndCities['hotels'];
        $cities = $hotelAndCities['cities'];
        $rooms = Room::withDescription();
        return view($this->viewDirectory.'index',get_defined_vars());
    }


    /**
     * return data of the hotel_reservations.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = HotelReservation::orderBy('hotel_reservations.id', 'DESC')
            ->leftJoin('users', 'users.id', 'hotel_reservations.user_id')
            ->join('cities', 'cities.id', 'hotel_reservations.city_id')
            ->join('city_descriptions as cityDesc', 'cityDesc.city_id', 'cities.id')
            ->where('cityDesc.language_id', $language_id)
            ->join('hotels', 'hotels.id', 'hotel_reservations.hotel_id')
            ->join('hotel_descriptions as hotelDesc', 'hotelDesc.hotel_id', 'hotels.id')
            ->where('hotelDesc.language_id', $language_id)
        ->select(
            [
                'hotel_reservations.*',
                'users.name as user_name',
                'users.email as user_email',
                'users.phone as user_phone',
                'cityDesc.name as city_name',
                'hotelDesc.name as hotel_name',
            ]
        );

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

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

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

        if ($request->hotel_id) {
            $query->where('hotel_reservations.hotel_id',$request->hotel_id);
        }
        if ($request->user_name) {
            $query->where('hotel_reservations.name', 'LIKE', '%'.$request->user_name.'%')
                ->orWhere('users.name', 'LIKE', '%'.$request->user_name.'%');
        }
        if ($request->user_email) {
            $query->where('hotel_reservations.email', 'LIKE', '%'.$request->user_email.'%')
            ->orWhere('users.email', 'LIKE', '%'.$request->user_email.'%');
        }
        if ($request->room_type) {
            $query->where('hotel_reservations.room_type', 'LIKE', '%'.$request->room_type.'%');
        }
        if ($request->reservation_status) {
            $query->where('hotel_reservations.status', $request->reservation_status);
        }
        if ($request->days_count) {
            $query->where('hotel_reservations.days_count', $request->days_count);
        }
        if ($request->person_count) {
            $query->where('hotel_reservations.person_count', $request->person_count);
        }

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

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

//        $roomTypes = [
//            1 => __('hotels.individually'),
//            2 => __('hotels.couple'),
//            3 => __('hotels.tripartite'),
//            4 => __('hotels.quadrilateral'),
//        ];

        $rooms = Room::withDescription();

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

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

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

        $hotelReservation = HotelReservation::where('hotel_reservations.id', $hotel_reservation->id);

        if ($hotel_reservation->user_id){
            $hotelReservation->join('users', 'users.id', 'hotel_reservations.user_id');
        }
            $hotelReservation->join('cities', 'cities.id', 'hotel_reservations.city_id')
            ->join('city_descriptions as cityDesc', 'cityDesc.city_id', 'cities.id')
            ->where('cityDesc.language_id', $language_id)
            ->join('hotels', 'hotels.id', 'hotel_reservations.hotel_id')
            ->join('hotel_descriptions as hotelDesc', 'hotelDesc.hotel_id', 'hotels.id')
            ->where('hotelDesc.language_id', $language_id);

        if ($hotel_reservation->user_id){
            $hotelReservation->select(
                [
                    'hotel_reservations.*',
                    'users.name as user_name',
                    'users.email as user_email',
                    'users.phone as user_phone',
                    'cityDesc.name as city_name',
                    'hotelDesc.name as hotel_name',
                ]
            );
        } else {
            $hotelReservation->select(
                [
                    'hotel_reservations.*',
                    'cityDesc.name as city_name',
                    'hotelDesc.name as hotel_name',
                ]
            );
        }

        $hotelReservation = $hotelReservation->first();

//        $hotelReservation->added_service = array_map(function ($value){
//            return __('hotels.'.$value);
//        }, $hotelReservation->added_service);

//        $hotelReservation->added_service_price = implode(' - ', $hotelReservation->added_service_price);
//        $roomTypes = [
//            1 => __('hotels.individually'),
//            2 => __('hotels.couple'),
//            3 => __('hotels.tripartite'),
//            4 => __('hotels.quadrilateral'),
//        ];

//        $hotelReservation->room_type = $roomTypes[$hotelReservation->room_type];
        $room = Room::withDescription($hotel_reservation->room_type);
        $roomType = $room ? $room->name : null;

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


    public function changeReservationStatus(Request $request)
    {
        if ($request->ajax()){

            $validation = Validator::make($request->all(), ['reservation_status' => 'required|in:confirmed,refund'], [], [
                'reservation_status' => __('hotel_reservations.status')
            ]);

            if ($validation->fails()){
                return ['errors' => $validation->errors()->first()];
            }

            $reservation = HotelReservation::find($request->reservation_id);

            if (!$reservation || $reservation->status == 'refund'){
                return ['errors' => __('hotel_reservations.reservation_not_found')];
            }
            if (!$reservation || $reservation->status == 'confirmed'){
                return ['errors' => __('hotel_reservations.reservation_already_confirmed')];
            }

            $payment = $reservation->payment;

            if (!$payment || !$reservation->status || $payment->refund){
                return ['errors' => __('hotel_reservations.payment_not_found')];
            }

            $message = null;
            $emailMessage = null;
            $emailDetails = null;
            $hotelName = descriptions($reservation->hotel)->name;
            $user = $reservation->user;

            if ($request->reservation_status == 'confirmed'){
                $emailMessage = __('hotel_reservations.confirmed_message');
                $emailMessage = str_replace_array('@@', [$user->name, $hotelName], $emailMessage);
                $message = __('hotel_reservations.reservation_confirmed');
                $city = descriptions($reservation->city)->name;
                $room = Room::withDescription($reservation->room_type);
                $emailDetails = [
                    'name' => $reservation->name,
                    'user_email' => $reservation->email,
                    'user_phone' => $reservation->phone,
                    'hotel_name' => $hotelName,
                    'hotel_email' => $reservation->hotel_email,
                    'hotel_address' => $reservation->hotel_address,
                    'city_name' => $city,
                    'room_type' => $room ? $room->name : null,
                    'days_count' => $reservation->days_count,
                    'person_count' => $reservation->person_count,
                    'going_date' => $reservation->going_date,
                    'return_date' => $reservation->return_date,
                ];
                $reservation->update(['status' => 'confirmed']);
            }

            if ($request->reservation_status == 'refund'){

                $refund = MyFatoorah::refund($payment->invoice_id, $payment->amount);
                if ($refund['errors']){
                    return ['errors' => $refund['errors']];
                }

                $reservation->update(['status' => 'refund']);
                $payment->update(['refund' => 1, 'meta' => $refund]);

                $emailMessage = __('hotel_reservations.refund_message');
                $emailMessage = str_replace_array('@@', [$user->name, $hotelName], $emailMessage);
                $message = __('hotel_reservations.reservation_refund');

            }

            $data = [
                'user_name' => $user->name,
                'email' => $user->email,
                'message' => $emailMessage,
                'details' => $emailDetails,
            ];
            HotelReservationStatusJob::dispatch($data, 'admin.hotel_reservations.email');

            return ['message' => $message];
        }
    }

    /**
     * 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 = HotelReservation::whereStatus('confirmed')->where('return_date', '<', $now)->cursor();

            if (count($reservations)){
                foreach ($reservations as $reservation) {
                    $reservation->update(['status' => 'finished']);
                }
                return ['message' => __('hotel_reservations.finish_all_reservation_done')];
            } else {
                return ['errors' => __('hotel_reservations.no_reservation_finished')];
            }
        }
    }


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

        $hotels = Hotel::whereHas('reservations')
                ->join('hotel_descriptions as hd', 'hd.hotel_id', 'hotels.id')
                ->where('hd.language_id', $languageId)->select(
                    [
                        'hotels.*',
                        'hd.name',
                        'hd.address',
                    ]
                )->cursor() ?? [];

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


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


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

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