<?php

namespace App\Http\Requests;

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

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $role = ['admin', 'user'];
        if (! Auth::check()) {
            return true;
        }
        if(!in_array(Auth::user()->role, $role))
        {
            return false;
        }
        if(Auth::user()->hasModule('users'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules=[
            'photo' => 'sometimes',
            'name'=> 'required|min:3',
            'birth_date'=> 'required|date',
            'email' => [
                'required',
                'email',
                Rule::unique('users')->ignore($this->user? $this->user->id : 0, 'id')
            ],
            'phone'=> [
                "required",
                "numeric",
                "digits_between:11,14",
                Rule::unique('users')->ignore($this->user? $this->user->id : 0, 'id')
            ],
        ];

        if ( !$this->user  ) {
            $rules['password'] ='required|confirmed';
        } else {
            $rules['password'] ='sometimes|confirmed';
        }

        if ( !$this->user || !$this->user->role || 'admin' != $this->user->role ) {
            $rules['modules'] = 'required|array|exists:modules,id';
        }

        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $field = metaFields('users');
        $local = getCurrentLocale();
        $attributes= [
            'name'=> $field[$local]['name'] ?? __('users.name'),
            'phone'=> $field[$local]['phone'] ?? __('users.phone'),
            'email'=> $field[$local]['email'] ?? __('users.email'),
            'photo'=> $field[$local]['photo'] ?? __('users.photo'),
            'password'=> $field[$local]['password'] ?? __('users.password'),
            'password_confirmation'=> $field[$local]['password_confirmation'] ?? __('users.password_confirmation'),
            'modules'=> $field[$local]['modules'] ?? __('users.modules'),
        ];
        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::wantsJson()){
            $errors = (new ValidationException($validator))->errors();
            throw new HttpResponseException(response()->json(['errors' => $errors], 422));
        } else {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
