<?php

namespace Modules\User\Requests\Admin;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Models\Module;
use Modules\User\Services\UserService;

class MemberRequest extends FormRequest
{
    public function __construct(
        private UserService $userService,
    )
    {}
    
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $role = UserRoleEnum::admins();
        if (! Auth::check()) {
            return false;
        }
        if(!in_array(Auth::user()->role, $role))
        {
            return false;
        }
        if(Auth::user()->hasModule('members'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        // dump('rules');
        $re = config('globals.phone_regex');
        $rules=[
            'photo' => 'sometimes|image',
            'name'=> 'required|min:3|max:50',
            'active'=> 'required|integer|min:0|max:1',
            'role'=> 'required|in:'.UserRoleEnum::USER->value,
            'phone'=> [
                "required",
                "regex:".$re,
                Rule::unique('users')->ignore($this->user ?? 0, 'code')
            ],
            'email'=> [
                "required",
                "email",
                "max:100",
                Rule::unique('users')->ignore($this->user ?? 0, 'code')
            ],
            'password'=>[
                $this->user ? 'sometimes' : 'required',
                'confirmed'
            ]
        ];
        // dd($rules);
        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {

        $attributes= [
            'name'=>__('users.name'),
            'email'=>__('users.email'),
            'phone'=>__('users.phone'),
            'photo'=>__('users.photo'),
            'password'=>__('users.password'),
            'password_confirmation'=>__('users.password_confirmation'),

        ];

        return $attributes;
    }

    /**
     * Add some data to be validated
     */
    public function validationData()
    {
        $data = parent::all();
        // dump($this->user);
        $user = $this->user ? $this->userService->getItemByCode($this->user) : null;
        $this->user= $user;
        $data['role'] = $user->role ?? UserRoleEnum::USER->value;
        if ($user && request()->user()->id == $user->id) {
            $data['active'] = request()->user()->active;
        }
        $data['active'] = 1;
        if($data['phone'] ?? null){
            $data['phone'] = validatePhone($this->phone ?? '') ?? 'asas';// any invalid default value
        }
        // dump($data);
        $this->replace($data); // < VIP line
        return parent::all();
    }
    public function getValidatorInstance()
    {
        $this->merge($this->validationData());
    
        return parent::getValidatorInstance();
    }
    /**
     * 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);
        }
    }
}
