<?php

namespace App\Http\Requests\Web;

use App\Models\BlockDate;
use App\Models\Room;
use App\Models\WorkDay;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
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 ReservationContinueRequest 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 =
            [
                'date'=>'required|date|after_or_equal:'.date('Y-m-d').'|not_in:'.$dates,
                'capacity'=>'required|numeric|min:1|max:'.$max_capacity,
            ];
        if (request('date'))
        {
            $day = date('l',strtotime(request('date')));
            $work_day = WorkDay::where('day',$day)->first();

            $date1=date_create($work_day->end_time);
            $date2=date_create($work_day->start_time);
            $diff=date_diff($date1,$date2);
            $rules['duration'] = 'required|min:1|max:'.$diff->h;
        }
        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $attributes=
            [
                'capacity' => __('web.capacity'),
                'date' => __('web.date'),
                'duration' => __('web.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);
        }
    }
}
