<?php
// Arquivo: menu.php

// INCLUINDO O SISTEMA DE ALERTAS CENTRALIZADO
require_once __DIR__ . "/sys/alerts.php";

// ==============================================================================
// LÓGICA DE ATUALIZAÇÕES RECENTES
// ==============================================================================
 $update_logs =[];
 $log_file_path = __DIR__ . '/sys/update_log.json';
if (file_exists($log_file_path)) {
    $data = file_get_contents($log_file_path);
    $update_logs = json_decode($data, true);
    if (!is_array($update_logs)) $update_logs =[];
}

// Conta atualizações feitas nas últimas 24h (Lógica PHP Base)
 $new_updates_count = 0;
foreach ($update_logs as $log) {
    if (isset($log['timestamp']) && (time() - $log['timestamp']) < 86400) { // 86400 = 24 horas
        $new_updates_count++;
    }
}
// ==============================================================================

// Função auxiliar para verificar a página ativa
if (!function_exists('isActivePage')) {
    function isActivePage($page_name) {
        if (is_array($page_name)) {
            return in_array(basename($_SERVER['PHP_SELF']), $page_name);
        }
        return basename($_SERVER['PHP_SELF']) == $page_name;
    }
}

// Obtém informações para o menu
 $logo_to_display = 'dist/img/logo_small.png';
 $system_logo_path = getServerProperty('custom_logo_path');
if (!empty($system_logo_path) && file_exists($system_logo_path)) {
    $logo_to_display = $system_logo_path;
}

 $whatsapp_link = getServerProperty('whatsapp_link', '#');
 $telegram_link = getServerProperty('telegram_link', '#');
 $optional_link_name = getServerProperty('optional_link_name', '');
 $optional_link_url = getServerProperty('optional_link_url', '#');

// ==============================================================================
// LÓGICA DE ACESSO
// ==============================================================================
 $is_super_user = false;
if (function_exists('isSubAdmin')) {
    $is_super_user = isSubAdmin($logged_user);
} else {
    $is_super_user = isAdmin($logged_user) || (function_exists('getUserProperty') && getUserProperty($logged_user['id'], 'is_sub_admin') === '1');
}

// Pacotes para teste rápido
 $fast_test_packages_for_menu =[];
if (!function_exists('getPackages')) {
    function getPackages() {
        return [['id' =>1, 'package_name' => 'MOCK', 'is_trial' =>1]]; 
    }
}
 $all_packages_for_menu = getPackages();
