<?php

namespace App\Http\Requests\Api;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use App\Product;

class EditProfileRequest 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()
    {
        $rules=[
            'photo' => 'sometimes',
            'name'=> 'required|min:3',
            
            'email' => [
                'required',
                'email',
                Rule::unique('users')->ignore(\Auth::user()->id? \Auth::user()->id : 0, 'id')
            ],
            'phone'=> [
                "required",
                "numeric",
                "digits_between:9,14",
                Rule::unique('users')->ignore(\Auth::user()->id? \Auth::user()->id : 0, 'id')
            ],
        ];

        
        
        
        if(request('role') == 'member')
        {
            $lang_rules=[
                
               'type_id'=>'required',
               'relative'=>'required',
               'age'=>'required',
               

            ];
            $rules= array_merge($rules, $lang_rules);
        }
        else{
            $lang_rules=[
               'country_id'=>'required',
               'category_id'=>'required',
               'gender'=>'required',
               'experience.*.name_ar'=> 'required',
            'certification.*.name_ar'=> 'required',
               'experience.*.name_en'=> 'required',
            'certification.*.name_en'=> 'required',
               'experience.*.image'=> 'required',
            'certification.*.image'=> 'required',

            ];
            $rules= array_merge($rules, $lang_rules);
        }

        

        return $rules;
    }

    /**
     * Handle a failed validation attempt.
     *
     * Override the parent method action if the request is for AJAX
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        // Change response attitude if the request done via Ajax requests like API requests
        
            $errors = (new ValidationException($validator))->errors();
            $message = $validator->errors()->first();
            throw new HttpResponseException(response()->json(['message'=> $message, 'errors' => $errors],  400));
       
    }
}