<?php

namespace App\Http\Requests\Web;

use App\Models\BlockDate;
use App\Models\Reservation;
use App\Models\Room;
use DateTime;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

/**
 * @property mixed video_type
 * @property mixed video_url
 * @property mixed images
 */
class ReservationPayRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $min_capacity = Room::min('min_count');
        $max_capacity = Room::max('max_count');
        $block_dates = BlockDate::pluck('date')->toArray();
        $dates = implode(',',$block_dates);
        $rules =
            [
                'accept_on'=>'required',
                'date'=>'required|date|after_or_equal:'.date('Y-m-d').'|not_in:'.$dates,
                'capacity'=>'required|numeric|min:'.$min_capacity.'|max:'.$max_capacity,
                'room_id'=>'required|exists:rooms,id'
            ];
        if (request('date') && request('time') && request('room_id'))
        {
            $times = explode(' / ',request('time'));
            $start_time=$times[0];
            $end_time=$times[1];

            if(!$this->validateDate($start_time) || ! $this->validateDate($start_time))
            {
                $rules['not_valid'] = 'required';
            }
            else
            {
                // $reservations = Reservation::where('room_id', request('room_id'))
                //     ->where('date', request('date'))
                //     ->get();
                // $start_time = DateTime::createFromFormat('h:i a', date('g:i a',strtotime($start_time)));
                // $end_time = DateTime::createFromFormat('h:i a',  date('g:i a',strtotime($end_time)));

                // foreach ($reservations as $reservation)
                // {
                //     $reservation_start = DateTime::createFromFormat('h:i a', date('g:i a',strtotime($reservation->start_time)));
                //     $reservation_end = DateTime::createFromFormat('h:i a', date('g:i a',strtotime($reservation->end_time)));

                //     if ($start_time >= $reservation_start && $start_time < $reservation_end)
                //     {
                //         $rules['booked']  = 'required';
                //     }
                //     if ($end_time > $reservation_start && $end_time < $reservation_end)
                //     {
                //         $rules['booked']  = 'required';
                //     }
                // }
                
                
                $reservations = Reservation::where('room_id', request('room_id'))
                    ->where('date', request('date'))
                    ->get();
                
                // Convert new reservation's start_time and end_time to DateTime objects
                $start_time = DateTime::createFromFormat('h:i a', date('g:i a', strtotime($start_time)));
                $end_time = DateTime::createFromFormat('h:i a', date('g:i a', strtotime($end_time)));
                
                foreach ($reservations as $reservation) 
                {
                    // Convert reservation's start_time and end_time to DateTime objects
                    $reservation_start = DateTime::createFromFormat('h:i a', date('g:i a', strtotime($reservation->start_time)));
                    $reservation_end = DateTime::createFromFormat('h:i a', date('g:i a', strtotime($reservation->end_time)));
                
                    // Handle the case where the reservation spans midnight (i.e., end_time is before start_time)
                    if ($reservation_end < $reservation_start) {
                        // If reservation ends before it starts, it spans midnight (e.g., 11:00 PM to 2:00 AM)
                        $reservation_end->modify('+1 day'); // Add 1 day to end_time to account for crossing midnight
                    }
                
                    // Handle the case where the new reservation spans midnight
                    if ($end_time < $start_time) {
                        // If the new reservation ends before it starts, it spans midnight (e.g., 11:00 PM to 1:00 AM)
                        $end_time->modify('+1 day'); // Add 1 day to end_time
                    }
                    
                    if ($end_time < $start_time || $start_time->format('H:i') === '00:00') {
                        $end_time->modify('+1 day'); // Adjust for crossing midnight
                    }
                
                    // Now check if the new reservation's time overlaps with the existing reservation's time
                    if (
                        ($start_time < $reservation_end && $end_time > $reservation_start) // If the new reservation overlaps the existing one
                    ) {
                        // Set the status to false if there's an overlap
                        $rules['booked']  = 'required';
                    }
                }
                
                $temporary_reservation = Reservation::onlyTrashed()->where('room_id', request('room_id'))
                    ->where('date', request('date'))
                    ->where('link_expire_at','>',date('Y-m-d H:i:s'))
                    ->get();

                foreach ($temporary_reservation as $reservation) 
                {
                    // Convert reservation's start_time and end_time to DateTime objects
                    $reservation_start = DateTime::createFromFormat('h:i a', date('g:i a', strtotime($reservation->start_time)));
                    $reservation_end = DateTime::createFromFormat('h:i a', date('g:i a', strtotime($reservation->end_time)));
                
                    // Handle the case where the reservation spans midnight (i.e., end_time is before start_time)
                    if ($reservation_end < $reservation_start) {
                        // If reservation ends before it starts, it spans midnight (e.g., 11:00 PM to 2:00 AM)
                        $reservation_end->modify('+1 day'); // Add 1 day to end_time to account for crossing midnight
                    }
                    
                    if ($end_time < $start_time || $start_time->format('H:i') === '00:00') {
                        $end_time->modify('+1 day'); // Adjust for crossing midnight
                    }
                    
                    // Handle the case where the new reservation spans midnight
                    if ($end_time < $start_time) {
                        // If the new reservation ends before it starts, it spans midnight (e.g., 11:00 PM to 1:00 AM)
                        $end_time->modify('+1 day'); // Add 1 day to end_time
                    }
                
                    // Now check if the new reservation's time overlaps with the existing reservation's time
                    if (
                        ($start_time < $reservation_end && $end_time > $reservation_start) // If the new reservation overlaps the existing one
                    ) {
                        // Set the status to false if there's an overlap
                        $rules['booked']  = 'required';
                    }
                }
            }
        }
        else
        {
            $rules['time'] = 'required';
        }
        return $rules;
    }
    private function validateDate($date, $format = 'H:i')
    {
        $d = DateTime::createFromFormat($format, $date);
        $format = $d->format($format);
        if($format == '00:00')
        {
            $format= '24:00';
        }
        return $d && $format == $date;
    }
    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        $messages =
        [
            'booked.required' => __('web.booked_already'),
            'not_valid.required' => __('web.not_valid'),
        ];
        return  $messages;
    }
        public function attributes()
    {
        $attributes=
            [
                'accept_on'=>__('web.accept_on'),
                'capacity' => __('reservations.capacity'),
                'date' => __('reservations.date'),
                'duration' => __('reservations.duration'),
            ];

        return $attributes;
    }


    /**
     * Handle a failed validation attempt.
     *
     * Override the parent method action if the request is for AJAX
     *
     * @param Validator $validator
     * @return void
     *
     * @throws ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        // Change response attitude if the request done via Ajax requests like API requests
        if(Request::wantsJson()){
            $errors = (new ValidationException($validator))->errors();
            throw new HttpResponseException(response()->json(['errors' => $errors], 422));
        } else {
            parent::failedValidation($validator);
        }
    }
}
