<?php

namespace Modules\VisitorMessage\Requests\Web;

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 VisitorMessageRequest 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()
    {
        return [
            'name' => 'required|string|min:2|max:35',
            'email' => 'required|email|max:255',
            'phone' => 'required|numeric|digits_between:9,12',
            'subject' => 'required|string|min:4|max:45',
            'message' => 'required|string|min:12|max:90',
        ];
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'name' => __('visitorMessages.name'),
            'subject' => __('visitorMessages.subject'),
            'email' => __('visitorMessages.email'),
            'phone' => __('visitorMessages.phone'),
            'message' => __('visitorMessages.message'),
        ];
    }

    /**
     * Get custom validation messages.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'name.min' => __('web.validation.name_min', ['min' => 2]),
            'name.max' => __('web.validation.name_max', ['max' => 35]),
            'subject.min' => __('web.validation.subject_min', ['min' => 4]),
            'subject.max' => __('web.validation.subject_max', ['max' => 45]),
            'phone.numeric' => __('web.validation.phone_numeric'),
            'phone.min' => __('web.validation.phone_min', ['min' => 9]),
            'phone.max' => __('web.validation.phone_max', ['max' => 12]),
            'message.min' => __('web.validation.message_min', ['min' => 12]),
            'message.max' => __('web.validation.message_max', ['max' => 90]),
        ];
    }

    /**
     * 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);
        }
    }
}
