<?php
session_start();
require_once 'config.php';

$pdo = getConexaoAtiva();

// --- INÍCIO: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---
$nome_painel = 'TOP IPTV';
$logo_url = '';
$cor_primaria = '#007bff';

try {
    $tabela_existe = $pdo->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($config_painel) {
            $nome_painel = !empty($config_painel['nome_painel']) ? $config_painel['nome_painel'] : $nome_painel;
            $logo_url = !empty($config_painel['logo_url']) ? $config_painel['logo_url'] : $logo_url;
            $cor_primaria = !empty($config_painel['cor_primaria']) ? $config_painel['cor_primaria'] : $cor_primaria;
        }
    }
} catch (Exception $e) {}
// --- FIM: BUSCA DE PERSONALIZAÇÃO DINÂMICA ---

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }

$role = $_SESSION['user_role'] ?? 'reseller';
$my_id = $_SESSION['user_id'];
$nome_usuario = $_SESSION['username'] ?? 'Usuário';

// BLOQUEIO DE SEGURANÇA: SÓ ADMIN ENTRA AQUI
if ($role !== 'admin') {
    header("Location: dashboard.php");
    exit;
}

try {
    $user_credits = $pdo->query("SELECT credits FROM reg_users WHERE id = $my_id")->fetchColumn() ?: 0;
} catch (Exception $e) { $user_credits = 0; }

// --- LÓGICA DO BANCO DE DADOS (CRIA TABELA DE LBs SE NÃO EXISTIR) ---
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `servidores_lb` (
        `id` int(11) AUTO_INCREMENT PRIMARY KEY,
        `nome` varchar(100) NOT NULL,
        `ip_servidor` varchar(50) NOT NULL,
        `porta` int(11) DEFAULT 80,
        `status` int(11) DEFAULT 1,
        `data_criacao` timestamp DEFAULT CURRENT_TIMESTAMP
    )");
} catch (PDOException $e) {}

$mensagem = "";

// --- AÇÕES DO LOAD BALANCER ---

// Adicionar LB
if (isset($_POST['action_add_lb'])) {
    $nome = trim($_POST['nome_lb']);
    $ip = trim($_POST['ip_lb']);
    $porta = intval($_POST['porta_lb']);

    if (!empty($nome) && !empty($ip)) {
        $pdo->prepare("INSERT INTO servidores_lb (nome, ip_servidor, porta) VALUES (?, ?, ?)")->execute([$nome, $ip, $porta]);
        $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Servidor Load Balancer adicionado com sucesso!</div>";
    }
}

// Editar LB
if (isset($_POST['action_edit_lb'])) {
    $id_edit = intval($_POST['edit_id_lb']);
    $nome = trim($_POST['edit_nome_lb']);
    $ip = trim($_POST['edit_ip_lb']);
    $porta = intval($_POST['edit_porta_lb']);

    if ($id_edit > 0 && !empty($nome) && !empty($ip)) {
        $pdo->prepare("UPDATE servidores_lb SET nome = ?, ip_servidor = ?, porta = ? WHERE id = ?")->execute([$nome, $ip, $porta, $id_edit]);
        $mensagem = "<div class='alert success'><i class='fas fa-check-circle'></i> Servidor atualizado com sucesso!</div>";
    }
}

// Excluir LB
if (isset($_GET['delete_lb'])) {
    $pdo->prepare("DELETE FROM servidores_lb WHERE id = ?")->execute([intval($_GET['delete_lb'])]);
    header("Location: admin_lb.php"); exit;
}

// Ligar/Desligar LB no Painel
if (isset($_GET['toggle_lb'])) {
    $pdo->prepare("UPDATE servidores_lb SET status = IF(status=1, 0, 1) WHERE id = ?")->execute([intval($_GET['toggle_lb'])]);
    header("Location: admin_lb.php"); exit;
}

$servidores_db = $pdo->query("SELECT * FROM servidores_lb ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
$total_lbs = count($servidores_db);
$online_lbs = 0;

$servidores = [];

// =================================================================================
// RADAR DE CONEXÃO BLINDADO: Ignora falsos negativos de SSL e Lentidão
// =================================================================================
foreach($servidores_db as $s) {
    $s['real_status'] = 'OFFLINE';
    $s['cpu'] = 0;
    $s['ram'] = 0;
    $s['disco'] = 0;

    if($s['status'] == 1) {
        $ip = trim($s['ip_servidor']);
        $porta_lb = !empty($s['porta']) ? $s['porta'] : 80; 
        
        // Define o protocolo dinamicamente
        $protocolo = ($porta_lb == 443) ? 'https' : 'http';
        $url = "{$protocolo}://{$ip}:{$porta_lb}/lb_stats.php";
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 6); // Aumentado para 6s para não derrubar atoa de manhã
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Segue redirecionamentos se a porta 8080 exigir
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Ignora bloqueios de SSL falso
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $resultado = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        // Aceita 200 (OK) e redics amigáveis
        if (($http_code == 200 || $http_code == 301 || $http_code == 302) && $resultado) {
            $dados = json_decode($resultado, true);
            if (isset($dados['cpu'])) {
                $s['real_status'] = 'ONLINE';
                $s['cpu'] = (float)$dados['cpu'];
                $s['ram'] = (float)$dados['ram'];
                $s['disco'] = (float)$dados['disco'];
                $online_lbs++;
            }
        }
    }
    $servidores[] = $s;
}
// =================================================================================

