<?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 MemberRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
         if (! Auth::check()) {
            return false;
        }
        if(Auth::user()->role == 'admin' )
        {
            return true;
        }

        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        
        return [
            'email' => [
                'required',
                'email',
                Rule::unique('members')->ignore($this->member? $this->member->id : 0, 'id')
            ],
            'password'=>'sometimes',
            'username'=>'required',
            'full_name'=>'required',
            'gender'=>'required',
            'job'=>'required',
            'city'=>'required',
           'phone'=> [
                "required",
                "numeric",
                "digits_between:11,14",
                Rule::unique('members')->ignore($this->member? $this->member->id : 0, 'id')
            ],
        ];
    }
    public function attributes()
    {
        return [
            'email.required'=>__('members.email'),
            'password.required'=>__('members.password'),
            'username.required'=>__('members.username'),
            'full_name.required'=>__('members.full_name'),
            'gender.required'=>__('members.gender'),
            'job.required'=>__('members.job'),
            'city.required'=>__('members.city'),
            'phone.required'=>__('members.phone'),
        ];
    }
    /**
     * 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);
        }
    }
}