if (is_array($all_packages_for_menu)) {
    foreach ($all_packages_for_menu as $pkg) {
        if (!empty($pkg['is_trial'])) {
            $fast_test_packages_for_menu[] = $pkg;
        }
    }
}
?>
<!-- Main Header -->
<header class="main-header">
    <!-- Logo -->
    <a href="dashboard.php" class="logo" style="display: none;">
        <span class="logo-mini"></span>
        <span class="logo-lg"></span>
    </a>

    <!-- Header Navbar -->
    <nav class="navbar navbar-static-top" role="navigation">
        <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
            <span class="sr-only">Toggle navigation</span>
            <i class="fas fa-bars"></i>
        </a>
        <div class="navbar-custom-menu">
            <ul class="nav navbar-nav">
                
                <!-- NOTIFICATIONS (ALERTAS PADRÃO - CARTINHA) -->
                <li class="dropdown messages-menu">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        <i class="far fa-envelope"></i> 
                        <span class="label label-warning" <?php echo (empty($system_alerts)) ? 'style="display:none;"' : ''; ?>>
                            <?php echo count($system_alerts); ?>
                        </span>
                    </a>
                    <?php echo (!empty($system_alerts_html)) ? $system_alerts_html : '<ul class="dropdown-menu"><li class="footer"><a href="#">Sem alertas.</a></li></ul>'; ?>
                </li>

                <!-- NOVO BOTÃO: ATENDIMENTO -->
                <li>
                    <a href="atendimento.php" title="Atendimento">
                        <i class="fas fa-headset"></i>
                    </a>
                </li>

                <!-- SELECTOR DE TEMA -->
                <?php if (file_exists(__DIR__ . "/dark_mode.php")) { require_once __DIR__ . "/dark_mode.php"; } ?>

                <!-- Configurações -->
                <?php if ($is_super_user) { ?>
                <li>
                    <a href="settings.php" title="Configurações">
                        <i class="fas fa-cog"></i>
                    </a>
                </li>
                <?php } ?>

                <!-- ============================================= -->
                <!-- USER ACCOUNT & ATUALIZAÇÕES INTEGRADAS        -->
                <!-- ============================================= -->
                <li class="dropdown user user-menu">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" onclick="markUpdatesAsSeen()">
                        <i class="fas fa-user-circle"></i>
                        <span class="label label-danger" id="user-update-badge" style="display: <?php echo ($new_updates_count > 0) ? 'inline-block' : 'none'; ?>;">
                            <?php echo $new_updates_count; ?>
                        </span>
                        <span class="hidden-xs"></span>
                    </a>
                    
                    <ul class="dropdown-menu" style="border-radius: 6px !important; width: 290px; border: 1px solid var(--border-color) !important; box-shadow: 0 5px 15px rgba(0,0,0,0.3) !important; padding: 0 !important; background-color: var(--bg-box) !important; overflow: hidden !important;">
                        
                        <!-- Cabeçalho do Perfil -->
                        <li class="user-header" style="height: auto; padding: 15px; background-color: var(--main-blue-color) !important; color: #fff; border-bottom: none !important;">
                            <img src="<?php echo htmlspecialchars($logo_to_display); ?>?t=<?php echo time(); ?>" class="img-circle" alt="User Image" style="width: 60px; height: 60px; border: 2px solid rgba(255,255,255,0.3);">
                            <p style="margin-top: 8px; font-size: 14px;">
                                <strong><?php echo htmlspecialchars($logged_user['username']); ?></strong>
                                <small style="display: block; margin-top:2px; font-size: 11px; opacity: 0.9; color: rgba(255,255,255,0.9);">
                                    <?php echo htmlspecialchars($logged_user['email']); ?>
                                </small>
                            </p>
                        </li>

                        <!-- CORPO: LISTA DE ATUALIZAÇÕES -->
                        <li class="user-body user-body-custom" style="padding: 0;">
                            
                            <div class="user-body-header">
                                <div class="checkbox" style="margin: 0;">
                                    <label style="font-size: 11px; font-weight: 600; cursor: pointer;">
                                        <input type="checkbox" id="toggle-update-notifs" onchange="toggleUpdateNotifications()" style="margin-top: 2px;">
                                        Receber avisos de atualização
                                    </label>
                                </div>
                            </div>

                            <?php if (!empty($update_logs)): ?>
                                <ul class="menu update-menu-list">
                                    <?php foreach ($update_logs as $log): ?>
                                    <li>
                                        <a href="#" class="update-link">
                                            <div style="display: flex; align-items: flex-start;">
                                                <div style="margin-right: 10px; margin-top: 2px;">
                                                    <i class="fas fa-cloud-download-alt update-icon"></i>
                                                </div>
                                                <div style="flex: 1; min-width: 0;">
                                                    <span class="update-title">ATUALIZAÇÃO NEXUS</span>
                                                    <span class="update-desc">Arquivo: <?php echo htmlspecialchars($log['file']); ?></span>
                                                    <span class="update-time"><i class="far fa-clock"></i> <?php echo htmlspecialchars($log['date'] . ' ' . $log['time']); ?></span>
                                                </div>
                                            </div>
                                        </a>
                                    </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php else: ?>
                                <div class="update-empty-state">
                                    Nenhuma atualização recente.
                                </div>
                            <?php endif; ?>
                        </li>

                        <!-- Rodapé do Menu -->
                        <li class="user-footer" style="background-color: var(--bg-box) !important; padding: 10px; border-top: 1px solid var(--border-color) !important;">
                            <div class="pull-left">
                                <a href="profile.php" class="btn btn-default btn-flat" style="border-radius: 30px; padding: 5px 15px; font-size: 12px; background-color: var(--bg-main); border-color: var(--border-color); color: var(--text-main);">
                                    <i class="fas fa-user-check"></i> Perfil
                                </a>
                            </div>
                            <div class="pull-right">
                                <a href="./logout.php" class="btn btn-default btn-flat" style="border-radius: 30px; padding: 5px 15px; font-size: 12px; background-color: var(--main-red-color); border-color: var(--main-red-color); color: #fff;">
                                    <i class="fas fa-power-off"></i> Sair
                                </a>
                            </div>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </nav>
</header>

