<?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
 */
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()
    {
//        dd(request()->all());
        $phonePattern = '/^(05){1}([0-9]{8})$/';
        $rules = [
//            'role'=> 'required|in:user,provider',
            'name'=> 'required|min:3|max:100',
            'email' => [
                'required',
                'email',
                Rule::unique('users')->ignore($this->member? $this->member->id : 0, 'id')
            ],
            'phone'=> [
                "required",
                "numeric",
                'regex:'.$phonePattern,
                Rule::unique('users')->ignore($this->member? $this->member->id : 0, 'id')
            ],
            'status'=> 'nullable|in:1,0',
//            'region_id'=> 'required_if:role,provider|nullable|exists:regions,id',
            'city_id'=> 'required|exists:cities,id',
            'birth_date'=> 'required|date',
            'gender'=> 'required|in:male,female',
//            'sector_id'=> 'required_if:role,provider|nullable|exists:sectors,id',
//            'street'=> 'required_if:role,provider|nullable|min:3|max:200',


        ];

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

        $rules['photo'] = 'sometimes';
        $rules['commercial_file'] = 'required_if:role,provider';

        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $field = metaFields('members');
        $local = getCurrentLocale();
        $attributes= [
            'role'=> __('members.member_type'),
            'name'=> $field[$local]['name'] ?? __('members.name'),
            'region_id'=> $field[$local]['region_id'] ?? __('members.region_id'),
            'city_id'=> $field[$local]['city_id'] ?? __('members.city_id'),
            'sector_id'=> $field[$local]['sector_id'] ?? __('members.sector_id'),
            'street'=> $field[$local]['street'] ?? __('members.street'),
            'email'=> $field[$local]['email'] ?? __('members.email'),
            'phone'=> $field[$local]['phone'] ?? __('members.phone'),
            'status'=> $field[$local]['status'] ?? __('members.status'),
            'birth_date'=> $field[$local]['birth_date'] ?? __('members.birth_date'),
            'gender'=> $field[$local]['gender'] ?? __('members.gender'),
            'password'=> $field[$local]['password'] ?? __('members.password'),
            'photo'=> $field[$local]['photo'] ?? __('members.photo'),
        ];

        return $attributes;
    }

    public function messages()
    {
        return [
            'region_id.required_if'=>  __('members.region_id_required_if'),
            'city_id.required_if'=>  __('members.city_id_required_if'),
            'sector_id.required_if'=>  __('members.sector_id_required_if'),
            'street.required_if'=>  __('members.street_required_if'),
            'commercial_file.required_if'=>  __('members.commercial_file_required_if'),
        ];
    }

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