<?php
require_once __DIR__ . '/../../config/bootstrap.php';
require_once __DIR__ . '/../../includes/require-auth.php';

use App\Services\AuthService;
use App\Services\SecurityService;
use App\Services\Database;
use App\Services\Logger;

$auth = new AuthService();
$security = new SecurityService();
$db = Database::getInstance();
$logger = new Logger();

$user = requireAuth($auth);
$adminId = $user['id'];
$rol = $user['rol'] ?? 'asesor';

// Solo administradores pueden gestionar usuarios
requireRole('administrador', $rol);

$csrfToken = $security->generateCSRFToken();

$success = '';
$error = '';

// ============================================================
// Procesar acciones POST
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if (!$security->verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'Token de seguridad inválido. Recarga la página.';
    } else {
        switch ($action) {

            case 'create':
                $nombre  = $security->sanitizeString($_POST['nombre'] ?? '');
                $email   = $security->sanitizeEmail($_POST['email'] ?? '');
                $pass    = $_POST['password'] ?? '';
                $pass2   = $_POST['password_confirm'] ?? '';
                $rolNuevo = in_array($_POST['rol'] ?? '', ['administrador', 'asesor']) ? $_POST['rol'] : 'asesor';

                if (empty($nombre) || empty($email) || empty($pass)) {
                    $error = 'Todos los campos son obligatorios.';
                } elseif (!$security->validateEmail($email)) {
                    $error = 'El correo electrónico no es válido.';
                } elseif (strlen($pass) < 8) {
                    $error = 'La contraseña debe tener al menos 8 caracteres.';
                } elseif ($pass !== $pass2) {
                    $error = 'Las contraseñas no coinciden.';
                } elseif ($db->exists('admins', 'email = :email', [':email' => $email])) {
                    $error = 'Ya existe un usuario con ese correo electrónico.';
                } else {
                    $db->insert('admins', [
                        'email'    => $email,
                        'password' => $security->hashPassword($pass),
                        'nombre'   => $nombre,
                        'rol'      => $rolNuevo,
                        'activo'   => 1
                    ]);
                    $logger->logAdminAccess($adminId, 'user_created', "Admin creó usuario: {$email}", ['email' => $email, 'rol' => $rolNuevo]);
                    $success = "Usuario <strong>{$nombre}</strong> creado como <strong>{$rolNuevo}</strong>.";
                }
                break;

            case 'edit':
                $targetId  = (int) ($_POST['user_id'] ?? 0);
                $nombre    = $security->sanitizeString($_POST['nombre'] ?? '');
                $email     = $security->sanitizeEmail($_POST['email'] ?? '');
                $pass      = $_POST['password'] ?? '';
                $rolNuevo  = in_array($_POST['rol'] ?? '', ['administrador', 'asesor']) ? $_POST['rol'] : null;

                if ($targetId <= 0 || empty($nombre) || empty($email)) {
                    $error = 'Datos inválidos.';
                } elseif (!$security->validateEmail($email)) {
                    $error = 'El correo electrónico no es válido.';
                } elseif ($db->exists('admins', 'email = :email AND id != :id', [':email' => $email, ':id' => $targetId])) {
                    $error = 'Ese correo ya lo usa otro usuario.';
                } else {
                    $updateData = ['nombre' => $nombre, 'email' => $email];
                    if ($rolNuevo) {
                        $updateData['rol'] = $rolNuevo;
                    }
                    if (!empty($pass)) {
                        if (strlen($pass) < 8) {
                            $error = 'La nueva contraseña debe tener al menos 8 caracteres.';
                            break;
                        }
                        $updateData['password'] = $security->hashPassword($pass);
                        // Cerrar sesiones activas del usuario editado si se cambia contraseña
                        $db->delete('sessions', 'admin_id = :id', [':id' => $targetId]);
                    }
                    $db->update('admins', $updateData, 'id = :id', [':id' => $targetId]);
                    $logger->logAdminAccess($adminId, 'user_edited', "Admin editó usuario ID:{$targetId}", ['target_id' => $targetId]);
                    $success = "Usuario actualizado correctamente.";
                }
                break;

            case 'toggle':
                $targetId = (int) ($_POST['user_id'] ?? 0);
                if ($targetId === $adminId) {
                    $error = 'No puedes desactivarte a ti mismo.';
                } elseif ($targetId > 0) {
                    $target = $db->fetchOne("SELECT * FROM admins WHERE id = :id", [':id' => $targetId]);
                    if ($target) {
                        $newState = $target['activo'] ? 0 : 1;
                        $db->update('admins', ['activo' => $newState], 'id = :id', [':id' => $targetId]);
                        if (!$newState) {
                            // Cerrar todas las sesiones activas del usuario desactivado
                            $db->delete('sessions', 'admin_id = :id', [':id' => $targetId]);
                        }
                        $stateLabel = $newState ? 'activado' : 'desactivado';
                        $logger->logAdminAccess($adminId, 'user_toggle', "Admin {$stateLabel} usuario ID:{$targetId}", ['target_id' => $targetId, 'new_state' => $newState]);
                        $success = "Usuario <strong>{$target['nombre']}</strong> {$stateLabel} correctamente.";
                    }
                }
                break;

            case 'delete':
                $targetId = (int) ($_POST['user_id'] ?? 0);
                if ($targetId === $adminId) {
                    $error = 'No puedes eliminar tu propia cuenta.';
                } elseif ($targetId > 0) {
                    $target = $db->fetchOne("SELECT * FROM admins WHERE id = :id", [':id' => $targetId]);
                    if ($target) {
                        $db->delete('sessions', 'admin_id = :id', [':id' => $targetId]);
                        $db->delete('admins', 'id = :id', [':id' => $targetId]);
                        $logger->logAdminAccess($adminId, 'user_deleted', "Admin eliminó usuario: {$target['email']}", ['deleted_email' => $target['email']]);
                        $success = "Usuario eliminado permanentemente.";
                    }
                }
                break;
        }
    }
}