<aside class="main-sidebar">
    <section class="sidebar">
        <!-- User Panel -->
        <div class="user-panel">
            <div class="pull-left image">
                <img src="<?php echo htmlspecialchars($logo_to_display); ?>?t=<?php echo time(); ?>" class="img-circle" alt="User Image">
            </div>
            <div class="pull-left info">
                <p style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                    <?php echo htmlspecialchars($logged_user['username']); ?>
                    <?php if (isAdmin($logged_user)): ?>
                        <span class="admin-tag">ADM</span>
                    <?php elseif (getUserProperty($logged_user['id'], 'is_sub_admin') === '1'): ?>
                        <span class="admin-tag" style="background-color: rgba(60, 141, 188, 0.1); color: var(--main-blue-color);">SUB ADM</span>
                    <?php elseif (isset($logged_user['reseller_type']) && !empty($logged_user['reseller_type'])): ?>
                        <span class="reseller-tag">
                            <?php echo htmlspecialchars($logged_user['reseller_type']); ?>
                        </span>
                    <?php endif; ?>
                </p>
                <div class="user-status-line">
                    <a href="#" class="online-status"><i class="fas fa-circle text-success"></i> Online</a>
                    <span class="credits-info-inline">
                        <i class="fas fa-gem"></i>
                        <?php if ($is_super_user || isUnlimitedCredits($logged_user['id'])): ?>
                            <span class="infinity-symbol-gradient">&infin;</span>
                        <?php else: ?>
                            <?php echo htmlspecialchars($logged_user['credits']); ?>
                        <?php endif; ?>
                    </span>
                </div>
            </div>
        </div>

        <!-- WIDGET DE RELÓGIO -->
        <div class="sidebar-widget-container">
            <div class="sidebar-widget">
                <div class="clock-accent"></div>
                <div class="clock-icon-box">
                    <i class="far fa-clock"></i>
                </div>
                <div class="clock-info">
                    <span id="sidebar-time" class="clock-time">--:--</span>
                    <div class="clock-divider"></div>
                    <span id="sidebar-date" class="clock-date">...</span>
                </div>
            </div>
        </div>

        <!-- Menu Lateral -->
        <ul class="sidebar-menu" data-widget="tree">
            
            <li class="<?php if(isActivePage('dashboard.php')) echo 'active'; ?>">
                <a href="dashboard.php"><i class="fas fa-chart-line"></i> <span>DASHBOARD</span></a>
            </li>

            <li class="<?php if(isActivePage('inform.php')) echo 'active'; ?>">
                <a href="inform.php"><i class="fas fa-newspaper"></i> <span>INFORMAÇÕES</span></a>
            </li>

            <?php if(isActivePage('dashboard.php')): ?>
            <li class="header">OPÇÕES RÁPIDAS</li>
            
            <li class="treeview active menu-open">
                <a href="#" class="generate-fast-test-plain-button"> 
                    <i class="fas fa-rocket"></i><span>Gerar Teste Rápido</span>
                    <span class="pull-right-container"><i class="fas fa-angle-left pull-right"></i></span>
                </a>
                <ul class="treeview-menu">
                    <?php if (!empty($fast_test_packages_for_menu)): ?>
                        <?php foreach ($fast_test_packages_for_menu as $pkg): ?>
                            <li>
                                <a href="#" class='create-fast-test' data-package-id='<?php echo htmlspecialchars($pkg["id"]); ?>'>
                                    <i class='fas fa-box-open package-icon'></i> <?php echo htmlspecialchars($pkg["package_name"]); ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <li><a><i class='far fa-circle text-muted'></i> Nenhum configurado</a></li>
                    <?php endif; ?>
                </ul>
            </li>
            <?php endif; ?>

            <li class="<?php if(isActivePage('buy_credits.php')) echo 'active'; ?>">
                <a href="buy_credits.php"><i class="fas fa-coins"></i> <span>Comprar Créditos</span></a>
            </li>

            <li class="header">GERENCIAMENTO</li>
            <li class="<?php if(isActivePage(['clients.php', 'edit_user.php', 'client_stats.php'])) echo 'active'; ?>"><a href="clients.php"><i class="fas fa-users"></i> <span>Gerenciar Clientes</span></a></li>
            <li class="<?php if(isActivePage('create_client.php')) echo 'active'; ?>"><a href="create_client.php"><i class="fas fa-user-plus"></i> <span>Adicionar Cliente</span></a></li>
            
            <li class="<?php if(isActivePage('controle_cadastro.php')) echo 'active'; ?>">
                <a href="controle_cadastro.php"><i class="fas fa-address-card"></i> <span>Controle de Cadastro</span></a>
            </li>
            
            <li class="<?php if(isActivePage('manage_clients.php')) echo 'active'; ?>">
                <a href="manage_clients.php"><i class="fas fa-user-cog"></i> <span>Administrar Clientes</span></a>
            </li>
            <li class="<?php if(isActivePage('migrate_clients.php')) echo 'active'; ?>">
                <a href="migrate_clients.php"><i class="fas fa-random"></i> <span>Migrar Clientes M3U</span></a>
            </li>
            
            <?php 
            $can_manage_resellers = (function_exists('canManageResellers') && canManageResellers($logged_user));
            $is_monthly_user = (isset($logged_user['is_monthly']) && $logged_user['is_monthly'] == 1);
            
            // GERENCIAR REVENDEDORES (Criar/Editar) - Mantido restrito apenas para quem tem permissão
            if ($can_manage_resellers || $is_monthly_user || $is_super_user): 
            ?>
                <li class="<?php if(isActivePage('resellers.php') || isActivePage('create_reseller.php')) echo 'active'; ?>"><a href="resellers.php"><i class="fas fa-user-tie"></i> <span>Gerenciar Revendedores</span></a></li>
                <li class="<?php if(isActivePage('create_reseller.php')) echo 'active'; ?>"><a href="create_reseller.php"><i class="fas fa-user-plus"></i> <span>Adicionar Revendedor</span></a></li>
            <?php endif; ?>

            <!-- ÁREA REVENDEDOR (Status/Mensalidade) - LIBERADO PARA TODOS -->
            <li class="<?php if(isActivePage('monthly_management.php')) echo 'active'; ?>">
                <a href="monthly_management.php">
                    <i class="fas fa-store-alt"></i> <span>Área Revendedor</span>
                </a>
            </li>

            <li class="header">SUPORTE E FERRAMENTAS</li>
            <li class="<?php if(isActivePage('aplicativos.php')) echo 'active'; ?>">
                <a href="aplicativos.php"><i class="fab fa-android"></i> <span>Aplicativos</span></a>
            </li>

            <li class="<?php if(isActivePage('developer.php')) echo 'active'; ?>">
                <a href="developer.php"><i class="fas fa-robot"></i> <span>Chatbot Automático</span></a>
            </li>

            <!-- NOVO ITEM ADICIONADO: AUTOMAÇÃO GESTOR -->
            <li class="<?php if(isActivePage('set_gestor.php')) echo 'active'; ?>">
                <a href="set_gestor.php"><i class="fas fa-cogs"></i> <span>Automação Gestor</span></a>
            </li>

            <li class="<?php if(isActivePage('login_history.php')) echo 'active'; ?>">
                <a href="login_history.php"><i class="fas fa-history"></i> <span>Histórico de Login</span></a>
            </li>

            <li class="<?php if(isActivePage('tools.php')) echo 'active'; ?>"><a href="tools.php"><i class="fas fa-magic"></i> <span>Ferramentas de Limpeza</span></a></li>

            <li class="header">CONTEÚDO</li>
            <li class="<?php if(isActivePage('content_updates.php')) echo 'active'; ?>">
                <a href="content_updates.php"><i class="fas fa-film"></i> <span>Ver Conteúdo Recente</span></a>
            </li>
            
            <li class="<?php if(isActivePage('area_cliente.php')) echo 'active'; ?>">
                <a href="area_cliente.php"><i class="fas fa-desktop"></i> <span>Área do Cliente</span></a>
            </li>

            <?php if (isAdmin($logged_user)): ?>
                <li class="<?php if(isActivePage('gerenciar_pacotes.php')) echo 'active'; ?>"><a href="gerenciar_pacotes.php"><i class="fas fa-cubes"></i> <span>Gerenciar Pacotes</span></a></li>
            <?php endif; ?>

            <?php if ((!empty($whatsapp_link) && $whatsapp_link !== '#') || (!empty($telegram_link) && $telegram_link !== '#') || (!empty($optional_link_url) && $optional_link_url !== '#')): ?>
            <li class="header">COMUNIDADE</li>
                <?php if (!empty($whatsapp_link) && $whatsapp_link !== '#'): ?>
                <li><a href="<?php echo htmlspecialchars($whatsapp_link); ?>" target="_blank"><i class="fab fa-whatsapp"></i> <span>Grupo WhatsApp</span></a></li>
                <?php endif; ?>
                <?php if (!empty($telegram_link) && $telegram_link !== '#'): ?>
                <li><a href="<?php echo htmlspecialchars($telegram_link); ?>" target="_blank"><i class="fab fa-telegram-plane"></i> <span>Grupo Telegram</span></a></li>
                <?php endif; ?>
                <?php if (!empty($optional_link_name) && !empty($optional_link_url) && $optional_link_url !== '#'): ?>
                <li><a href="<?php echo htmlspecialchars($optional_link_url); ?>" target="_blank"><i class="fas fa-globe"></i> <span><?php echo htmlspecialchars($optional_link_name); ?></span></a></li>
                <?php endif; ?>
            <?php endif; ?>

            <?php if ($is_super_user): ?>
            <li class="header" style="margin-top: 0px !important;">FERRAMENTAS AVANÇADAS</li>
            
            <li class="<?php if(isActivePage('migrate_resellers.php')) echo 'active'; ?>">
                <a href="migrate_resellers.php"><i class="fas fa-dolly"></i> <span>Migrar Revendedores XUI</span></a>
            </li>
            <li class="<?php if(isActivePage('personalizar.php')) echo 'active'; ?>"><a href="personalizar.php"><i class="fas fa-paint-brush"></i> <span>Personalizar Aparência</span></a></li>
            
            <?php if (isAdmin($logged_user)): ?>
                <li class="<?php if(isActivePage('monitor.php')) echo 'active'; ?>">
                    <a href="monitor.php"><i class="fas fa-heartbeat"></i> <span>Monitor do Sistema</span>
                </a>
            <?php endif; ?>

            <?php if (isAdmin($logged_user)): ?>
                <li class="<?php if(isActivePage('manage_groups.php')) echo 'active'; ?>"><a href="manage_groups.php"><i class="fas fa-users-cog"></i> <span>Grupos de Revendedores</span></a></li>
            <?php endif; ?>
            
            <li class="<?php if(isActivePage('trash.php')) echo 'active'; ?>">
                <a href="trash.php"><i class="fas fa-trash-alt"></i> <span>Lixeira</span></a>
            </li>
            <li class="<?php if(isActivePage('settings.php')) echo 'active'; ?>"><a href="settings.php"><i class="fas fa-sliders-h"></i> <span>Configurações Gerais</span></a></li>
            <li class="<?php if(isActivePage('manage_test_templates.php')) echo 'active'; ?>"><a href="manage_test_templates.php"><i class="fas fa-file-invoice"></i> <span>Templates de Teste</span></a></li>
            <li class="<?php if(isActivePage('controle_teste.php')) echo 'active'; ?>">
                <a href="controle_teste.php"><i class="fas fa-stopwatch"></i> <span>Controle Teste Rápido</span>
            </a>
            </li>
            <li class="<?php if(isActivePage('banco.php')) echo 'active'; ?>">
                <a href="banco.php"><i class="fas fa-database"></i> <span>Ferramentas XUI DB</span></a>
            </li>
            
            <li class="<?php if(isActivePage('fix_db.php')) echo 'active'; ?>">
                <a href="fix_db.php"><i class="fas fa-wrench"></i> <span>Sincronizar Banco API</span></a>
            </li>

            <li class="<?php if(isActivePage('customize_billing_message.php')) echo 'active'; ?>">
                <a href="customize_billing_message.php"><i class="fas fa-comment-dots"></i> <span>Mensagem de Template</span></a>
            </li>
            
            <li class="<?php if(isActivePage('edit_template.php')) echo 'active'; ?>">
                <a href="edit_template.php"><i class="fas fa-edit"></i> <span>Editar Template</span></a>
            </li>

            <?php if (isAdmin($logged_user)): ?>
            <li class="<?php if(isActivePage('admin_system.php')) echo 'active'; ?>">
                <a href="admin_system.php"><i class="fas fa-sync-alt"></i> <span>Sincronizado Conteúdo</span>
            </a>
            <?php endif; ?>

            <?php endif; ?> <!-- FECHA IF IS_SUPER_USER -->

            <li>
                <a href="logout.php" class="text-danger"><i class="fas fa-sign-out-alt"></i> <span>Sair</span></a>
            </li>
        </ul>
    </section>
