<?php

namespace Modules\User\Requests\Employee;

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\Enums\UserTargetEnum;
use Modules\User\Services\UserService;

class EmployeeRequest 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::employees();
        if (! Auth::check()) {
            return false;
        }
        if(!in_array(Auth::user()->role, $role))
        {
            return false;
        }
        if(Auth::user()->hasModule('employees'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $statuses = UserTargetEnum::values();
        $roles = UserRoleEnum::employees();
        $user = $this->userService->getItem($this->employee ?? 0 );
        if($user)
        {
            if($user->lock)
            {
                return [
                    'locked'=>'required'
                ];
            }
        }
        $rules =
        [
            'name'=>
            [
                'required',
                'string'
            ],
            'email'=>
            [
                'required',
                'email',
                Rule::unique('users','email')->ignore($this->employee ?? null)
            ],
            'phone'=>
            [
                'nullable',
                'numeric',
                Rule::unique('users','phone')->ignore($this->employee ?? null)
            ],
            'role'=>
            [
                'required',
                'in:'.implode(',',$roles)
            ],
            'phone_country_id'=>
            [
                'required',
                Rule::exists('countries','id')->whereNull('deleted_at')
            ],
            'sector_id'=>
            [
                'required',
                'array'
            ],
            'sector_id.*'=>
            [
                'required',
                Rule::exists('sectors','id')->whereNull('deleted_at')
            ],
            'password'=>
            [
                $this->employee ? 'sometimes' : 'required',
                'confirmed'
            ],
            'modules'=>
            [
                'nullable',
                'array',
                Rule::exists('modules', 'id')->whereNull('deleted_at'),
            ]
        ];

        if(in_array(request('role'),UserRoleEnum::sub_employees()))
        {
            $rules['manager_id'] =
            [
                'required',
                Rule::exists('users','id')->whereIn('role',UserRoleEnum::values())->whereNull('deleted_at')
            ];
        }

        return $rules;
    }


    public function messages()
    {
        return [
            'locked.required'=>__('dashboard.locked'),
        ];
    }

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

        $attributes= [
            'name'=>__('users.name'),
            'email'=>__('users.email'),
            'phone'=>__('users.phone'),
            'photo'=>__('users.photo'),
            'role'=>__('users.role'),
            'phone_country_id'=>__('users.phone_country_id'),
            'sector_id'=>__('users.sector_id'),
            'password'=>__('users.password'),
            'password_confirmation'=>__('users.password_confirmation'),
            'target_status'=>__('employees.target_status'),
            'target'=>__('employees.target'),
            'manager_id'=>__('employees.manager_id')
        ];

        return $attributes;
    }


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

    }
}
