<?php
namespace App\Livewire\Admin;

use App\Models\User;
use Livewire\Component;
use Illuminate\Support\Facades\Hash;

class GestionUsuarios extends Component
{
    public string $nuevoNombre    = '';
    public string $nuevoEmail     = '';
    public string $nuevoPassword  = '';
    public string $nuevoRol       = '';
    public string $busqueda       = '';

    public function crearUsuario(): void
    {
        $this->validate([
            'nuevoNombre'   => 'required|string|min:3|max:100',
            'nuevoEmail'    => 'required|email|unique:users,email',
            'nuevoPassword' => 'required|string|min:8',
            'nuevoRol'      => 'required|in:asociado,evaluador,junta,admin',
        ]);

        $user = User::create([
            'name'              => $this->nuevoNombre,
            'email'             => $this->nuevoEmail,
            'password'          => Hash::make($this->nuevoPassword),
            'email_verified_at' => now(),
            'estado'            => 'activo',
        ]);

        $user->assignRole($this->nuevoRol);

        session()->flash('success', "Usuario {$this->nuevoNombre} creado con rol {$this->nuevoRol}.");
        $this->reset(['nuevoNombre', 'nuevoEmail', 'nuevoPassword', 'nuevoRol']);
    }

    public function toggleEstado(int $userId): void
    {
        $user = User::findOrFail($userId);
        if ($user->id === auth()->id()) return;
        $user->update([
            'estado' => ($user->estado ?? 'activo') === 'activo' ? 'inactivo' : 'activo',
        ]);
    }

    public function render()
    {
        $usuarios = User::with('roles')
            ->when($this->busqueda, fn($q) => $q->where('name', 'like', "%{$this->busqueda}%")
                ->orWhere('email', 'like', "%{$this->busqueda}%"))
            ->orderBy('name')
            ->get();

        return view('admin.gestion-usuarios', compact('usuarios'))
            ->layout('layouts.fempha');
    }
}