<?php
namespace Modules\User\Requests\Api;


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

class RegistRequest 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|max:100',
            'phone'=> [
                "required",
                "numeric",
                "digits:9",
                'regex:/^5/',
                Rule::unique('users')
            ],
            'code'=>[
                'required',
            ],
            'title' => [
                'required',
                'max:250'
            ],
            'address' => [
                'required',
                'max:250'
            ],
            'city_id' => [
                'required',
                'exists:cities,id'
            ],
            'area_id' => [
                'required',
                'exists:areas,id'
            ],
            'latitude'=>[
                'required'    
            ],
            'longitude'=>[
                'required'    
            ],
        ];

        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $attributes = [
            'name' =>  __('web.name'),
            'code' =>  __('web.code'),
            'phone' =>  __('web.phone'),
            'address' =>  __('web.address'),
            'city_id' =>  __('web.city_id'),
            'area_id' =>  __('web.area_id'),
            'latitude' =>  __('web.map'),
            'longitude' =>  __('web.map'),
        ];

        return $attributes;
    }


    /**
     * Handle a failed validation attempt.
     *
     * Override the parent method action if the request is for AJAX
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
     protected function failedValidation(Validator $validator)
    {
        // Change response attitude if the request done via Ajax requests like API requests
        
            $errors = (new ValidationException($validator))->errors();
            $message = $validator->errors()->first();
            throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  400));
       
    }
}