<script>
if (window.jQuery) {
    $(document).on('submit', '#dynamic-content form', function(e) {
        e.preventDefault();
        var $form = $(this);
        $.ajax({
            url: $form.attr('action') || '',
            type: 'POST',
            data: $form.serialize(),
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            success: function(data) {
                $("#dynamic-content .content-area").html(data);
                if (typeof initTogglePassword === 'function') initTogglePassword();
            }
        });
    });
}
</script>
<?php
include 'opciones_data.php';
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panel de Control</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles/opciones.css">
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #34495e;
            --accent-color: #3498db;
            --success-color: #27ae60;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
        }

        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            transition: all 0.3s ease;
        }

        .sidebar {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            min-height: 100vh;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }

        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 12px 20px;
            margin: 5px 10px;
            border-radius: 8px;
            transition: all 0.3s ease;
            border-left: 3px solid transparent;
        }

        .sidebar .nav-link:hover {
            background-color: rgba(255,255,255,0.1);
            color: white;
            border-left-color: var(--accent-color);
            transform: translateX(5px);
        }

        .sidebar .nav-link.active {
            background-color: var(--accent-color);
            color: white;
            border-left-color: white;
        }

        .sidebar .nav-link i {
            width: 20px;
            margin-right: 10px;
        }

        .user-profile {
            background: rgba(255,255,255,0.1);
            border-radius: 15px;
            margin: 20px;
            padding: 20px;
            text-align: center;
            backdrop-filter: blur(10px);
        }

        .user-profile .avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--accent-color), var(--success-color));
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px auto;
            font-size: 2rem;
            color: white;
        }

        .main-content {
            background-color: #f8f9fa;
            min-height: 100vh;
        }

        .stats-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            border: none;
            overflow: hidden;
            position: relative;
        }

        .stats-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--accent-color);
        }

        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        .stats-card.users::before { background: linear-gradient(135deg, #16a085, #2c3e50); }
        .stats-card.expired::before { background: linear-gradient(135deg, #e74c3c, #c0392b); }
        .stats-card.expiring::before { background: linear-gradient(135deg, #f39c12, #f1c40f); }
        .stats-card.resellers::before { background: linear-gradient(135deg, #3498db, #16a085); }
        .stats-card.credits::before { background: linear-gradient(135deg, #27ae60, #16a085); }

        .stats-card .icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px auto;
            font-size: 1.5rem;
            color: white;
        }

        .stats-card.users .icon { background: linear-gradient(135deg, #16a085, #2c3e50); }
        .stats-card.expired .icon { background: linear-gradient(135deg, #e74c3c, #c0392b); }
        .stats-card.expiring .icon { background: linear-gradient(135deg, #f39c12, #f1c40f); }
        .stats-card.resellers .icon { background: linear-gradient(135deg, #3498db, #16a085); }
        .stats-card.credits .icon { background: linear-gradient(135deg, #27ae60, #16a085); }

        .stats-number {
            font-size: 2.5rem;
            font-weight: 700;
            color: var(--primary-color);
            margin: 10px 0;
        }

        .stats-label {
            color: #6c757d;
            font-size: 0.9rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .header-bar {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .btn-custom {
            border-radius: 25px;
            padding: 8px 20px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-credits {
            background: linear-gradient(135deg, var(--success-color), var(--accent-color));
            border: none;
            color: white;
        }

        .content-area {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            min-height: 400px;
        }

        /* Responsive */
        @media (max-width: 767.98px) {
            .sidebar {
                position: fixed;
                top: 0;
                left: -100%;
                height: 100vh;
                z-index: 999;
                transition: all 0.3s ease;
                width: 280px;
            }
            .sidebar.active {
                left: 0;
            }
            .stats-card {
                margin-bottom: 20px;
            }
            @media (max-width: 767.98px) {
                .row.g-4.mb-4 > div[class^="col-"] {
                    flex: 0 0 100%;
                    max-width: 100%;
                }
                .stats-card {
                    margin-bottom: 24px;
                    padding: 18px 8px;
                }
                .stats-card .stats-number {
                    font-size: 2rem;
                }
                .stats-card .stats-label {
                    font-size: 1rem;
                }
                .stats-card .btn {
                    width: 100%;
                    font-size: 1rem;
                }
                .icon {
                    font-size: 2.2rem;
                }
            }
        }

        #sidebarCollapse {
            display: none;
            background: var(--primary-color);
            border: none;
            color: white;
            border-radius: 10px;
            padding: 10px 15px;
        }

        @media (max-width: 767.98px) {
            #sidebarCollapse {
                display: block;
                position: fixed;
                top: 20px;
                left: 20px;
                z-index: 1000;
            }
        }

        /* Dark mode */
        body.dark-mode {
            background-color: #1a1a1a;
            color: #e9ecef;
        }

        .dark-mode .main-content {
            background-color: #1a1a1a;
        }

        .dark-mode .stats-card,
        .dark-mode .header-bar,
        .dark-mode .content-area {
            background-color: #2d3748;
            color: #e9ecef;
        }

        .dark-mode .stats-number {
            color: #e9ecef;
        }

        /* Loading animation */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row flex-nowrap">
            <!-- Sidebar -->
            <div class="col-auto col-md-3 col-xl-2 px-0 sidebar">
                <div class="user-profile">
                    <div class="avatar">
                        <i class="fas fa-user"></i>
                    </div>
                    <h5 class="text-light mb-0"><?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Usuario'); ?></h5>
                    <p class="text-light-50 small mb-0">Panel de Control</p>
                </div>
                
                <ul class="nav flex-column px-2">
                    <li class="nav-item">
                        <a class="nav-link active" href="#" data-page="dashboard">
                            <i class="fas fa-tachometer-alt"></i> Dashboard
                        </a>
                    </li>
<?php if (isset($_SESSION['user_id'])) { ?>
<li class="nav-item">
    <a class="nav-link" href="#" data-page="bandeja_entrada.php">
        <i class="fas fa-envelope"></i> Bandeja de Entrada
    </a>
</li>
<?php if (isset($_SESSION['user_email']) && $_SESSION['user_email'] === 'carlosrf2007@gmail.com') { ?>
<li class="nav-item">
    <a class="nav-link" href="#" data-page="admin_mensajes.php">
        <i class="fas fa-bullhorn"></i> Enviar Mensaje Global
    </a>
</li>
<?php } ?>
<?php } ?>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="add_users.php">
                            <i class="fas fa-user-plus"></i> Agregar Usuario Nuevo
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="add_demo.php">
                            <i class="fas fa-user-clock"></i> Agregar Usuario Demo
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="add_reseller.php">
                            <i class="fas fa-user-tie"></i> Agregar Revendedor
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" data-page="users_creados.php">
                            <i class="fas fa-users"></i> Ver Usuarios
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="listar" data-page="listar_resellers.php">
                            <i class="fas fa-users-cog"></i> Ver Revendedores
                        </a>
                    </li>
                </ul>
            </div>

            <!-- Main content -->
            <main class="col py-3 main-content">
                <div class="header-bar d-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center">
                        <button id="sidebarCollapse">
                            <i class="fas fa-bars"></i>
                        </button>
                        <h1 class="h2 mb-0 ms-3">Panel de Control</h1>
                    </div>
                    <div class="d-flex align-items-center gap-3">
                        <button id="toggleDark" class="btn btn-outline-secondary btn-custom" title="Modo oscuro">
                            <i class="fas fa-moon"></i>
                        </button>
                        <a href="logout.php" class="btn btn-outline-danger btn-custom">
                            <i class="fas fa-sign-out-alt"></i> Cerrar sesión
                        </a>
                    </div>
                </div>

                <!-- DASHBOARD ESTADÍSTICAS -->
                <div id="dashboard-content">
                    <div class="row g-4 mb-4">
                        <div class="col-lg-2 col-md-4 col-sm-6">
                            <div class="stats-card users">
                                <div class="icon">
                                    <i class="fas fa-users"></i>
                                </div>
                                <div class="stats-number"><?php echo $total_usuarios ?? 0; ?></div>
                                <div class="stats-label">Usuarios Creados</div>
                                <a href="users_creados.php" class="btn btn-outline-primary btn-sm mt-3">
                                    <i class="fas fa-eye"></i> Ver Detalles
                                </a>
                            </div>
                        </div>
                        
                        <div class="col-lg-2 col-md-4 col-sm-6">
                            <div class="stats-card expired">
                                <div class="icon">
                                    <i class="fas fa-user-times"></i>
                                </div>
                                <div class="stats-number"><?php echo $total_vencidos ?? 0; ?></div>
                                <div class="stats-label">Usuarios Vencidos</div>
                                <a href="usuarios_vencidos.php" class="btn btn-outline-danger btn-sm mt-3">
                                    <i class="fas fa-eye"></i> Ver Detalles
                                </a>
                            </div>
                        </div>
                        
                        <div class="col-lg-2 col-md-4 col-sm-6">
                            <div class="stats-card expiring">
                                <div class="icon">
                                    <i class="fas fa-hourglass-half"></i>
                                </div>
                                <div class="stats-number"><?php echo $total_por_vencer ?? 0; ?></div>
                                <div class="stats-label">Por Vencer (7 días)</div>
                                <a href="usuarios_por_vencer.php" class="btn btn-outline-warning btn-sm mt-3">
                                    <i class="fas fa-eye"></i> Ver Detalles
                                </a>
                            </div>
                        </div>
                        
                        <div class="col-lg-2 col-md-4 col-sm-6">
                            <div class="stats-card resellers">
                                <div class="icon">
                                    <i class="fas fa-user-tie"></i>
                                </div>
                                <div class="stats-number"><?php echo $total_resellers ?? 0; ?></div>
                                <div class="stats-label">Revendedores</div>
                                <a href="listar_resellers.php" class="btn btn-outline-info btn-sm mt-3">
                                    <i class="fas fa-eye"></i> Ver Detalles
                                </a>
                            </div>
                        </div>
                        
                        <div class="col-lg-2 col-md-4 col-sm-6">
                            <div class="stats-card credits">
                                <div class="icon">
                                    <i class="fas fa-coins"></i>
                                </div>
                                <div class="stats-number"><?php echo $_SESSION['user_credits'] ?? 0; ?></div>
                                <div class="stats-label">Créditos Disponibles</div>
                                <button class="btn btn-success btn-sm mt-3" onclick="updateCredits()">
                                    <i class="fas fa-sync-alt"></i> Actualizar
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="content-area">
                        <h4><i class="fas fa-chart-line me-2"></i>Bienvenido al Panel de Control</h4>
                        <p class="text-muted">Gestiona tus usuarios, revendedores y créditos desde este panel centralizado.</p>
                        <div class="row mt-4">
                            <div class="col-md-6">
                                <h5><i class="fas fa-info-circle me-2"></i>Acciones Rápidas</h5>
                                <ul class="list-unstyled">
                                    <li><i class="fas fa-chevron-right text-primary me-2"></i>Crear nuevo usuario o demo</li>
                                    <li><i class="fas fa-chevron-right text-primary me-2"></i>Agregar revendedores</li>
                                    <li><i class="fas fa-chevron-right text-primary me-2"></i>Revisar usuarios por vencer</li>
                                    <li><i class="fas fa-chevron-right text-primary me-2"></i>Gestionar créditos</li>
                                </ul>
                            </div>
                            <div class="col-md-6">
                                <h5><i class="fas fa-bell me-2"></i>Alertas</h5>
                                <div class="alert alert-warning" role="alert">
                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                    Tienes <strong><?php echo $total_por_vencer ?? 0; ?></strong> usuarios que vencen en los próximos 7 días.
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Contenido dinámico -->
                <div id="dynamic-content" style="display: none;">
                    <div class="content-area">
                        <div class="d-flex justify-content-center">
                            <div class="loading"></div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    $(document).ready(function() {
        // Navegación del sidebar
        $(".nav-link").click(function(e) {
            e.preventDefault();

            // Remover clase active de todos los enlaces
            $(".nav-link").removeClass("active");
            // Agregar clase active al enlace clickeado
            $(this).addClass("active");

            var page = $(this).data("page");

            if (page === "dashboard") {
                $("#dashboard-content").show();
                $("#dynamic-content").hide();
            } else {
                $("#dashboard-content").hide();
                $("#dynamic-content").show();
                loadPage(page);
            }

            // Cerrar el sidebar solo en pantallas pequeñas
            if ($(window).width() <= 767.98) {
                $(".sidebar").removeClass("active");
            }
        });

        // Función para cargar páginas
        function loadPage(page) {
            $("#dynamic-content .content-area").html('<div class="d-flex justify-content-center"><div class="loading"></div></div>');
            
            $.ajax({
                url: page,
                type: 'GET',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                success: function(data) {
                    $("#dynamic-content .content-area").html(data);
                },
                error: function() {
                    $("#dynamic-content .content-area").html(
                        '<div class="alert alert-danger"><i class="fas fa-exclamation-triangle me-2"></i>Error al cargar la página.</div>'
                    );
                }
            });
        }

        // Funcionalidad para mostrar/ocultar sidebar
        $("#sidebarCollapse").click(function(e) {
            e.stopPropagation();
            $(".sidebar").toggleClass("active");
        });

        // Cerrar sidebar al hacer clic fuera de él en pantallas pequeñas
        $(document).click(function(event) {
            if (!$(event.target).closest('.sidebar').length &&
                !$(event.target).is('#sidebarCollapse') &&
                $(window).width() <= 767.98) {
                $(".sidebar").removeClass("active");
            }
        });

        // Modo oscuro
        $("#toggleDark").click(function() {
            $("body").toggleClass("dark-mode");
            
            // Cambiar icono
            var icon = $(this).find("i");
            if ($("body").hasClass("dark-mode")) {
                icon.removeClass("fa-moon").addClass("fa-sun");
                localStorage.setItem("darkMode", "enabled");
            } else {
                icon.removeClass("fa-sun").addClass("fa-moon");
                localStorage.setItem("darkMode", "disabled");
            }
        });

        // Recuperar estado del modo oscuro
        if (localStorage.getItem("darkMode") === "enabled") {
            $("body").addClass("dark-mode");
            $("#toggleDark i").removeClass("fa-moon").addClass("fa-sun");
        }
    });

    // Función para actualizar créditos
    function updateCredits() {
        $.ajax({
            url: 'update_credits.php',
            type: 'GET',
            success: function(data) {
                location.reload();
            },
            error: function() {
                alert('Error al actualizar créditos');
            }
        });
    }

    // Animaciones en scroll
    $(window).scroll(function() {
        $('.stats-card').each(function() {
            var elementTop = $(this).offset().top;
            var elementBottom = elementTop + $(this).outerHeight();
            var viewportTop = $(window).scrollTop();
            var viewportBottom = viewportTop + $(window).height();

            if (elementBottom > viewportTop && elementTop < viewportBottom) {
                $(this).addClass('animate__animated animate__fadeInUp');
            }
        });
    });
    </script>
</body>
</html>
<script>
function initTogglePassword() {
    document.querySelectorAll('.toggle-password').forEach(button => {
        button.onclick = function() {
            const td = button.closest('td');
            const passwordMask = td.querySelector('.password-mask');
            const passwordHidden = td.querySelector('.password-hidden');
            const isHiddenVisible = window.getComputedStyle(passwordHidden).display !== 'none';
            if (isHiddenVisible) {
                passwordHidden.style.display = 'none';
                passwordMask.style.display = 'inline';
                button.innerHTML = '<i class="fas fa-eye"></i>';
            } else {
                passwordHidden.style.display = 'inline';
                passwordMask.style.display = 'none';
                button.innerHTML = '<i class="fas fa-eye-slash"></i>';
            }
        }
    });
}
document.addEventListener('DOMContentLoaded', initTogglePassword);
if (window.jQuery) {
    $(document).ajaxComplete(initTogglePassword);
}
</script>
<script>
if (window.jQuery) {
    $(document).on('submit', 'form', function(e) {
        if ($(this).find('button[type=submit]').closest('.content-area').length) {
            e.preventDefault();
            var $form = $(this);
            $.post($form.attr('action') || '', $form.serialize(), function(data) {
                $("#dynamic-content .content-area").html(data);
                if (typeof initTogglePassword === 'function') initTogglePassword();
            });
        }
    });
}
</script>