<?php
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

// 1. Seguridad: Solo Admin
if (!isset($_SESSION['usuario_id']) || $_SESSION['usuario_rol'] != ROL_ADMIN) {
    header("Location: ../../index.php");
    exit();
}

// 2. PROCESAR CREACIÓN DE USUARIO (POST)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['accion']) && $_POST['accion'] == 'crear') {
    $nombre = limpiar($_POST['nombre']);
    $correo = limpiar($_POST['correo']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $rol = $_POST['rol'];

    // Verificar si el correo ya existe
    $check = $pdo->prepare("SELECT id FROM usuarios WHERE correo = ?");
    $check->execute([$correo]);
    
    if ($check->rowCount() > 0) {
        header("Location: usuarios.php?msg=correo_duplicado");
    } else {
        $stmt = $pdo->prepare("INSERT INTO usuarios (nombre, correo, password, id_rol, fecha_creacion) VALUES (?, ?, ?, ?, NOW())");
        if ($stmt->execute([$nombre, $correo, $password, $rol])) {
            header("Location: usuarios.php?msg=creado_ok");
        } else {
            header("Location: usuarios.php?msg=error");
        }
    }
    exit();
}

// 3. PROCESAR CAMBIO DE CONTRASEÑA
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id_usuario_pass'])) {
    $id_u = $_POST['id_usuario_pass'];
    $pass = $_POST['nueva_password'];

    if (!empty($pass)) {
        $hashed_password = password_hash($pass, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE usuarios SET password = ? WHERE id = ?");
        $stmt->execute([$hashed_password, $id_u]);
        header("Location: usuarios.php?msg=pass_ok");
    }
    exit();
}

// 4. Obtener lista de usuarios
$usuarios = $pdo->query("SELECT id, nombre, correo, id_rol FROM usuarios ORDER BY nombre ASC")->fetchAll();

include '../layout/header.php';
?>

