<?php
// FILE: /digitalpremium/pages/gestion_usuarios.php

if (session_status() === PHP_SESSION_NONE) session_start();

// Solo superadmin puede ver esta página
if (!isset($_SESSION['id_usuario']) || ($_SESSION['rol'] ?? '') !== 'superadmin') {
    header("Location: /digitalpremium/pages/dashboard.php?mensaje=" . urlencode("Acceso no autorizado.") . "&tipo=danger");
    exit();
}

$page_title = "Gestión de Usuarios - DigitalPremium";

// Token CSRF (reutiliza el ya existente si hay)
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

require_once __DIR__ . '/../config/db.php';

// Cargar usuarios + último login desde auditoría
try {
    $sql = $pdo->prepare("
        SELECT
            u.id_usuario,
            u.nombre_completo,
            u.username,
            u.rol,
            u.estado,
            u.fecha_fin_membresia,
            u.telefono,
            al.last_login
        FROM usuarios u
        LEFT JOIN (
            SELECT entidad_id, MAX(creado_en) AS last_login
            FROM auditoria_acciones
            WHERE accion = 'login' AND entidad = 'usuarios'
            GROUP BY entidad_id
        ) al ON al.entidad_id = u.id_usuario
        ORDER BY u.id_usuario DESC
    ");
    $sql->execute();
    $usuarios = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $usuarios = [];
    $error_carga = $e->getMessage();
}

// Roles soportados
$ROLES = [
    'superadmin' => 'Super Admin',
    'admin'      => 'Admin',
    'ventas'     => 'Ventas',
    'cortes'     => 'Cortes',
];

// Estados
$ESTADOS = [
    '1' => 'Activo',
    '0' => 'Inactivo',
];

include_once __DIR__ . '/../includes/header.php';
?>

<style>
/* --- TEMA VISUAL MEJORADO --- */
:root {
    --primary-color: #6a11cb;
    --secondary-color: #2575fc;
    --primary-gradient: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
    --background-color: #f0f2f5;
    --card-bg: #FFFFFF;
    --card-shadow: 0 10px 30px rgba(0, 0, 0, 0.07);
    --card-shadow-hover: 0 15px 40px rgba(37, 117, 252, 0.2);
    --text-dark: #333;
    --text-light: #888;
    --border-color: #e9ecef;
    --success-color: #20c997;
    --danger-color: #e74c3c;
    --warning-color: #ffc107;
    --card-border-radius: 1rem;
}

body { 
    background-color: var(--background-color); 
}

/* --- HEADER MEJORADO --- */
.page-header {
    background: var(--card-bg);
    border-radius: var(--card-border-radius);
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: var(--card-shadow);
    border: none;
}

.page-title {
    font-weight: 700;
    color: var(--text-dark);
    margin: 0;
    font-size: 1.8rem;
}

/* --- GRID DE USUARIOS --- */
.users-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.user-card {
    background: var(--card-bg);
    border-radius: var(--card-border-radius);
    box-shadow: var(--card-shadow);
    transition: all 0.3s ease;
    overflow: hidden;
    border: none;
}

.user-card:hover {
    transform: translateY(-5px);
    box-shadow: var(--card-shadow-hover);
}

/* --- HEADER DE LA CARD --- */
.user-card-header {
    background: var(--primary-gradient);
    color: white;
    padding: 1.5rem;
    position: relative;
}

.user-avatar {
    width: 60px;
    height: 60px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
    font-weight: 700;
    margin-bottom: 1rem;
    border: 3px solid rgba(255, 255, 255, 0.3);
}

.user-name {
    font-size: 1.3rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.user-username {
    font-size: 0.9rem;
    opacity: 0.8;
}

/* --- BADGES MEJORADOS --- */
.badge-role {
    position: absolute;
    top: 1rem;
    right: 1rem;
    font-weight: 600;
    border-radius: 50px;
    padding: 0.4rem 0.8rem;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.badge-role.superadmin {
    background: rgba(255, 255, 255, 0.2);
    color: white;
}

.badge-role.admin {
    background: rgba(255, 255, 255, 0.2);
    color: white;
}

.badge-role.ventas {
    background: rgba(255, 255, 255, 0.2);
    color: white;
}

.badge-role.cortes {
    background: rgba(255, 255, 255, 0.2);
    color: white;
}

.badge-estado {
    border-radius: 50px;
    padding: 0.3rem 0.8rem;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.badge-estado.activo {
    background: var(--success-color);
    color: white;
}

.badge-estado.inactivo {
    background: var(--danger-color);
    color: white;
}

/* --- CUERPO DE LA CARD --- */
.user-card-body {
    padding: 1.5rem;
}

.user-info-item {
    display: flex;
    align-items: center;
    margin-bottom: 1rem;
    padding: 0.75rem;
    background: #f8f9fa;
    border-radius: 0.5rem;
}

.user-info-item:last-child {
    margin-bottom: 0;
}

.user-info-icon {
    width: 40px;
    height: 40px;
    background: var(--primary-gradient);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    margin-right: 1rem;
    flex-shrink: 0;
}

.user-info-content {
    flex: 1;
}

.user-info-label {
    font-size: 0.75rem;
    color: var(--text-light);
    text-transform: uppercase;
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.user-info-value {
    font-weight: 600;
    color: var(--text-dark);
}

/* --- ACCIONES --- */
.user-card-actions {
    padding: 1rem 1.5rem;
    background: #f8f9fa;
    border-top: 1px solid var(--border-color);
    display: flex;
    gap: 0.5rem;
}

.user-card-actions .btn {
    flex: 1;
    border-radius: 50px;
    font-weight: 600;
    padding: 0.6rem 1rem;
    font-size: 0.85rem;
}

/* --- BÚSQUEDA MEJORADA --- */
.search-container {
    background: var(--card-bg);
    border-radius: var(--card-border-radius);
    padding: 1.5rem;
    margin-bottom: 2rem;
    box-shadow: var(--card-shadow);
    border: none;
}

.search-input {
    border-radius: 50px;
    border: 2px solid var(--border-color);
    padding: 0.75rem 1.5rem;
    padding-left: 3rem;
    font-size: 1rem;
    transition: all 0.3s ease;
}

.search-input:focus {
    border-color: var(--secondary-color);
    box-shadow: 0 0 0 3px rgba(37, 117, 252, 0.1);
}

.search-icon {
    position: absolute;
    left: 1.25rem;
    top: 50%;
    transform: translateY(-50%);
    color: var(--text-light);
    z-index: 10;
}

/* --- MODALES MEJORADOS --- */
.modal-content {
    border-radius: var(--card-border-radius);
    border: none;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
}

.modal-header {
    background: var(--primary-gradient);
    color: white;
    border-top-left-radius: var(--card-border-radius);
    border-top-right-radius: var(--card-border-radius);
    border-bottom: none;
    padding: 1.5rem;
}

.modal-header .btn-close {
    filter: invert(1) grayscale(100%) brightness(200%);
}

.modal-body {
    padding: 2rem;
}

.modal-footer {
    border-top: 1px solid var(--border-color);
    padding: 1.5rem;
}

.form-label {
    font-weight: 600;
    color: var(--text-dark);
    margin-bottom: 0.5rem;
}

.form-control, .form-select {
    border-radius: 0.5rem;
    border: 2px solid var(--border-color);
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
}

.form-control:focus, .form-select:focus {
    border-color: var(--secondary-color);
    box-shadow: 0 0 0 3px rgba(37, 117, 252, 0.1);
}

/* --- RESPONSIVE --- */
@media (max-width: 768px) {
    .users-grid {
        grid-template-columns: 1fr;
        gap: 1rem;
    }
    
    .page-header {
        padding: 1.5rem;
    }
    
    .user-card-header {
        padding: 1.25rem;
    }
    
    .user-card-body {
        padding: 1.25rem;
    }
}

/* --- ANIMACIONES --- */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.user-card {
    animation: fadeInUp 0.6s ease forwards;
}

.user-card:nth-child(1) { animation-delay: 0.1s; }
.user-card:nth-child(2) { animation-delay: 0.2s; }
.user-card:nth-child(3) { animation-delay: 0.3s; }
.user-card:nth-child(4) { animation-delay: 0.4s; }
.user-card:nth-child(5) { animation-delay: 0.5s; }
.user-card:nth-child(6) { animation-delay: 0.6s; }
</style>

<div class="container-fluid px-4">
    <!-- HEADER MEJORADO -->
    <div class="page-header">
        <div class="d-flex justify-content-between align-items-center">
            <h1 class="page-title">
                <i class="fas fa-users-cog me-3"></i>Gestión de Usuarios
            </h1>
            <button class="btn btn-primary btn-lg rounded-pill shadow-sm" data-bs-toggle="modal" data-bs-target="#modalCrear" style="background: var(--primary-gradient); border: none;">
                <i class="fas fa-user-plus me-2"></i>Nuevo Usuario
            </button>
        </div>
    </div>

    <!-- ALERTAS -->
    <?php if (isset($_GET['mensaje'])): ?>
        <div class="alert alert-<?php echo htmlspecialchars($_GET['tipo'] ?? 'info'); ?> alert-dismissible fade show" role="alert" style="border-radius: var(--card-border-radius);">
            <i class="fas fa-info-circle me-2"></i><?php echo htmlspecialchars($_GET['mensaje']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (!empty($error_carga)): ?>
        <div class="alert alert-danger" style="border-radius: var(--card-border-radius);">
            <i class="fas fa-exclamation-triangle me-2"></i>No se pudieron cargar los usuarios: <?php echo htmlspecialchars($error_carga); ?>
        </div>
    <?php endif; ?>

    <!-- BÚSQUEDA MEJORADA -->
    <div class="search-container">
        <div class="position-relative">
            <i class="fas fa-search search-icon"></i>
            <input type="text" id="searchInput" class="form-control search-input" placeholder="Buscar usuarios por nombre, usuario, rol, teléfono...">
        </div>
    </div>

    <!-- GRID DE USUARIOS -->
    <div class="users-grid" id="usersGrid">
        <?php if (!empty($usuarios)): ?>
            <?php foreach ($usuarios as $u): 
                $last_login = !empty($u['last_login']) ? date('d/m/Y H:i', strtotime($u['last_login'])) : 'Nunca';
                $rol_key = $u['rol'];
                $rol_text = $ROLES[$rol_key] ?? $rol_key;
                $estado_key = (string)($u['estado']);
                $estado_text = $ESTADOS[$estado_key] ?? 'Desconocido';
                $estado_class = $estado_key === '1' ? 'activo' : 'inactivo';
            ?>
                <div class="user-card" data-search-text="<?php
                    echo htmlspecialchars(
                        strtolower(
                            ($u['nombre_completo'] ?? '') . ' ' .
                            ($u['username'] ?? '') . ' ' .
                            ($rol_text ?? '') . ' ' .
                            ($u['telefono'] ?? '')
                        )
                    );
                ?>">
                    <!-- HEADER DE LA CARD -->
                    <div class="user-card-header">
                        <div class="user-avatar">
                            <?php echo strtoupper(substr($u['nombre_completo'], 0, 1)); ?>
                        </div>
                        <div class="user-name"><?php echo htmlspecialchars($u['nombre_completo']); ?></div>
                        <div class="user-username">@<?php echo htmlspecialchars($u['username']); ?></div>
                        <span class="badge badge-role <?php echo htmlspecialchars($rol_key); ?>">
                            <?php echo htmlspecialchars($rol_text); ?>
                        </span>
                    </div>

                    <!-- CUERPO DE LA CARD -->
                    <div class="user-card-body">
                        <!-- ESTADO -->
                        <div class="user-info-item">
                            <div class="user-info-icon">
                                <i class="fas fa-circle"></i>
                            </div>
                            <div class="user-info-content">
                                <div class="user-info-label">Estado</div>
                                <div class="user-info-value">
                                    <span class="badge badge-estado <?php echo $estado_class; ?>">
                                        <?php echo htmlspecialchars($estado_text); ?>
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- TELÉFONO -->
                        <div class="user-info-item">
                            <div class="user-info-icon">
                                <i class="fas fa-phone"></i>
                            </div>
                            <div class="user-info-content">
                                <div class="user-info-label">Teléfono</div>
                                <div class="user-info-value">
                                    <?php echo htmlspecialchars($u['telefono'] ?? 'No especificado'); ?>
                                </div>
                            </div>
                        </div>

                        <!-- ÚLTIMO ACCESO -->
                        <div class="user-info-item">
                            <div class="user-info-icon">
                                <i class="fas fa-clock"></i>
                            </div>
                            <div class="user-info-content">
                                <div class="user-info-label">Último Acceso</div>
                                <div class="user-info-value">
                                    <?php echo htmlspecialchars($last_login); ?>
                                </div>
                            </div>
                        </div>

                        <!-- ID DE USUARIO -->
                        <div class="user-info-item">
                            <div class="user-info-icon">
                                <i class="fas fa-id-card"></i>
                            </div>
                            <div class="user-info-content">
                                <div class="user-info-label">ID de Usuario</div>
                                <div class="user-info-value">
                                    #<?php echo (int)$u['id_usuario']; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- ACCIONES -->
                    <div class="user-card-actions">
                        <button
                            class="btn btn-outline-primary"
                            data-bs-toggle="modal" data-bs-target="#modalEditar"
                            data-id="<?php echo (int)$u['id_usuario']; ?>"
                            data-nombre="<?php echo htmlspecialchars($u['nombre_completo']); ?>"
                            data-username="<?php echo htmlspecialchars($u['username']); ?>"
                            data-rol="<?php echo htmlspecialchars($rol_key); ?>"
                            data-estado="<?php echo htmlspecialchars($estado_key); ?>"
                            data-telefono="<?php echo htmlspecialchars($u['telefono'] ?? ''); ?>"
                            data-fin="<?php echo htmlspecialchars($u['fecha_fin_membresia'] ?? ''); ?>"
                            title="Editar Usuario">
                            <i class="fas fa-edit me-1"></i>Editar
                        </button>
                        <button
                            class="btn btn-outline-danger"
                            data-bs-toggle="modal" data-bs-target="#modalEliminar"
                            data-id="<?php echo (int)$u['id_usuario']; ?>"
                            data-nombre="<?php echo htmlspecialchars($u['nombre_completo']); ?>"
                            title="Eliminar Usuario">
                            <i class="fas fa-trash-alt me-1"></i>Eliminar
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="col-12">
                <div class="card text-center py-5" style="border-radius: var(--card-border-radius);">
                    <div class="card-body">
                        <i class="fas fa-users fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">No hay usuarios para mostrar</h5>
                        <p class="text-muted">Crea tu primer usuario para empezar a gestionar el sistema.</p>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- MODAL: Crear Usuario -->
<div class="modal fade" id="modalCrear" tabindex="-1" aria-labelledby="modalCrearLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalCrearLabel">
                    <i class="fas fa-user-plus me-2"></i>Crear Nuevo Usuario
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="/digitalpremium/actions/gestion_usuarios_controlador.php" method="POST" autocomplete="off">
                <input type="hidden" name="accion" value="crear_usuario">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Nombre Completo <span class="text-danger">*</span></label>
                            <input type="text" name="nombre_completo" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Usuario <span class="text-danger">*</span></label>
                            <input type="text" name="username" class="form-control" minlength="3" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Contraseña <span class="text-danger">*</span></label>
                            <input type="password" name="password" class="form-control" minlength="6" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Rol <span class="text-danger">*</span></label>
                            <select name="rol" class="form-select" required>
                                <?php foreach ($ROLES as $k=>$v): ?>
                                    <option value="<?php echo htmlspecialchars($k); ?>"><?php echo htmlspecialchars($v); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Duración de Membresía (días) <span class="text-danger">*</span></label>
                            <input type="number" name="duracion_membresia" class="form-control" min="1" step="1" placeholder="30" required>
                            <div class="form-text">Se calculará la fecha fin a partir de hoy.</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Teléfono</label>
                            <input type="text" name="telefono" class="form-control" placeholder="Opcional">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary rounded-pill" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>Cancelar
                    </button>
                    <button type="submit" class="btn btn-primary rounded-pill" style="background: var(--primary-gradient); border: none;">
                        <i class="fas fa-check-circle me-1"></i>Crear Usuario
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- MODAL: Editar Usuario -->
<div class="modal fade" id="modalEditar" tabindex="-1" aria-labelledby="modalEditarLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalEditarLabel">
                    <i class="fas fa-user-edit me-2"></i>Editar Usuario
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="/digitalpremium/actions/gestion_usuarios_controlador.php" method="POST" autocomplete="off">
                <input type="hidden" name="accion" value="editar_usuario">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                <input type="hidden" name="id_usuario" id="edit_id_usuario">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Nombre Completo <span class="text-danger">*</span></label>
                            <input type="text" name="nombre_completo" id="edit_nombre" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Usuario <span class="text-danger">*</span></label>
                            <input type="text" name="username" id="edit_username" class="form-control" minlength="3" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Nueva Contraseña</label>
                            <input type="password" name="password" class="form-control" placeholder="Déjalo en blanco para no cambiar">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Rol <span class="text-danger">*</span></label>
                            <select name="rol" id="edit_rol" class="form-select" required>
                                <?php foreach ($ROLES as $k=>$v): ?>
                                    <option value="<?php echo htmlspecialchars($k); ?>"><?php echo htmlspecialchars($v); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Estado <span class="text-danger">*</span></label>
                            <select name="estado" id="edit_estado" class="form-select" required>
                                <option value="1">Activo</option>
                                <option value="0">Inactivo</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Teléfono</label>
                            <input type="text" name="telefono" id="edit_telefono" class="form-control" placeholder="Opcional">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Fecha Fin de Membresía</label>
                        <input type="date" name="fecha_fin_membresia" id="edit_fin" class="form-control">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary rounded-pill" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>Cancelar
                    </button>
                    <button type="submit" class="btn btn-warning rounded-pill">
                        <i class="fas fa-save me-1"></i>Guardar Cambios
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- MODAL: Eliminar Usuario -->
<div class="modal fade" id="modalEliminar" tabindex="-1" aria-labelledby="modalEliminarLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="background: var(--danger-color);">
                <h5 class="modal-title" id="modalEliminarLabel">
                    <i class="fas fa-trash-alt me-2"></i>Eliminar Usuario
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="/digitalpremium/actions/gestion_usuarios_controlador.php" method="POST">
                <input type="hidden" name="accion" value="eliminar_usuario">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                <input type="hidden" name="id_usuario" id="del_id_usuario">
                <div class="modal-body">
                    <div class="text-center mb-4">
                        <i class="fas fa-exclamation-triangle fa-3x text-danger mb-3"></i>
                        <h5>¿Estás seguro?</h5>
                        <p class="mb-3">¿Deseas eliminar al usuario <strong id="del_nombre"></strong>?</p>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            Esta acción es <strong>irreversible</strong> y eliminará todos sus datos asociados.
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary rounded-pill" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i>Cancelar
                    </button>
                    <button type="submit" class="btn btn-danger rounded-pill">
                        <i class="fas fa-exclamation-triangle me-1"></i>Eliminar Usuario
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include_once __DIR__ . '/../includes/footer.php'; ?>

<script>
// Búsqueda mejorada en cards
(function(){
    const input = document.getElementById('searchInput');
    const cards = Array.from(document.querySelectorAll('.user-card'));
    
    if (!input) return;
    
    input.addEventListener('input', function(){
        const query = this.value.toLowerCase().trim();
        let visibleCards = 0;
        
        cards.forEach(card => {
            const searchText = card.getAttribute('data-search-text') || '';
            const isVisible = searchText.includes(query);
            
            card.style.display = isVisible ? 'block' : 'none';
            if (isVisible) visibleCards++;
        });
        
        // Mostrar mensaje si no hay resultados
        const noResultsMsg = document.getElementById('noResultsMsg');
        if (visibleCards === 0 && cards.length > 0) {
            if (!noResultsMsg) {
                const msg = document.createElement('div');
                msg.id = 'noResultsMsg';
                msg.className = 'col-12';
                msg.innerHTML = `
                    <div class="card text-center py-5" style="border-radius: var(--card-border-radius);">
                        <div class="card-body">
                            <i class="fas fa-search fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No se encontraron usuarios</h5>
                            <p class="text-muted">Intenta con otros términos de búsqueda.</p>
                        </div>
                    </div>
                `;
                document.getElementById('usersGrid').appendChild(msg);
            }
        } else if (noResultsMsg) {
            noResultsMsg.remove();
        }
    });
})();

// Modal editar: prellenar datos
const modalEditar = document.getElementById('modalEditar');
if (modalEditar){
    modalEditar.addEventListener('show.bs.modal', function(ev){
        const btn = ev.relatedTarget;
        if (!btn) return;
        
        const id = btn.getAttribute('data-id');
        const nombre = btn.getAttribute('data-nombre') || '';
        const username = btn.getAttribute('data-username') || '';
        const rol = btn.getAttribute('data-rol') || 'admin';
        const estado = btn.getAttribute('data-estado') || '1';
        const telefono = btn.getAttribute('data-telefono') || '';
        const fin = btn.getAttribute('data-fin') || '';

        document.getElementById('edit_id_usuario').value = id;
        document.getElementById('edit_nombre').value = nombre;
        document.getElementById('edit_username').value = username;
        document.getElementById('edit_rol').value = rol;
        document.getElementById('edit_estado').value = estado;
        document.getElementById('edit_telefono').value = telefono;
        document.getElementById('edit_fin').value = fin;
    });
}

// Modal eliminar: set datos
const modalEliminar = document.getElementById('modalEliminar');
if (modalEliminar){
    modalEliminar.addEventListener('show.bs.modal', function(ev){
        const btn = ev.relatedTarget;
        if (!btn) return;
        
        document.getElementById('del_id_usuario').value = btn.getAttribute('data-id');
        document.getElementById('del_nombre').textContent = btn.getAttribute('data-nombre') || '';
    });
}

// Auto-hide alerts after 5 seconds
document.addEventListener('DOMContentLoaded', function() {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        setTimeout(() => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }, 5000);
    });
});
</script>
