<?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 MembersRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
       public function rules()
    {
        if(\Auth::guard('member')->user()){
        $email ='required|unique:members,email,'.\Auth::guard('member')->user()->id;
        }
        else{
        $email = 'sometimes|required|unique:members,email';
        }
        
        if(\Auth::guard('member')->user()){
        $phone ='required|unique:members,phone,'.\Auth::guard('member')->user()->id;
        }
        else{
        $phone = 'sometimes|required|unique:members,phone';
        }
        
        $rules = [
            'email'=>$email,
            'phone'=>$phone,
            'password'=>'required',
            'username'=>'required',
            'city'=>'required',
            'gender'=>'required',
            ];
        return $rules;
    }
    public function attributes()
    {
        return [
            'email.required'=>__('members.email'),
            'phone.required'=>__('members.phone'),
            'password.required'=>__('members.password'),
            'username.required'=>__('members.username'),
            'package.required'=>__('members.package'),
            'full_name.required'=>__('site.full_name'),
            'city.required'=>__('site.city'),
            'gender.required'=>__('site.gender'),
           
        ];
    }
    /**
     * 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);
        }
    }
}