?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Load Balancer - <?php echo htmlspecialchars($nome_painel); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root { --bg-dark: #121519; --bg-sidebar: #1e2227; --bg-card: #272c33; --text-main: #d1d5da; --text-muted: #8a94a1; --accent: <?php echo $cor_primaria; ?>; --border-color: #3a4149; --success: #28a745; --danger: #dc3545; --warning: #f39c12; --info: #17a2b8; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        .sidebar { width: 260px; background-color: var(--bg-sidebar); display: flex; flex-direction: column; transition: 0.3s; border-right: 1px solid var(--border-color); z-index: 1001; flex-shrink: 0; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-logo { max-width: 180px; max-height: 55px; object-fit: contain; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(255, 255, 255, 0.05); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 14px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i:first-child { color: var(--accent); }
        
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 11px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 20px 8px; font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .logout-btn { padding: 15px; background-color: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; margin-top: auto; }

        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 30px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); }
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 22px; cursor: pointer; padding: 5px; }
        .mode-badge { padding: 6px 15px; background: rgba(40, 167, 69, 0.15); color: var(--success); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--success); white-space: nowrap; }
        
        .content-area { padding: 30px; flex: 1; }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; }
        .alert.success { background: rgba(40, 167, 69, 0.1); border: 1px solid var(--success); color: var(--success); }

        .btn-filter { background: var(--accent); color: white; border: none; padding: 12px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; width: 100%; transition: 0.2s; }
        .btn-filter:hover { filter: brightness(1.1); }
        
        /* TUTORIAL BOX */
        .tutorial-box { background: rgba(0, 0, 0, 0.2); border: 1px solid var(--border-color); border-radius: 10px; padding: 25px; line-height: 1.6; margin-bottom: 25px; }
        .tutorial-box h3 { color: var(--accent); margin-top: 0; display: flex; align-items: center; gap: 10px; }
        .step-block { margin-bottom: 20px; }
        .step-title { font-weight: bold; color: white; margin-bottom: 8px; font-size: 15px; }
        .code-block { background: #0f1114; border: 1px solid #3a4149; padding: 15px; border-radius: 6px; font-family: monospace; color: #a5d6ff; position: relative; overflow-x: auto; white-space: pre-wrap; word-break: break-all; }
        .copy-btn { position: absolute; top: 10px; right: 10px; background: #2c3138; border: none; color: white; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-size: 11px; }
        .copy-btn:hover { background: var(--accent); }
        .info-card { background: rgba(243, 156, 18, 0.1); border-left: 4px solid var(--warning); padding: 15px; color: #d1d5da; font-size: 13px; margin-bottom: 20px; }
        
        /* TABS */
        .tab-container { display: flex; gap: 10px; margin-bottom: 15px; flex-wrap: wrap; }
        .tab-btn { background: #1e2227; color: white; border: 1px solid var(--border-color); padding: 12px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; transition: 0.2s; display: flex; align-items: center; gap: 8px; flex: 1; justify-content: center; }
        .tab-btn.active { background: var(--accent); border-color: var(--accent); }
        .tab-btn:hover:not(.active) { filter: brightness(1.2); }

        /* DESIGN DOS CARDS DE LOAD BALANCER */
        .lb-grid { display: flex; flex-direction: column; gap: 20px; margin-top: 20px; }
        .lb-card { background: #ffffff; border-radius: 12px; padding: 20px; color: #333; font-family: 'Segoe UI', sans-serif; box-shadow: 0 4px 15px rgba(0,0,0,0.1); position: relative;}
        
        .lb-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2px; }
        .lb-title { font-size: 18px; font-weight: bold; color: #111; display: flex; align-items: center; gap: 8px; margin: 0; }
        .icon-check { color: #28a745; font-size: 16px; }
        .icon-off { color: #dc3545; font-size: 16px; }
        
        .lb-ip { font-size: 13px; color: #888; margin-top: 2px; margin-bottom: 20px; margin-left: 24px; }
        
        .status-badge { background: #28a745; color: white; padding: 6px 14px; border-radius: 6px; font-weight: bold; font-size: 12px; }
        .status-badge.off { background: #dc3545; }
        .status-badge.disabled { background: #6c757d; }
        
        .stats-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; row-gap: 20px; column-gap: 30px; margin-bottom: 25px; }
        
        .stat-item { display: flex; flex-direction: column; }
        .stat-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
        .stat-label { font-size: 12px; font-weight: bold; color: #a0a0a0; text-transform: uppercase; }
        .stat-value { font-size: 13px; font-weight: bold; color: #333; }
        
        .progress-bg { background: #f0f0f0; height: 6px; border-radius: 3px; overflow: hidden; width: 100%; }
        .progress-bar { height: 100%; border-radius: 3px; }
        
        .pb-ram { background: #007bff; }
        .pb-cpu { background: #e0e0e0; }
        .pb-disco { background: #6c757d; }
        .pb-rede { background: #28a745; }

        .lb-actions { display: flex; gap: 10px; }
        .btn-lb { flex: 1; padding: 12px; border-radius: 8px; font-weight: bold; font-size: 14px; cursor: pointer; text-align: center; text-decoration: none; transition: 0.2s; background: transparent; }
        .btn-lb-edit { border: 1px solid #007bff; color: #007bff; }
        .btn-lb-edit:hover { background: #007bff; color: white; }
        
        .btn-lb-toggle { border: 1px solid #f39c12; color: #f39c12; }
        .btn-lb-toggle:hover { background: #f39c12; color: white; }
        
        .btn-lb-del { border: 1px solid #dc3545; color: #dc3545; flex: 0 0 50px; display: flex; align-items: center; justify-content: center; font-size: 16px; background: rgba(220,53,69,0.05); }
        .btn-lb-del:hover { background: #dc3545; color: white; }

        .overlay-offline { position: absolute; top:0; left:0; width:100%; height:100%; background:rgba(255,255,255,0.6); z-index:10; border-radius: 12px; display:flex; align-items:center; justify-content:center; flex-direction:column; pointer-events: none;}
        .overlay-offline span { background:#dc3545; color:white; padding: 5px 15px; border-radius:20px; font-weight:bold; font-size:14px; margin-bottom:50px;}

        /* MODALS */
        .modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); align-items: center; justify-content: center; }
        .modal-content { background: var(--bg-card); width: 90%; max-width: 400px; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); }
        .form-group-modal { margin-bottom: 15px; }
        .form-group-modal label { display: block; margin-bottom: 5px; font-size: 12px; color: var(--text-muted); }
        .form-group-modal input { width: 100%; padding: 12px; background: #121519; border: 1px solid var(--border-color); color: white; border-radius: 6px; box-sizing: border-box; }
        .btn-save-modal { width: 100%; padding: 12px; background: var(--accent); border: none; color: white; border-radius: 6px; font-weight: bold; cursor: pointer; margin-top: 5px; }

        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }

        @media (max-width: 768px) {
            .menu-toggle { display: block; margin-right: 10px; }
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .topbar { padding: 15px; flex-wrap: nowrap; }
            .topbar h2 { font-size: 15px !important; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 50%; }
            .content-area { padding: 15px; }
            .tab-btn { font-size: 12px; padding: 10px; }
        }
    </style>
</head>
<body>

    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>

    <nav class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <?php if(!empty($logo_url) && file_exists($logo_url)): ?>
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="sidebar-logo">
            <?php else: ?>
                <?php echo htmlspecialchars($nome_painel); ?>
            <?php endif; ?>
        </div>
        <div class="user-info">
            <div style="color:white; font-size: 14px;">Olá, <strong><?php echo htmlspecialchars($nome_usuario); ?></strong></div>
            <span class="badge"><?php echo $role === 'admin' ? 'Administrador' : 'Revendedor'; ?></span>
            <div class="credits-badge"><i class="fas fa-coins"></i> Saldo: <?php echo number_format($user_credits, 1); ?></div>
        </div>
        
        <div class="menu-list">
            <a href="dashboard.php" class="menu-item active"><i class="fas fa-chart-line"></i> Dashboard</a>
            <a href="perfil.php" class="menu-item active"><i class="fas fa-user-circle"></i> Meu Perfil</a>
            
            <a href="lancamentos.php" class="menu-item active"><i class="fas fa-fire"></i> Últimos Adicionados</a>
            
            <a href="ajuda.php" class="menu-item active"><i class="fas fa-question-circle"></i> Material de Ajuda</a>
            <a href="meus_links.php" class="menu-item active"><i class="fas fa-link" style="color: var(--accent);"></i> Central de Links</a>
            
            <div class="menu-category">Gestão</div>
            <a href="clientes.php" class="menu-item active"><i class="fas fa-users"></i> Clientes IPTV</a>
            <a href="testes.php" class="menu-item active"><i class="fas fa-vial"></i> Gerenciar Testes</a>
            <a href="online.php" class="menu-item active"><i class="fas fa-plug"></i> Clientes Online</a>
            <a href="revendedores.php" class="menu-item active"><i class="fas fa-user-tie"></i> Revendedores</a>
            <a href="migrar_clientes.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Migrar Clientes</a>
            <a href="logs_creditos.php" class="menu-item active"><i class="fas fa-list-alt"></i> Extrato de Créditos</a>
            <a href="marketing.php" class="menu-item active"><i class="fas fa-bullhorn"></i> Central de Marketing</a>
            
            
            <div class="menu-category">Clientes P2P</div>
            <a href="p2p_clientes.php" class="menu-item active"><i class="fas fa-tv"></i> Clientes P2P</a>
            
            <?php if (!empty($api_conf['api_binstream_url'])): ?>
                <a href="binstream_p2p.php" class="menu-item active"><i class="fas fa-tv"></i> Binstream P2P</a>
            <?php endif; ?>

 <?php if($role === 'admin'): ?>
<div class="menu-category">Gerar Licença</div>
<a href="admin_licencas.php" class="menu-item active"> <i class="fas fa-key" style="color: #28a745;"></i> <span>Gerador SaaS</span> </a>
<?php endif; ?>

<div class="menu-category">Api WhatsApp</div>
                <a href="integracoes_api_whatsapp.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API WhatsApp</a>


            <div class="menu-category">Integração & Cobrança</div>
            <a href="pagamentos.php" class="menu-item active"><i class="fas fa-dollar-sign"></i> Pagamento Automático</a>
            <a href="cobranca.php" class="menu-item active"><i class="fas fa-comment-dollar"></i> Central de Cobrança</a>
            <a href="admin_planos.php" class="menu-item active"><i class="fas fa-tags"></i> Meus Planos de Venda</a>
            <a href="comprar_creditos.php" class="menu-item active"><i class="fas fa-shopping-cart"></i> Comprar Créditos</a>
          
            <div class="menu-item active" onclick="toggleSubmenu('appsSub')">
                <i class="fas fa-rocket"></i><span>Aplicações</span><i class="fas fa-chevron-down arrow-icon" id="arrow-appsSub"></i>

            </div>
            <div class="submenu" id="appsSub">
                <a href="loja_apps.php" class="menu-item active"><i class="fas fa-store"></i> Loja de Aplicativos</a>
                <?php if($role === 'admin'): ?>
                    <a href="admin_loja.php" class="menu-item active"><i class="fas fa-cogs"></i> Gerenciar Loja</a>
                <?php endif; ?>
                <a href="chatbot.php" class="menu-item active"><i class="fab fa-whatsapp"></i> Chatbot Automático</a>
            </div>
           <a href="admin_player_revenda.php" class="menu-item active"><i class="fas fa-play-circle"></i> WebPlayer</a>
            
   <div class="menu-category">Segurança</div>
            <a href="historico_logins.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sessões Ativas</a>

            <?php if($role === 'admin'): ?>
                <div class="menu-category">Administração</div>
                <a href="admin_monitor.php" class="menu-item active"><i class="fas fa-heartbeat"></i> Monitor do Servidor</a>
                <a href="admin_template.php" class="menu-item active"><i class="fas fa-edit"></i> Editor de Template</a>
                <a href="admin_token.php" class="menu-item active"><i class="fas fa-user-secret"></i> Token Links Xui</a>
                <a href="admin_lb.php" class="menu-item active"><i class="fas fa-server"></i> Load Balancers</a>
                <a href="guia_cloudflare.php" class="menu-item active"><i class="fas fa-cloud"></i> Guia Cloudflare</a>
                 <a href="admin_loja_creditos.php" class="menu-item active"><i class="fas fa-store"></i> Configurar Loja (PIX)</a>
                 <a href="integracoes_api.php" class="menu-item active"><i class="fas fa-plug"></i> Integrações API</a>
                 <a href="admin_robo.php" class="menu-item active"><i class="fas fa-robot"></i> Robô de Cobrança</a>
                 <a href="admin_anti_bloqueio.php" class="menu-item active"><i class="fas fa-bolt"></i> Botão de Pânico</a>
                 <a href="admin_anti_fraude.php" class="menu-item active"><i class="fas fa-user-secret"></i> Radar Anti-Fraude</a>  
                 <a href="admin_watchdog.php" class="menu-item active"><i class="fas fa-dog"></i> Watchdog LB</a>  
                 
                 <a href="admin_epg_sync.php" class="menu-item active">
        <i class="fas fa-clock"></i> Sincronizar EPG
    </a>
    

 <div class="menu-item active" onclick="toggleSubmenu('painelSub')">
                    <i class="fas fa-desktop"></i><span>Painel</span><i class="fas fa-chevron-down arrow-icon" id="arrow-painelSub"></i>
                </div>
                <div class="submenu" id="painelSub">
                    <a href="personalizacao.php" class="menu-item active"><i class="fas fa-paint-brush"></i> Personalização</a>
                </div>
             
                <div class="menu-item active" onclick="toggleSubmenu('adminSub')">
                    <i class="fas fa-toolbox"></i><span>Ferramentas</span><i class="fas fa-chevron-down arrow-icon" id="arrow-adminSub"></i>
                </div>
                <div class="submenu" id="adminSub">
                    <a href="importar.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador</a>
                    <a href="importar3.php" class="menu-item active"><i class="fas fa-file-import"></i> Importador Turbo</a>
                    <a href="dns_manager.php" class="menu-item active"><i class="fas fa-link"></i> Alterar DNS</a>
                    <a href="admin_logos.php" class="menu-item active"><i class="fas fa-image"></i> Alterar Logos</a>
                    <a href="mover_conteudos.php" class="menu-item active"><i class="fas fa-exchange-alt"></i> Mover Conteúdos</a>
                    <a href="limpeza.php" class="menu-item active"><i class="fas fa-trash-alt"></i> Limpeza de Dados</a>
                    <a href="limpar_duplicados.php" class="menu-item active"><i class="fas fa-copy"></i> Limpeza de Duplicados</a>
                    <a href="backup.php" class="menu-item active"><i class="fas fa-database"></i> Backup do Sistema</a>
                    <a href="seguranca.php" class="menu-item active"><i class="fas fa-shield-alt"></i> Sistema de Segurança</a>
                    <a href="configuracoes.php" class="menu-item active"><i class="fas fa-tools"></i> Configurações</a>
                </div>

                 <?php if($role === 'admin'): ?>
    <div class="menu-category">Financeiro</div>
     <!-- NOVO MENU FINANCEIRO COM SUBMENU -->
            <div class="menu-item active" onclick="toggleSubmenu('finSub')">
                <i class="fas fa-hand-holding-usd"></i><span>Financeiro</span><i class="fas fa-chevron-down arrow-icon rotate" id="arrow-finSub"></i>
            </div>
            <div class="submenu" id="finSub" style="display: block;">
                <a href="financeiro.php" class="menu-item active">Faturamento</a>
            </div>
    
    <?php endif; ?>

                <div class="menu-category">Conteúdos</div>
                <a href="categorias.php" class="menu-item active"><i class="fas fa-folder-open"></i><span>Categorias</span></a>
                <div class="menu-item active" onclick="toggleSubmenu('contentSub')">
                    <i class="fas fa-layer-group"></i><span>Mídias</span><i class="fas fa-chevron-down arrow-icon" id="arrow-contentSub"></i>
                </div>
                <div class="submenu" id="contentSub">
                    <a href="bouquets.php" class="menu-item active">Editar Bouquets</a>
                    <a href="canais.php" class="menu-item active">Canais Ao Vivo</a>
                    <a href="filmes.php" class="menu-item active">Filmes (VOD)</a>
                    <a href="series.php" class="menu-item active">Séries</a>
                </div>
                 <a href="admin_autofix_vod.php" class="menu-item active"><i class="fas fa-magic"></i> Auto-Fix TMDB</a>
            <?php endif; ?>
        </div>
        <a href="logout.php" class="logout-btn"><i class="fas fa-power-off"></i> Sair</a>
    </nav>

    <div class="main-content">
        <header class="topbar">
            <button class="menu-toggle" onclick="toggleMenu()" style="background:none; border:none; color:white; font-size:22px; cursor:pointer;"><i class="fas fa-bars"></i></button>
            <h2 style="margin:0; font-size: 18px; color:white; margin-left: 10px;">Load Balancer (LB)</h2>
            <div class="topbar-right">
                <span class="mode-badge" style="background:rgba(243,156,18,0.1); color:var(--warning); border-color:var(--warning);"><i class="fas fa-lock"></i> SÓ ADMIN</span>
            </div>
        </header>

        <div class="content-area">
            <?php echo $mensagem; ?>

            <div style="display: flex; gap: 20px; margin-bottom: 25px; flex-wrap: wrap;">
                <div style="background: var(--bg-card); border: 1px solid var(--border-color); padding: 20px; border-radius: 10px; flex: 1; min-width: 200px;">
                    <h3 style="margin: 0; color: var(--text-muted); font-size: 12px; text-transform: uppercase;">Servidores Cadastrados</h3>
                    <span style="font-size: 28px; font-weight: bold; color: white;"><?php echo $total_lbs; ?></span>
                </div>
                <div style="background: var(--bg-card); border: 1px solid var(--border-color); padding: 20px; border-radius: 10px; flex: 1; min-width: 200px;">
                    <h3 style="margin: 0; color: var(--text-muted); font-size: 12px; text-transform: uppercase;">LBs Online</h3>
                    <span style="font-size: 28px; font-weight: bold; color: var(--success);"><?php echo $online_lbs; ?></span>
                </div>
            </div>

            <div class="tab-container">
                <button class="tab-btn active" id="btn-tuto-interno" onclick="switchTab('interno')"><i class="fas fa-magic"></i> Instalador Automático de Load Balancer</button>
                <button class="tab-btn" id="btn-tuto-externo" onclick="switchTab('externo')"><i class="fas fa-server"></i> LB Modo Externo (Xtream UI)</button>
            </div>

            <div id="tuto_interno" class="tutorial-box">
                <h3 style="color: #28a745;"><i class="fas fa-robot"></i> Super Script de Instalação Interativa</h3>
                <p style="color:var(--text-muted);">Copie o bloco inteiro abaixo e cole no terminal SSH do seu Load Balancer (VPS nova). O script vai conversar com você, perguntar o IP ou Domínio do seu painel e fazer TUDO sozinho: instala Nginx, configura o proxy, ajusta HTTPS e já ativa o leitor de gráficos. <b>À prova de erros!</b></p>
                
                <div class="step-block">
                    <div class="code-block" id="code-int-1">clear && echo -e "\n=============================================\n   INSTALADOR LOAD BALANCER - TOP IPTV\n=============================================\n" && read -p "Digite o IP ou Dominio do Painel Principal (Ex: topiptv1.brtvs.top ou 178.105.10.253): " ALVO && read -p "O painel principal possui SSL/HTTPS? (s/n): " USA_SSL && if [[ "$USA_SSL" == "s" || "$USA_SSL" == "S" ]]; then PROTOCOLO="https"; SSL_ON="proxy_ssl_server_name on;"; else PROTOCOLO="http"; SSL_ON=""; fi && echo -e "\nConfigurando proxy para: $PROTOCOLO://$ALVO" && read -p "Pressione ENTER para instalar ou CTRL+C para cancelar..." && apt-get update && apt-get install nginx php-cli php-fpm -y && mkdir -p /var/www/html && cat &lt;&lt; 'EOF_PHP' &gt; /var/www/html/lb_stats.php
&lt;?php
header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json");
$cpu = sys_getloadavg()[0] ?? 0;
$ram = shell_exec("free | grep Mem | awk '{print \$3/\$2 * 100.0}'");
$disk = shell_exec("df / | grep /$ | awk '{print \$5}' | sed 's/%//g'");
echo json_encode(["cpu" => round((float)$cpu, 1), "ram" => round((float)$ram, 1), "disco" => round((float)$disk, 1)]);
?&gt;
EOF_PHP
SOCK=$(find /var/run/php/ -name "php*-fpm.sock" | head -n 1) && cat &lt;&lt; EOF_NGINX &gt; /etc/nginx/sites-available/iptv.conf
server {
    listen 8080;
    server_name _;
    location = /lb_stats.php {
        root /var/www/html;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:$SOCK;
    }
    location / {
        proxy_pass $PROTOCOLO://$ALVO;
        proxy_set_header Host $ALVO;
        $SSL_ON
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    }
}
EOF_NGINX
rm -f /etc/nginx/sites-enabled/default && ln -sf /etc/nginx/sites-available/iptv.conf /etc/nginx/sites-enabled/ && systemctl restart nginx && echo -e "\n=============================================\n INSTALADO COM SUCESSO \n O Sensor LB e o Proxy estao rodando \n=============================================\n"
<button class="copy-btn" onclick="copyCode('code-int-1')"><i class="fas fa-copy"></i> Copiar Código</button></div>
                </div>
            </div>

            <div id="tuto_externo" class="tutorial-box" style="display:none;">
                <h3><i class="fas fa-server"></i> Instalação Load Balancer - Modo Externo (Xtream UI Oficial)</h3>
                <p style="color:var(--text-muted);">Use este modo se você possuir a licença do Xtream UI e quiser integrar o banco de dados oficial do LB.</p>
                
                <div class="step-block">
                    <div class="step-title">1. Acesse o SSH do novo servidor LB e rode o script oficial de instalação do Xtream UI:</div>
                    <div class="code-block" id="code-ext-1">apt-get update && apt-get install libfreetype6 -y && wget https://xtream-ui.com/install/install.py && sudo python install.py
<button class="copy-btn" onclick="copyCode('code-ext-1')"><i class="fas fa-copy"></i> Copiar</button></div>
                </div>
                
                <div class="step-block">
                    <div class="step-title">2. No menu de instalação do Xtream UI, selecione a opção de "Load Balancer" e insira o IP do seu painel principal e a senha do banco de dados MySQL quando for solicitado.</div>
                </div>
            </div>

            <div style="margin-bottom:20px;">
                <button class="btn-filter" onclick="document.getElementById('modalAddLB').style.display='flex'">Adicionar Servidor na Lista</button>
            </div>

            <div class="lb-grid">
                <?php if(empty($servidores)): ?>
                    <div style="text-align:center; padding:30px; color:var(--text-muted);">Nenhum Load Balancer cadastrado.</div>
                <?php else: ?>
                    <?php foreach($servidores as $s): ?>
                        <div class="lb-card">
                            
                            <?php if($s['real_status'] === 'OFFLINE' || $s['status'] == 0): ?>
                            <div class="overlay-offline">
                                <span><i class="fas fa-plug"></i> SERVIDOR OFFLINE</span>
                            </div>
                            <?php endif; ?>

                            <div class="lb-header">
                                <h3 class="lb-title">
                                    <?php if($s['status'] == 1 && $s['real_status'] === 'ONLINE'): ?>
                                        <i class="fas fa-check-circle icon-check"></i>
                                    <?php else: ?>
                                        <i class="fas fa-times-circle icon-off"></i>
                                    <?php endif; ?>
                                    <?php echo htmlspecialchars($s['nome']); ?>
                                </h3>
                                
                                <?php if($s['status'] == 0): ?>
                                    <span class="status-badge disabled">DESATIVADO</span>
                                <?php elseif($s['real_status'] === 'ONLINE'): ?>
                                    <span class="status-badge">ON</span>
                                <?php else: ?>
                                    <span class="status-badge off">OFF</span>
                                <?php endif; ?>
                            </div>
                            
                            <div class="lb-ip"><?php echo htmlspecialchars($s['ip_servidor']); ?></div>
                            
                            <div class="stats-grid">
                                <div class="stat-item">
                                    <div class="stat-header">
                                        <span class="stat-label">RAM</span>
                                        <span class="stat-value"><?php echo $s['ram']; ?>%</span>
                                    </div>
                                    <div class="progress-bg"><div class="progress-bar pb-ram" style="width: <?php echo $s['ram']; ?>%;"></div></div>
                                </div>
                                
                                <div class="stat-item">
                                    <div class="stat-header">
                                        <span class="stat-label">CPU</span>
                                        <span class="stat-value"><?php echo $s['cpu']; ?>%</span>
                                    </div>
                                    <div class="progress-bg"><div class="progress-bar pb-cpu" style="width: <?php echo $s['cpu']; ?>%;"></div></div>
                                </div>
                                
                                <div class="stat-item">
                                    <div class="stat-header">
                                        <span class="stat-label">DISCO</span>
                                        <span class="stat-value"><?php echo $s['disco']; ?>%</span>
                                    </div>
                                    <div class="progress-bg"><div class="progress-bar pb-disco" style="width: <?php echo $s['disco']; ?>%;"></div></div>
                                </div>
                                
                                <div class="stat-item">
                                    <div class="stat-header">
                                        <span class="stat-label">REDE</span>
                                        <span class="stat-value">0 GB</span>
                                    </div>
                                    <div class="progress-bg"><div class="progress-bar pb-rede" style="width: 0%;"></div></div>
                                </div>
                            </div>
                            
                            <div class="lb-actions" style="position:relative; z-index: 11;">
                                <button type="button" class="btn-lb btn-lb-edit" onclick="openEditLbModal(<?php echo $s['id']; ?>, '<?php echo htmlspecialchars($s['nome'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($s['ip_servidor'], ENT_QUOTES); ?>', <?php echo $s['porta']; ?>)">Editar</button>
                                
                                <a href="?toggle_lb=<?php echo $s['id']; ?>" class="btn-lb btn-lb-toggle">
                                    <?php echo $s['status'] == 1 ? 'Desativar' : 'Ativar'; ?>
                                </a>
                                <a href="?delete_lb=<?php echo $s['id']; ?>" class="btn-lb btn-lb-del" onclick="return confirm('Excluir este servidor definitivamente?')"><i class="fas fa-trash"></i></a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <div id="modalAddLB" class="modal">
        <div class="modal-content">
            <h3 style="color:white; margin-top:0; border-bottom:1px solid var(--border-color); padding-bottom:10px;">Adicionar Load Balancer</h3>
            <form method="POST">
                <input type="hidden" name="action_add_lb" value="1">
                <div class="form-group-modal">
                    <label>Nome (Ex: Servidor BR 01)</label>
                    <input type="text" name="nome_lb" required>
                </div>
                <div class="form-group-modal">
                    <label>IP do Servidor (Ex: 192.168.0.100)</label>
                    <input type="text" name="ip_lb" required>
                </div>
                <div class="form-group-modal">
                    <label>Porta (Padrão: 80)</label>
                    <input type="number" name="porta_lb" value="80" required>
                </div>
                <button type="submit" class="btn-save-modal">SALVAR SERVIDOR</button>
                <button type="button" onclick="document.getElementById('modalAddLB').style.display='none'" style="width:100%; background:transparent; border:none; color:var(--text-muted); margin-top:10px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <div id="modalEditLB" class="modal">
        <div class="modal-content">
            <h3 style="color:white; margin-top:0; border-bottom:1px solid var(--border-color); padding-bottom:10px;"><i class="fas fa-edit" style="color:var(--info);"></i> Editar Load Balancer</h3>
            <form method="POST">
                <input type="hidden" name="action_edit_lb" value="1">
                <input type="hidden" name="edit_id_lb" id="edit_id_lb">
                <div class="form-group-modal">
                    <label>Nome do Servidor</label>
                    <input type="text" name="edit_nome_lb" id="edit_nome_lb" required>
                </div>
                <div class="form-group-modal">
                    <label>IP do Servidor</label>
                    <input type="text" name="edit_ip_lb" id="edit_ip_lb" required>
                </div>
                <div class="form-group-modal">
                    <label>Porta (Padrão: 80)</label>
                    <input type="number" name="edit_porta_lb" id="edit_porta_lb" required>
                </div>
                <button type="submit" class="btn-save-modal" style="background:var(--info);">SALVAR ALTERAÇÕES</button>
                <button type="button" onclick="document.getElementById('modalEditLB').style.display='none'" style="width:100%; background:transparent; border:none; color:var(--text-muted); margin-top:10px; cursor:pointer;">Cancelar</button>
            </form>
        </div>
    </div>

    <script>
        const btnMenu = document.getElementById('btn-menu');
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        function toggleMenu() { sidebar.classList.toggle('active'); overlay.classList.toggle('active'); }

        function toggleSubmenu(id) {
            const sub = document.getElementById(id);
            const arrow = document.getElementById('arrow-' + id);
            if (sub.style.display === "block") { sub.style.display = "none"; if(arrow) arrow.classList.remove('rotate'); } 
            else { sub.style.display = "block"; if(arrow) arrow.classList.add('rotate'); }
        }

        function switchTab(tabId) {
            document.getElementById('tuto_interno').style.display = 'none';
            document.getElementById('tuto_externo').style.display = 'none';
            
            document.getElementById('btn-tuto-interno').classList.remove('active');
            document.getElementById('btn-tuto-externo').classList.remove('active');
            
            document.getElementById('tuto_' + tabId).style.display = 'block';
            document.getElementById('btn-tuto-' + tabId).classList.add('active');
        }

        // Função para abrir o modal de edição e preencher os dados
        function openEditLbModal(id, nome, ip, porta) {
            document.getElementById('edit_id_lb').value = id;
            document.getElementById('edit_nome_lb').value = nome;
            document.getElementById('edit_ip_lb').value = ip;
            document.getElementById('edit_porta_lb').value = porta;
            document.getElementById('modalEditLB').style.display = 'flex';
        }

        function copyCode(id) {
            let codeBlock = document.getElementById(id);
            let clone = codeBlock.cloneNode(true);
            let btn = clone.querySelector('.copy-btn');
            if (btn) clone.removeChild(btn); 
            
            let textToCopy = clone.textContent || clone.innerText;
            
            navigator.clipboard.writeText(textToCopy.trim()).then(function() {
                let originalBtn = codeBlock.querySelector('.copy-btn');
                let originalHtml = originalBtn.innerHTML;
                originalBtn.innerHTML = '<i class="fas fa-check"></i> Copiado!';
                originalBtn.style.background = '#28a745';
                setTimeout(function() {
                    originalBtn.innerHTML = originalHtml;
                    originalBtn.style.background = '#2c3138';
                }, 2000);
            });
        }
    </script>
</body>
</html>