<?php

namespace App\Http\Requests\Web;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class RoomComplaintRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     * So the user must be guest
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $namesRegex = '/^([a-zA-Z ]|[\p{Arabic}])*$/u';
        $phonePattern = '/^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/';
        $rules = [
            'name' => ['required', 'min:3', 'max:100', 'regex:'.$namesRegex],
            'email' => ['required', 'email', 'max:50'],
            'phone' => ['required', 'numeric', 'regex:'.$phonePattern],
            'title' => ['required', 'min:3', 'max:50'],
            'details' => ['required', 'min:3', 'max:400'],
            'image' => ['nullable', 'mimes:jpg,jpeg,png'],
        ];
        return $rules;
    }

    public function attributes()
    {
        $field = metaFields('roomComplaints');
        $local = getCurrentLocale();
        $attributes = [
            'name' => $field[$local]['name'] ?? __('roomComplaints.name'),
            'email' => $field[$local]['email'] ?? __('roomComplaints.email'),
            'phone' => $field[$local]['phone'] ?? __('roomComplaints.phone'),
            'title' => $field[$local]['title'] ?? __('roomComplaints.title'),
            'details' => $field[$local]['details'] ?? __('roomComplaints.details'),
            'image' => $field[$local]['image'] ?? __('roomComplaints.image'),
        ];

        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::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);
        }
    }
}
