<?php

namespace App\Http\Requests;

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

class ConsultationRequest 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()
    {
        $phonePattern = '/^(05){1}([0-9]{8,15})$/';
        return [
            'name' => 'required|min:3|max:100',
            'email' => 'required|email|max:100',
            'phone'     => 'required|regex:'.$phonePattern,
            'consulting_id' => 'required|exists:consultings,id',
            'subject' => 'required|min:3',
        ];
    }

    public function attributes()
    {
        $field = metaFields('consultations');
        $local = getCurrentLocale();
        $attributes=[
            'name' => $field[$local]['name'] ?? __('consultations.name'),
            'email' => $field[$local]['email'] ?? __('consultations.email'),
            'phone' => $field[$local]['phone'] ?? __('consultations.phone'),
            'consulting_id' => $field[$local]['consulting_id'] ?? __('consultations.consulting_id'),
            'subject' => $field[$local]['subject'] ?? __('consultations.subject'),
        ];

        return $attributes;
    }


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