<?php

namespace App\Http\Requests;

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;

class AddReservationRequest 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()
    {
        $rules=[
            'occasion_id' => 'required|exists:occasions,id',
        ];

        if ($this->hall->reservation_type == 'person_count'){
            $rules['person_count'] = 'required|numeric|gt:0';
        }
//        $rules['re_date_from'] = 'required|date';
//        $rules['re_date_to'] = 'required|date|after_or_equal:re_date_from';
        $rules['re_days'] = 'required|array';
        $rules['services'] = 'nullable|array|exists:services,id';
        $rules['added_services'] = 'nullable|array';


        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $attributes= [
            'occasion_id'=>  __('reservations.occasion_id'),
            'person_count'=>  __('reservations.person_count'),
            're_days'=>  __('reservations.re_days'),
            're_date_from'=>  __('reservations.re_date_from'),
            're_date_to'=>  __('reservations.re_date_to'),
            'services'=>  __('reservations.services'),
            'added_services'=>  __('reservations.added_services'),
        ];
        return $attributes;
    }

    public function messages()
    {
        return [
            'person_count.gt' => __('reservations.person_count_gt'),
            're_date_to.after_or_equal' => __('reservations.re_date_to_after_or_equal'),
        ];
    }

    /**
     * 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::ajax()){
            $errors = $validator->errors()->first();
            throw new HttpResponseException(response()->json(['errors' => $errors]));
        } else {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
