<?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('end_count');
        $max_capacity = Room::max('end_count');
        $block_dates = BlockDate::pluck('date')->toArray();
        $dates = implode(',',$block_dates);
        $rules =
            [
                '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';
                    }
                }
            }
        }
        else
        {
            $rules['time'] = 'required';
        }
        return $rules;
    }
    private function validateDate($date, $format = 'H:i')
    {
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($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=
            [
                '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);
        }
    }
}
