<?php

namespace App\Http\Requests;

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

/**
 * @property mixed name
 * @property mixed email
 * @property mixed phone
 * @property mixed file
 */
class CareerRequest 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 = [
            'name' => 'required|min:3|max:|100',
            'email' => 'required|email|min:9|max:100',
            'phone' => 'required|digits_between:9,14',
            'file' => 'required|file|mimes:pdf,doc,zip,docx,rar',
        ];

        return $rules;
    }

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

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