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

$pdo = getConexaoAtiva(); // Banco Principal
$pdo_int = getConexaoInterna(); // Banco Local (Onde os Load Balancers vão ficar)

$pdo->exec("SET NAMES utf8mb4");
$pdo_int->exec("SET NAMES utf8mb4");

// ====================================================================
// INTELIGÊNCIA ARTIFICIAL: DETECTA SE É XUI ONE OU XTREAM UI
// ====================================================================
$modo_ativo = 'interno';
try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
} catch (Exception $e) {}

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

try {
    $tabela_existe = $pdo_int->query("SHOW TABLES LIKE 'painel_config'")->rowCount() > 0;
    if ($tabela_existe) {
        $config_painel = $pdo_int->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_int->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 NO BANCO INTERNO) ---
try {
    $pdo_int->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 (No Banco Interno)
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_int->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 (No Banco Interno)
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_int->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 (No Banco Interno)
if (isset($_GET['delete_lb'])) {
    $pdo_int->prepare("DELETE FROM servidores_lb WHERE id = ?")->execute([intval($_GET['delete_lb'])]);
    header("Location: admin_lb.php"); exit;
}

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

// Busca a lista no Banco Interno
$servidores_db = $pdo_int->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>
    <link rel="stylesheet" href="tema.css">
    <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; }
        
        /* CSS OBRIGATÓRIO PARA A LOGO E MENU */
        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; transition: 0.3s; 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 { width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(0, 123, 255, 0.2); 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-category { padding: 20px 20px 8px; font-size: 11px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .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: 15px; 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); }
        .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); }
        
        /* 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; padding: 20px; box-sizing: border-box;}
        .modal-content { background: var(--bg-card); width: 100%; max-width: 400px; padding: 25px; border-radius: 12px; border: 1px solid var(--border-color); position: relative; margin: auto;}
        .modal h3 { margin-top:0; color:white; border-bottom: 1px solid var(--border-color); padding-bottom: 10px;}
        .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: 15px;}
            .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 20px; justify-content: flex-start;}
            .topbar-right { margin-left: auto; }
            .content-area { padding: 15px; padding-bottom: 100px;}
            .tab-btn { font-size: 12px; padding: 10px; }
        }
    </style>
</head>
<body>

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

    <?php include 'sidebar.php'; ?>

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; align-items:center;">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white; margin-left: 10px;">Load Balancers</h2>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-database"></i> MODO: <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></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: topiptv.tvbr.top): " 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 iniciar a instalacao..." && apt-get update && apt-get install nginx php-cli php-fpm ufw -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

cat &lt;&lt; 'EOF_RESTART' &gt; /var/www/html/restart_lb.php
&lt;?php
$chave_secreta_do_painel = "top_iptv_123";

if (!isset($_GET['key']) || $_GET['key'] !== $chave_secreta_do_painel) {
    http_response_code(403);
    die("Acesso negado.");
}

shell_exec('sudo /bin/systemctl restart nginx');
shell_exec('sudo /bin/systemctl restart php*-fpm'); 

echo "Servicos reiniciados com sucesso.";
?&gt;
EOF_RESTART

echo "www-data ALL=(ALL) NOPASSWD: /bin/systemctl restart nginx, /bin/systemctl restart php*-fpm, /usr/bin/systemctl restart nginx, /usr/bin/systemctl restart php*-fpm" | sudo tee /etc/sudoers.d/lb_restart
sudo chmod 0440 /etc/sudoers.d/lb_restart

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 = /restart_lb.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/
ufw allow 8080/tcp
ufw allow 80/tcp
systemctl restart nginx
systemctl restart php*-fpm

echo -e "\n=============================================\n  INSTALADO COM SUCESSO\n  Porta configurada: 8080\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>
        function toggleMenu() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('overlay').classList.toggle('active'); 
        }

        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>
    <script src="tema.js"></script>
</body>
</html>
