<?php

namespace App\Http\Requests;


use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        //dd($this->user->rol[0]->id);
        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'role_id' => 'required','username'=>'required',
            'area_id' => Rule::requiredIf($this->role_id == 3),
            'email' => ['required', 'string', 'email', 'max:255'],
            'username' => ['required', 'string', 'max:255', Rule::unique('users')->ignore($this->user)],
        ];
        
        if ($this->isMethod('POST') ) {
            $rules['password'] = ['required', 'string', 'confirmed'];
        }

        return $rules;
    }

    protected function passedValidation()
    {
        if ($this->isMethod('PUT') && !$this->filled('password')) {
            $this->request->remove('password');
        }
    }

    public function messages()
    {
        return [
            'name.required' => 'El nombre es obligatorio',
            'area_id.required' => 'Debe seleccionar una area de trabajo',
            'email.required' => 'El correo electrónico es obligatorio',
            'email.unique' => 'El correo electrónico ya existe',
            'password.required' => 'La contraseña es obligatoria',
            'password.confirmed' => 'La confirmación de la contraseña no coincide',
            'role_id.required' => 'Debe asignar un rol',
            'username.required' => 'El nombre de usuario es obligatorio',
            'username.unique' => 'El nombre de usuario ya existe',
        ];
    }
}
