<?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;

/**
 * @property mixed email
 * @property mixed phone
 */
class JobRequest 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,
            'nationality'     => 'required|string|min:3|max:50',
            'speciality_id' => 'required|exists:specialities,id',
            'experience_years' => 'required|numeric|min:1',
            'cv' => 'required|mimes:jpg,jpeg,png,pdf',
            'details' => 'required|min:3|max:400',
        ];
    }

    public function attributes()
    {
        $field = metaFields('jobs');
        $local = getCurrentLocale();
        $attributes=[
            'name' => $field[$local]['name'] ?? __('jobs.name'),
            'email' => $field[$local]['email'] ?? __('jobs.email'),
            'phone' => $field[$local]['phone'] ?? __('jobs.phone'),
            'speciality_id' => $field[$local]['speciality_id'] ?? __('jobs.speciality_id'),
            'experience_years' => $field[$local]['experience_years'] ?? __('jobs.experience_years'),
            'cv' => $field[$local]['cv'] ?? __('jobs.cv'),
            'details' => $field[$local]['details'] ?? __('jobs.details'),
        ];

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