</aside>

<style>
    /* ========================================================================= */
    /* FIX DEFINITIVO PARA ELIMINAR O VAZAMENTO BRANCO (MODO ESCURO)             */
    /* ========================================================================= */
    .user-body-custom {
        background-color: var(--bg-box) !important;
        border-top: 1px solid var(--border-color) !important;
        border-bottom: none !important; /* Removemos para evitar borda dupla */
    }
    .user-body-header {
        background-color: var(--bg-main) !important;
        padding: 8px 12px;
        border-bottom: 1px solid var(--border-color) !important;
        color: var(--text-main) !important;
    }
    .update-menu-list {
        max-height: 200px;
        overflow-y: auto;
        list-style: none;
        padding: 0;
        margin: 0;
        background-color: var(--bg-box) !important;
    }
    .update-menu-list > li {
        border-bottom: 1px solid var(--border-color) !important;
        background-color: var(--bg-box) !important;
    }
    /* Tira a borda do último item pra não chocar com a do rodapé e gerar mancha */
    .update-menu-list > li:last-child {
        border-bottom: none !important; 
    }
    
    /* Regras forçadas para ignorar o AdminLTE */
    .navbar-nav > .user-menu > .dropdown-menu > li.user-body > ul.update-menu-list > li > a.update-link {
        display: block !important;
        padding: 10px 12px !important;
        white-space: normal !important;
        background-color: var(--bg-box) !important;
        color: var(--text-main) !important;
        transition: background-color 0.2s;
    }
    .navbar-nav > .user-menu > .dropdown-menu > li.user-body > ul.update-menu-list > li > a.update-link:hover {
        background-color: var(--sidebar-link-hover-bg, rgba(0,0,0,0.05)) !important;
    }
    
    /* Textos internos da notificação */
    .update-icon {
        color: var(--main-blue-color) !important;
        font-size: 14px;
    }
    .update-title {
        display: block;
        font-weight: bold;
        font-size: 11px;
        text-transform: uppercase;
        margin-bottom: 2px;
        color: var(--text-main) !important;
    }
    .update-desc {
        display: block;
        font-size: 10px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        color: var(--text-light) !important;
    }
    .update-time {
        display: block;
        font-size: 9px;
        margin-top: 2px;
        color: var(--text-light) !important;
    }
    .update-empty-state {
        padding: 15px;
        text-align: center;
        color: var(--text-light) !important;
        font-size: 11px;
        background-color: var(--bg-box) !important;
    }

    /* ESTILOS ORIGINAIS DO MENU LATERAL */
    .sidebar-menu > li { margin: 0; }
    .sidebar-menu > li > a { padding: 12px 15px; display: flex; align-items: center; color: #444; border-left: 3px solid transparent; transition: all 0.3s ease-in-out; }
    .sidebar-menu > li > a > i { width: 30px; text-align: center; margin-right: 12px; font-size: 17px; opacity: 0.8; transition: transform 0.2s, opacity 0.2s; color: #555; }
    .sidebar-menu > li:hover > a > i, .sidebar-menu > li.active > a > i { opacity: 1; transform: scale(1.1); color: #3c8dbc; }
    .sidebar-menu > li > a span { font-size: 14px; line-height: 1.4; white-space: normal; font-weight: 500; }
    .sidebar-menu li.header { margin-top: 25px; padding: 5px 15px; font-size: 11px; font-weight: 700; color: #aaa; text-transform: uppercase; letter-spacing: 0.8px; }
    .sidebar-menu li.header:first-child { margin-top: 0; }
    .sidebar-menu > li:hover > a, .sidebar-menu > li.active > a { background-color: #f4f6f9; color: #000; border-left-color: #3c8dbc; }
    
    /* CUSTOM SCROLLBAR FINO PARA A LISTA MENOR */
    .user-body .update-menu-list::-webkit-scrollbar { width: 4px; }
    .user-body .update-menu-list::-webkit-scrollbar-track { background: var(--bg-box) !important; }
    .user-body .update-menu-list::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 2px; }
    .user-body .update-menu-list::-webkit-scrollbar-thumb:hover { background: var(--text-light); }

    /* CORE DARK THEME MENU OVERRIDES */
    body[data-theme="dark"] .sidebar-menu > li > a { color: #c2c7d0; }
    body[data-theme="dark"] .sidebar-menu > li > a > i { color: #a0a0a0; }
    body[data-theme="dark"] .sidebar-menu > li:hover > a, body[data-theme="dark"] .sidebar-menu > li.active > a { background-color: #2c3b41; color: #fff; }
    body[data-theme="dark"] .sidebar-menu > li:hover > a > i, body[data-theme="dark"] .sidebar-menu > li.active > a > i { color: #3c8dbc; }

    .main-sidebar { box-shadow: 2px 0 8px rgba(0,0,0,0.08); z-index: 1000; }
    body[data-theme="dark"] .main-sidebar { box-shadow: 4px 0 15px rgba(0,0,0,0.6); border-right: 1px solid #1f2937; }

    .main-header { background-color: #ffffff; border-bottom: 1px solid #e9ecef; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
    body[data-theme="dark"] .main-header { background-color: #2c3e50; border-bottom: 1px solid #1a252f; box-shadow: 0 2px 6px rgba(0,0,0,0.4); }

    body[data-theme="dark"] .navbar-nav > li > a { color: #ecf0f1 !important; }
    body[data-theme="dark"] .sidebar-toggle { color: #ecf0f1 !important; }

    /* WIDGET RELÓGIO */
    .sidebar-widget-container { padding: 6px 15px; margin-bottom: 20px; }
    .sidebar-widget { display: flex; align-items: center; justify-content: flex-start; height: 38px; width: 100%; background: linear-gradient(to right, #ffffff, #f9fafb); border-radius: 19px; border: 1px solid #e5e7eb; box-shadow: 0 2px 5px rgba(0,0,0,0.04); position: relative; overflow: hidden; transition: all 0.3s ease; }
    .clock-accent { position: absolute; left: 0; top: 0; bottom: 0; width: 4px; background: linear-gradient(to bottom, #3498db, #2980b9); }
    .clock-icon-box { flex: 0 0 auto; width: 32px; height: 100%; display: flex; align-items: center; justify-content: center; margin-left: 6px; }
    .clock-icon-box i { font-size: 14px; color: #3498db; }
    .clock-info { flex: 1; display: flex; align-items: center; padding-right: 12px; gap: 6px; }
    .clock-time { font-family: 'Courier New', Courier, monospace; font-size: 14px; font-weight: 700; color: #1f2937; letter-spacing: -0.5px; }
    .clock-divider { width: 1px; height: 14px; background-color: #d1d5db; }
    .clock-date { font-family: 'Segoe UI', sans-serif; font-size: 9px; font-weight: 600; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px; }
    .sidebar-widget:hover { box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2); border-color: #aed6f1; transform: translateY(-1px); }

    body[data-theme="dark"] .sidebar-widget { background: linear-gradient(to right, #1f2937, #111827); border: 1px solid #374151; box-shadow: 0 2px 5px rgba(0,0,0,0.3); }
    body[data-theme="dark"] .clock-accent { background: linear-gradient(to bottom, #3498db, #5dade2); box-shadow: 0 0 8px rgba(52, 152, 219, 0.5); }
    body[data-theme="dark"] .clock-icon-box i { color: #5dade2; }
    body[data-theme="dark"] .clock-time { color: #f3f4f6; text-shadow: 0 0 1px rgba(255,255,255,0.2); }
    body[data-theme="dark"] .clock-divider { background-color: #4b5563; }
    body[data-theme="dark"] .clock-date { color: #9ca3af; }
    body[data-theme="dark"] .sidebar-widget:hover { border-color: #3498db; box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3); }
</style>

<script>
    // ===============================================
    // LÓGICA DO SISTEMA DE ATUALIZAÇÃO (JS)
    // ===============================================
    
    // Função executada ao carregar a página
    document.addEventListener('DOMContentLoaded', function() {
        initUpdateSystem();
    });

    function initUpdateSystem() {
        // Verifica preferência do usuário no LocalStorage (padrão é 'true' se não existir)
        const storedPref = localStorage.getItem('nexus_updates_enabled');
        const isEnabled = storedPref === null ? true : (storedPref === 'true');
        
        // Ajusta o checkbox
        const toggle = document.getElementById('toggle-update-notifs');
        if (toggle) {
            toggle.checked = isEnabled;
        }

        // Ajusta a visibilidade do badge imediatamente ao carregar
        checkBadgeVisibility(isEnabled);
    }

    // Função chamada quando clica no checkbox
    function toggleUpdateNotifications() {
        const toggle = document.getElementById('toggle-update-notifs');
        const isChecked = toggle.checked;
        
        // Salva a preferência no LocalStorage
        localStorage.setItem('nexus_updates_enabled', isChecked);
        
        // Aplica a visualização imediatamente (Funcionalidade solicitada)
        checkBadgeVisibility(isChecked);
    }

    // Controla se a bolinha aparece ou não
    function checkBadgeVisibility(isEnabled) {
        const badge = document.getElementById('user-update-badge');
        if (!badge) return;

        // Se o usuário desativou, esconde a bolinha independente do número de atualizações
        if (!isEnabled) {
            badge.style.display = 'none';
        } else {
            // Se ativado, verifica se tem valor dentro (PHP já colocou o valor no innerText)
            // Se o número for maior que 0, mostra o badge.
            const count = parseInt(badge.innerText || '0');
            if (count > 0) {
                badge.style.display = 'inline-block';
            } else {
                badge.style.display = 'none';
            }
        }
    }

    // Função chamada ao clicar no ícone do perfil para abrir o menu
    // Mantive a lógica original: ao abrir, esconde o badge indicando "Lido"
    function markUpdatesAsSeen() {
        const badge = document.getElementById('user-update-badge');
        if(badge) badge.style.display = 'none';
    }

    // ===============================================
    // RELÓGIO E OUTROS SCRIPTS
    // ===============================================
    function updateSidebarClock() {
        const now = new Date();
        const timeString = now.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
        const dateString = now.toLocaleDateString('pt-BR', { weekday: 'short', day: 'numeric', month: 'short' });
        
        const timeEl = document.getElementById('sidebar-time');
        const dateEl = document.getElementById('sidebar-date');
        
        if(timeEl) timeEl.textContent = timeString;
        if(dateEl) dateEl.textContent = dateString;
    }
    setInterval(updateSidebarClock, 1000);
    updateSidebarClock();

    $(document).ready(function() {
        $('.create-fast-test').on('click', function(e) {
            e.preventDefault();
            var button = $(this);
            var originalHtml = button.html();
            button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Gerando...');
            var packageId = $(this).data('package-id');
            var packageName = $(this).text().trim().replace(/[^\w\s]/gi, '');
            if (confirm('Gerar um teste rápido para o pacote: "' + packageName + '"?')) {
                $.ajax({
                    url: './sys/API.php',
                    type: 'GET',
                    dataType: 'json',
                    data: { action: 'create_test', package_id: packageId },
                    success: function(response) {
                        if (response.result === 'success') {
                            alert('Teste "' + packageName + '" criado com sucesso!');
                        } else {
                            alert('Erro ao criar teste: ' + (response.message || 'Erro desconhecido.'));
                        }
                    },
                    error: function(xhr, status, error) { alert('Erro de comunicação.'); },
                    complete: function() { button.prop('disabled', false).html(originalHtml); }
                });
            } else { button.prop('disabled', false).html(originalHtml); }
        });
    });
</script>

<!-- ============================================================================== -->
<!-- INÍCIO DO RODAPÉ GLOBAL (NO FINAL DA PÁGINA)                                   -->
<!-- ============================================================================== -->
<style>
/* Estilos do Rodapé (Agora ele fica no final da página e rola junto com o conteúdo) */
.global-bottom-footer {
    padding: 15px !important;
    text-align: center !important;
    font-size: 13px;
    font-weight: 500;
    
    /* Cores padrão (Light Mode) */
    background-color: var(--dashboard-background-color, #f4f6f9) !important; 
    border-top: 1px solid var(--border-color, #dee2e6) !important;
    color: var(--text-light, #6c757d) !important;
}

/* Aplica cores escuras caso o site esteja no Dark Mode */
body[data-theme="dark"] .global-bottom-footer {
    background-color: var(--dashboard-background-color, #222d32) !important;
    border-top: 1px solid var(--border-color, #343a40) !important;
    color: var(--text-light, #adb5bd) !important;
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function() {
    // 1. Remove os rodapés antigos perdidos nas páginas para não ficar duplicado
    var oldFooters = document.querySelectorAll('.main-footer:not(.global-bottom-footer)');
    oldFooters.forEach(function(f) { f.remove(); });

    // 2. Cria o HTML do novo rodapé com o visual exato da imagem
    var anoAtual = new Date().getFullYear();
    var footerHTML = `
    <footer class="main-footer global-bottom-footer">
        <div class="footer-text">
            TODOS DIREITOS RESERVADOS © ${anoAtual} 
            <a href="https://nexus-painel.ct.ws/" target="_blank" style="text-decoration: none;">
                <span class="blue-text" style="color: #007bff; font-weight: 600;">NEXUS-PAINEL</span> 
                <span class="red-heart" style="color: #dc3545;"><i class="fas fa-heart"></i></span>
            </a>
        </div>
    </footer>`;
    
    // 3. Injerta o rodapé fixo no final da classe .wrapper
    var wrapper = document.querySelector('.wrapper');
    if(wrapper) {
        wrapper.insertAdjacentHTML('beforeend', footerHTML);
    } else {
        document.body.insertAdjacentHTML('beforeend', footerHTML);
    }
});
</script>
<!-- FIM DO RODAPÉ GLOBAL -->