<?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;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

/**
 * @property mixed password
 */
class UserUpdateProfileRequest extends FormRequest
{

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [];
        $phonePattern = '/^(05){1}([0-9]{8})$/';

        if ($this->user->role == 'user'){
            $rules=[
                'name'=> 'required|min:3|max:50',
                'email' => [
                    'required',
                    'email',
                    'min:3|max:50',
                    Rule::unique('users')->ignore($this->user->id, 'id')
                ],
                'phone'=> [
                    "required",
                    "numeric",
                    "digits:10",
                    "regex:".$phonePattern,
                    Rule::unique('users')->ignore($this->user->id, 'id')
                ],
                'password' => 'sometimes|nullable|confirmed',
                'email_receive' => 'nullable|in:1,0',
//            'password' => 'sometimes|confirmed|nullable|regex:/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*]{6,}$/',

            ];
        }

        if (request('update_address_flag')){
            $rules=[
                'city'=> 'required|min:3|max:50',
                'state_id'=> 'required|exists:states,id',
                'zip_code'=> 'required|numeric|min:3|max:10',
                'country_id'=> 'required|exists:countries,id',

            ];
        }

        return  $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $field = metaFields('users');
        $local = getCurrentLocale();
        $attributes= [
            'name'=> $field[$local]['name'] ?? __('members.name'),
            'gender'=> $field[$local]['gender'] ?? __('members.gender'),
            'email'=> $field[$local]['email'] ?? __('members.email'),
            'phone'=> $field[$local]['phone'] ?? __('members.phone'),
            'password'=> $field[$local]['password'] ?? __('members.password'),
            'city'=> $field[$local]['city'] ?? __('members.city'),
            'state_id'=> $field[$local]['state_id'] ?? __('members.state_id'),
            'zip_code'=> $field[$local]['zip_code'] ?? __('members.zip_code'),
            'country_id'=> $field[$local]['country_id'] ?? __('members.country_id'),
        ];
        return $attributes;
    }

    public function messages()
    {
        return [
            'phone.digits' => __('members.phone_digits'),
            'phone.regex' => __('members.phone_regex'),
        ];
    }

    /**
     * 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()){
            if ($validator->fails()){
                $errors = $validator->errors()->first();
                throw new HttpResponseException(response()->json(['errors' => $errors]));
            }

        } else {
            parent::failedValidation($validator);
        }
    }
}
