<?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
    {
        $rules = [
            'name' => ['required', 'string', 'max:255'],
            'role_id' => 'required',
            'empleado_ci'=>'required',
            'unidad_id'=>'required',
            'cargo'=>'required',
            'email' => ['required', 'string', 'email'],
        ];
        
        if ($this->isMethod('POST')) {
            $rules['password'] = ['required', 'string', 'confirmed'];
            $rules['username'] = ['required', 'string', 'max:255', Rule::unique('users')->ignore($this->user)];
        }

        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',
            'username.required' => 'El nombre de usuario es obligatorio',
            'password.required' => 'La contraseña es obligatoria',
            'password.confirmed' => 'La confirmación de la contraseña no coincide',
            'empleado_id.required_if' => 'El empleado es obligatorio',
            'role_id.required' => 'El rol es obligatorio',
            'username.unique' => 'El nombre de usuario ya existe',
        ];
    }
}
