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

/**
 * @property mixed facebook
 * @property mixed twitter
 * @property mixed instagram
 * @property mixed linkedin
 * @property mixed password
 * @property mixed role
 * @property mixed phone
 */
class MemberRequest 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, ['super_admin', 'admin', 'sub_admin']))
        {
            return true;
        }
        if(Auth::user()->hasModule('members'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $phonePattern = '/^(5){1}([0-9]{8})$/';
        $rules=[
            'name'=> 'required|min:3|max:100',
            'email' => [
                'required',
                'email',
                Rule::unique('users')->ignore($this->member? $this->member->id : 0, 'id')
            ],
            'phone'=> [
                "required",
                "numeric",
                "digits:9",
                'regex:'.$phonePattern,
                Rule::unique('users')->ignore($this->member? $this->member->id : 0, 'id')
            ],
            'gender'=> 'required|in:male,female',
            'country_id'=> 'required|exists:countries,id',
            'state_id'=> 'required|exists:states,id',
            'city'=> 'required|min:3|max:300',
            'zip_code'=> 'required|digits_between:3,10|min:3|max:10',


        ];

        $rules['status'] = 'nullable|in:1,0';

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

        $rules['photo'] = 'sometimes';


        return $rules;
    }

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

        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()){
            $errors = $validator->errors();
            if ($validator->fails()){
                throw new HttpResponseException(response()->json(['errors' => $errors->first()]));
            }
        } else {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