// ============================================================
// Obtener listado de usuarios
// ============================================================
$search = $security->sanitizeString($_GET['search'] ?? '');
$filterActivo = $_GET['activo'] ?? '';

$where = '1=1';
$params = [];
if (!empty($search)) {
    $where .= ' AND (nombre LIKE :search OR email LIKE :search2)';
    $params[':search']  = "%{$search}%";
    $params[':search2'] = "%{$search}%";
}
if ($filterActivo !== '') {
    $where .= ' AND activo = :activo';
    $params[':activo'] = (int) $filterActivo;
}

$usuarios = $db->fetchAll("SELECT * FROM admins WHERE {$where} ORDER BY created_at DESC", $params);

// Estadísticas de sesiones activas por usuario
$sesionesActivas = $db->fetchAll(
    "SELECT admin_id, COUNT(*) as total FROM sessions WHERE expires_at > NOW() GROUP BY admin_id"
);
$sesionesMap = [];
foreach ($sesionesActivas as $s) {
    $sesionesMap[$s['admin_id']] = $s['total'];
}

// Contar logs por usuario (actividad últimos 30 días)
$actividadLogs = $db->fetchAll(
    "SELECT usuario_id, COUNT(*) as total FROM access_logs
     WHERE usuario_id IS NOT NULL AND created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
     GROUP BY usuario_id"
);
$actividadMap = [];
foreach ($actividadLogs as $a) {
    $actividadMap[$a['usuario_id']] = $a['total'];
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestión de Usuarios - Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        * { font-family: 'Inter', sans-serif; -webkit-font-smoothing: antialiased; letter-spacing: -0.011em; }
        .modal-bg { transition: opacity 0.2s ease; }
        .modal-box { transition: transform 0.2s ease, opacity 0.2s ease; }
    </style>
</head>
<body class="bg-gray-50 flex flex-col min-h-screen">

    <?php include __DIR__ . '/../../includes/admin-nav.php'; ?>

    <main class="flex-1 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 w-full">

        <!-- Header -->
        <div class="mb-8 flex items-center justify-between">
            <div>
                <h1 class="text-3xl font-bold text-gray-900">Gestión de Usuarios</h1>
                <p class="mt-1 text-sm text-gray-600">Administra los accesos al panel de control</p>
            </div>
            <button onclick="openModal('modalCrear')" class="inline-flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-medium transition">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                </svg>
                Nuevo Usuario
            </button>
        </div>

        <!-- Alertas -->
        <?php if ($success): ?>
        <div class="mb-6 bg-green-50 border border-green-200 rounded-lg p-4 flex items-start gap-3">
            <svg class="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
            </svg>
            <p class="text-green-800 text-sm"><?= $success ?></p>
        </div>
        <?php endif; ?>
        <?php if ($error): ?>
        <div class="mb-6 bg-red-50 border border-red-200 rounded-lg p-4 flex items-start gap-3">
            <svg class="w-5 h-5 text-red-500 mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
            </svg>
            <p class="text-red-800 text-sm"><?= htmlspecialchars($error) ?></p>
        </div>
        <?php endif; ?>

        <!-- Stats cards -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-6 mb-6">
            <?php
            $totalUsuarios  = count($usuarios);
            $totalActivos   = count(array_filter($usuarios, fn($u) => $u['activo']));
            $totalInactivos = $totalUsuarios - $totalActivos;
            ?>
            <div class="bg-white rounded-lg shadow p-6 flex items-center gap-4">
                <div class="bg-indigo-100 rounded-lg p-3">
                    <svg class="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/>
                    </svg>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Total Usuarios</p>
                    <p class="text-2xl font-bold text-gray-900"><?= $totalUsuarios ?></p>
                </div>
            </div>
            <div class="bg-white rounded-lg shadow p-6 flex items-center gap-4">
                <div class="bg-green-100 rounded-lg p-3">
                    <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Activos</p>
                    <p class="text-2xl font-bold text-green-700"><?= $totalActivos ?></p>
                </div>
            </div>
            <div class="bg-white rounded-lg shadow p-6 flex items-center gap-4">
                <div class="bg-red-100 rounded-lg p-3">
                    <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/>
                    </svg>
                </div>
                <div>
                    <p class="text-sm text-gray-500">Inactivos</p>
                    <p class="text-2xl font-bold text-red-700"><?= $totalInactivos ?></p>
                </div>
            </div>
        </div>

        <!-- Filtros -->
        <div class="bg-white rounded-lg shadow mb-6 p-4">
            <form method="GET" class="flex flex-col sm:flex-row gap-3">
                <div class="relative flex-1">
                    <input type="text" name="search" placeholder="Buscar por nombre o email..."
                        value="<?= htmlspecialchars($search) ?>"
                        class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent text-sm">
                    <svg class="absolute left-3 top-2.5 h-4 w-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                    </svg>
                </div>
                <select name="activo" onchange="this.form.submit()" class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                    <option value="">Todos los estados</option>
                    <option value="1" <?= $filterActivo === '1' ? 'selected' : '' ?>>Activos</option>
                    <option value="0" <?= $filterActivo === '0' ? 'selected' : '' ?>>Inactivos</option>
                </select>
                <button type="submit" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium transition">
                    Buscar
                </button>
                <?php if ($search || $filterActivo !== ''): ?>
                <a href="<?= base_url('admin/usuarios') ?>" class="px-4 py-2 text-gray-500 hover:text-gray-700 text-sm font-medium">Limpiar</a>
                <?php endif; ?>
            </form>
        </div>

        <!-- Tabla de usuarios -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Usuario</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Rol</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Estado</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Sesiones</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actividad (30d)</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Último Login</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Registrado</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Acciones</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($usuarios)): ?>
                    <tr>
                        <td colspan="8" class="px-6 py-12 text-center text-gray-500">
                            <svg class="mx-auto h-12 w-12 text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/>
                            </svg>
                            <p class="text-sm">No se encontraron usuarios</p>
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($usuarios as $u): ?>
                    <tr class="hover:bg-gray-50 <?= !$u['activo'] ? 'opacity-60' : '' ?>">
                        <td class="px-6 py-4">
                            <div class="flex items-center gap-3">
                                <div class="w-9 h-9 rounded-full flex items-center justify-center text-white font-semibold text-sm
                                    <?= $u['activo'] ? 'bg-indigo-500' : 'bg-gray-400' ?>">
                                    <?= strtoupper(substr($u['nombre'], 0, 1)) ?>
                                </div>
                                <div>
                                    <div class="text-sm font-semibold text-gray-900 flex items-center gap-1">
                                        <?= htmlspecialchars($u['nombre']) ?>
                                        <?php if ($u['id'] === $adminId): ?>
                                        <span class="text-xs bg-indigo-100 text-indigo-700 px-1.5 py-0.5 rounded">Tú</span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="text-xs text-gray-500"><?= htmlspecialchars($u['email']) ?></div>
                                    <div class="text-xs text-gray-400">#<?= str_pad($u['id'], 4, '0', STR_PAD_LEFT) ?></div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <?php if (($u['rol'] ?? 'asesor') === 'administrador'): ?>
                            <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold bg-violet-100 text-violet-800">
                                Administrador
                            </span>
                            <?php else: ?>
                            <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold bg-blue-100 text-blue-700">
                                Asesor
                            </span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4">
                            <?php if ($u['activo']): ?>
                            <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-800">
                                <span class="w-1.5 h-1.5 rounded-full bg-green-500"></span> Activo
                            </span>
                            <?php else: ?>
                            <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold bg-gray-100 text-gray-600">
                                <span class="w-1.5 h-1.5 rounded-full bg-gray-400"></span> Inactivo
                            </span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4">
                            <?php $ses = $sesionesMap[$u['id']] ?? 0; ?>
                            <?php if ($ses > 0): ?>
                            <span class="inline-flex items-center gap-1 text-xs font-medium text-emerald-700 bg-emerald-50 px-2 py-1 rounded">
                                <span class="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
                                <?= $ses ?> activa<?= $ses > 1 ? 's' : '' ?>
                            </span>
                            <?php else: ?>
                            <span class="text-xs text-gray-400">Sin sesión</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4">
                            <span class="text-sm text-gray-700 font-medium"><?= number_format($actividadMap[$u['id']] ?? 0) ?></span>
                            <span class="text-xs text-gray-400 ml-1">acciones</span>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-500">
                            <?= $u['ultimo_login'] ? date('d/m/Y H:i', strtotime($u['ultimo_login'])) : '<span class="text-gray-400 italic text-xs">Nunca</span>' ?>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-500">
                            <?= date('d/m/Y', strtotime($u['created_at'])) ?>
                        </td>
                        <td class="px-6 py-4 text-right">
                            <div class="flex items-center justify-end gap-2">
                                <!-- Editar -->
                                <button onclick="openEditModal(<?= htmlspecialchars(json_encode([
                                    'id'     => $u['id'],
                                    'nombre' => $u['nombre'],
                                    'email'  => $u['email'],
                                    'rol'    => $u['rol'] ?? 'asesor'
                                ])) ?>)"
                                    class="text-indigo-600 hover:text-indigo-900 text-sm font-medium">
                                    Editar
                                </button>
                                <?php if ($u['id'] !== $adminId): ?>
                                <!-- Activar/Desactivar -->
                                <form method="POST" class="inline">
                                    <input type="hidden" name="csrf_token" value="<?= $csrfToken ?>">
                                    <input type="hidden" name="action" value="toggle">
                                    <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                    <button type="submit"
                                        class="text-sm font-medium <?= $u['activo'] ? 'text-yellow-600 hover:text-yellow-800' : 'text-green-600 hover:text-green-800' ?>">
                                        <?= $u['activo'] ? 'Desactivar' : 'Activar' ?>
                                    </button>
                                </form>
                                <!-- Eliminar -->
                                <button onclick="confirmDelete(<?= $u['id'] ?>, '<?= htmlspecialchars(addslashes($u['nombre'])) ?>')"
                                    class="text-red-600 hover:text-red-800 text-sm font-medium">
                                    Eliminar
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

    </main>

    <!-- ============================================================ -->
    <!-- Modal: Crear Usuario -->
    <!-- ============================================================ -->
    <div id="modalCrear" class="fixed inset-0 z-50 hidden">
        <div class="modal-bg absolute inset-0 bg-black/50" onclick="closeModal('modalCrear')"></div>
        <div class="relative flex items-center justify-center min-h-screen p-4">
            <div class="modal-box bg-white rounded-xl shadow-2xl w-full max-w-md">
                <div class="px-6 py-5 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900">Crear Nuevo Usuario</h3>
                    <p class="text-sm text-gray-500 mt-1">El usuario tendrá acceso completo al panel de administración.</p>
                </div>
                <form method="POST" class="px-6 py-5 space-y-4">
                    <input type="hidden" name="csrf_token" value="<?= $csrfToken ?>">
                    <input type="hidden" name="action" value="create">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Nombre completo *</label>
                        <input type="text" name="nombre" required placeholder="Ej: Juan García"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Correo electrónico *</label>
                        <input type="email" name="email" required placeholder="usuario@ejemplo.com"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Rol *</label>
                        <select name="rol" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                            <option value="asesor">Asesor — solo ve sus contratos</option>
                            <option value="administrador">Administrador — ve todos los contratos</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Contraseña *</label>
                        <input type="password" name="password" required minlength="8" placeholder="Mínimo 8 caracteres"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Confirmar contraseña *</label>
                        <input type="password" name="password_confirm" required minlength="8" placeholder="Repite la contraseña"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                    <div class="flex justify-end gap-3 pt-2">
                        <button type="button" onclick="closeModal('modalCrear')"
                            class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50">
                            Cancelar
                        </button>
                        <button type="submit"
                            class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700">
                            Crear Usuario
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- ============================================================ -->
    <!-- Modal: Editar Usuario -->
    <!-- ============================================================ -->
    <div id="modalEditar" class="fixed inset-0 z-50 hidden">
        <div class="modal-bg absolute inset-0 bg-black/50" onclick="closeModal('modalEditar')"></div>
        <div class="relative flex items-center justify-center min-h-screen p-4">
            <div class="modal-box bg-white rounded-xl shadow-2xl w-full max-w-md">
                <div class="px-6 py-5 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-900">Editar Usuario</h3>
                    <p class="text-sm text-gray-500 mt-1">Deja la contraseña vacía para no cambiarla.</p>
                </div>
                <form method="POST" class="px-6 py-5 space-y-4">
                    <input type="hidden" name="csrf_token" value="<?= $csrfToken ?>">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="user_id" id="editUserId">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Nombre completo *</label>
                        <input type="text" name="nombre" id="editNombre" required
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Correo electrónico *</label>
                        <input type="email" name="email" id="editEmail" required
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Rol</label>
                        <select name="rol" id="editRol" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                            <option value="asesor">Asesor — solo ve sus contratos</option>
                            <option value="administrador">Administrador — ve todos los contratos</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Nueva contraseña <span class="text-gray-400">(opcional)</span></label>
                        <input type="password" name="password" minlength="8" placeholder="Dejar vacío para no cambiar"
                            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                    <div class="flex justify-end gap-3 pt-2">
                        <button type="button" onclick="closeModal('modalEditar')"
                            class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50">
                            Cancelar
                        </button>
                        <button type="submit"
                            class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700">
                            Guardar Cambios
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- ============================================================ -->
    <!-- Modal: Confirmar Eliminar -->
    <!-- ============================================================ -->
    <div id="modalEliminar" class="fixed inset-0 z-50 hidden">
        <div class="modal-bg absolute inset-0 bg-black/50" onclick="closeModal('modalEliminar')"></div>
        <div class="relative flex items-center justify-center min-h-screen p-4">
            <div class="modal-box bg-white rounded-xl shadow-2xl w-full max-w-sm">
                <div class="px-6 pt-6 pb-2 text-center">
                    <div class="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
                        </svg>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-900">Eliminar Usuario</h3>
                    <p class="text-sm text-gray-500 mt-2">¿Estás seguro de eliminar a <strong id="deleteUserName"></strong>? Esta acción no se puede deshacer.</p>
                </div>
                <form method="POST" class="px-6 pb-6">
                    <input type="hidden" name="csrf_token" value="<?= $csrfToken ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="user_id" id="deleteUserId">
                    <div class="flex gap-3 mt-4">
                        <button type="button" onclick="closeModal('modalEliminar')"
                            class="flex-1 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50">
                            Cancelar
                        </button>
                        <button type="submit"
                            class="flex-1 px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700">
                            Sí, eliminar
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
    function openModal(id) {
        document.getElementById(id).classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }
    function closeModal(id) {
        document.getElementById(id).classList.add('hidden');
        document.body.style.overflow = '';
    }
    function openEditModal(data) {
        document.getElementById('editUserId').value = data.id;
        document.getElementById('editNombre').value = data.nombre;
        document.getElementById('editEmail').value = data.email;
        document.getElementById('editRol').value = data.rol || 'asesor';
        openModal('modalEditar');
    }
    function confirmDelete(id, nombre) {
        document.getElementById('deleteUserId').value = id;
        document.getElementById('deleteUserName').textContent = nombre;
        openModal('modalEliminar');
    }
    // Abrir modal de crear si hay error de creación (para mantener UX)
    <?php if ($error && isset($_POST['action']) && $_POST['action'] === 'create'): ?>
    openModal('modalCrear');
    <?php endif; ?>
    </script>

    <?php include __DIR__ . '/../../includes/admin-footer.php'; ?>
</body>
</html>