<div class="max-w-6xl mx-auto px-4 py-8">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4">
        <div>
            <h1 class="text-3xl font-bold text-slate-800 tracking-tight">Personal Institucional</h1>
            <p class="text-sm text-slate-500">Administración de accesos al Sistema TIC</p>
        </div>
        <button onclick="abrirModalCrear()" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-xl font-bold shadow-lg shadow-blue-200 transition flex items-center gap-2">
            <i class="fas fa-user-plus"></i> Registrar Usuario
        </button>
    </div>

    <?php if(isset($_GET['msg'])): ?>
        <?php 
            $alertas = [
                'creado_ok' => ['bg-green-100', 'text-green-700', '¡Usuario creado correctamente!'],
                'pass_ok'   => ['bg-blue-100', 'text-blue-700', '¡Contraseña actualizada!'],
                'correo_duplicado' => ['bg-red-100', 'text-red-700', 'El correo ya está registrado.'],
                'error'     => ['bg-red-100', 'text-red-700', 'Ocurrió un error inesperado.']
            ];
            $m = $_GET['msg'];
            if(isset($alertas[$m])):
        ?>
        <div class="<?php echo $alertas[$m][0]; ?> border border-transparent p-4 rounded-xl mb-6 flex items-center gap-3 animate-bounce-short">
            <i class="fas fa-info-circle <?php echo $alertas[$m][1]; ?>"></i>
            <span class="text-sm font-bold <?php echo $alertas[$m][1]; ?>"><?php echo $alertas[$m][2]; ?></span>
        </div>
        <?php endif; ?>
    <?php endif; ?>

    <div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
        <table class="min-w-full divide-y divide-slate-100">
            <thead class="bg-slate-50">
                <tr>
                    <th class="px-6 py-4 text-left text-[10px] font-bold text-slate-400 uppercase tracking-widest">Nombre Completo</th>
                    <th class="px-6 py-4 text-left text-[10px] font-bold text-slate-400 uppercase tracking-widest">Correo Electrónico</th>
                    <th class="px-6 py-4 text-center text-[10px] font-bold text-slate-400 uppercase tracking-widest">Rol</th>
                    <th class="px-6 py-4 text-right text-[10px] font-bold text-slate-400 uppercase tracking-widest">Acción</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php foreach($usuarios as $u): ?>
                <tr class="hover:bg-slate-50/50 transition">
                    <td class="px-6 py-4 text-sm font-bold text-slate-700"><?php echo htmlspecialchars($u['nombre']); ?></td>
                    <td class="px-6 py-4 text-sm text-slate-500"><?php echo htmlspecialchars($u['correo']); ?></td>
                    <td class="px-6 py-4 text-center">
                        <span class="px-3 py-1 rounded-full text-[9px] font-black uppercase <?php echo ($u['id_rol'] == ROL_ADMIN) ? 'bg-purple-100 text-purple-600' : 'bg-slate-100 text-slate-500'; ?>">
                            <?php echo ($u['id_rol'] == ROL_ADMIN) ? 'ADMIN' : 'DOCENTE'; ?>
                        </span>
                    </td>
                    <td class="px-6 py-4 text-right">
                        <button onclick="abrirModalPass(<?php echo $u['id']; ?>, '<?php echo $u['nombre']; ?>')" 
                                class="text-slate-400 hover:text-blue-600 transition p-2">
                            <i class="fas fa-key"></i>
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div id="modalCrear" class="fixed inset-0 bg-slate-900/60 z-[60] hidden flex items-center justify-center backdrop-blur-sm p-4">
    <div class="bg-white w-full max-w-md rounded-2xl shadow-2xl animate-in zoom-in duration-200">
        <div class="p-6 border-b border-slate-100">
            <h3 class="text-xl font-bold text-slate-800">Nuevo Usuario</h3>
        </div>
        <form action="usuarios.php" method="POST" class="p-6 space-y-4">
            <input type="hidden" name="accion" value="crear">
            
            <div>
                <label class="text-[10px] font-bold text-slate-400 uppercase mb-1 block">Nombre y Apellido</label>
                <input type="text" name="nombre" required class="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 transition">
            </div>

            <div>
                <label class="text-[10px] font-bold text-slate-400 uppercase mb-1 block">Correo Institucional</label>
                <input type="correo" name="correo" required class="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 transition">
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="text-[10px] font-bold text-slate-400 uppercase mb-1 block">Contraseña</label>
                    <input type="password" name="password" required minlength="6" class="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 transition">
                </div>
                <div>
                    <label class="text-[10px] font-bold text-slate-400 uppercase mb-1 block">Rol</label>
                    <select name="rol" class="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 transition">
                        <option value="2">Docente</option>
                        <option value="1">Administrador</option>
                    </select>
                </div>
            </div>

            <div class="flex gap-3 pt-4">
                <button type="button" onclick="cerrarModalCrear()" class="flex-1 px-4 py-3 bg-slate-100 text-slate-600 rounded-xl font-bold text-sm">Cancelar</button>
                <button type="submit" class="flex-1 px-4 py-3 bg-blue-600 text-white rounded-xl font-bold text-sm hover:bg-blue-700 shadow-lg shadow-blue-200">Guardar</button>
            </div>
        </form>
    </div>
</div>

<div id="modalPass" class="fixed inset-0 bg-slate-900/60 z-[60] hidden flex items-center justify-center backdrop-blur-sm p-4">
    <div class="bg-white w-full max-w-md rounded-2xl shadow-2xl">
        <div class="p-6 border-b border-slate-100">
            <h3 class="text-lg font-bold text-slate-800">Resetear Contraseña</h3>
            <p id="labelUser" class="text-xs text-blue-600 font-bold mt-1"></p>
        </div>
        <form action="usuarios.php" method="POST" class="p-6 space-y-4">
            <input type="hidden" name="id_usuario_pass" id="id_usuario_pass">
            <input type="password" name="nueva_password" required placeholder="Nueva contraseña" class="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl">
            <div class="flex gap-3">
                <button type="button" onclick="cerrarModalPass()" class="flex-1 py-3 bg-slate-100 rounded-xl font-bold">Cancelar</button>
                <button type="submit" class="flex-1 py-3 bg-slate-800 text-white rounded-xl font-bold">Actualizar</button>
            </div>
        </form>
    </div>
</div>

<script>
function abrirModalCrear() { document.getElementById('modalCrear').classList.remove('hidden'); }
function cerrarModalCrear() { document.getElementById('modalCrear').classList.add('hidden'); }
function abrirModalPass(id, nombre) {
    document.getElementById('id_usuario_pass').value = id;
    document.getElementById('labelUser').innerText = nombre;
    document.getElementById('modalPass').classList.remove('hidden');
}
function cerrarModalPass() { document.getElementById('modalPass').classList.add('hidden'); }
</script>

<?php include '../layout/footer.php'; ?>