<?php
ob_start(); // Trava o envio do HTML até o PHP processar 100% dos cálculos e pings
session_start();
require_once 'conexao.php';

// --- 1. TRAVA DE SEGURANÇA TOTAL (KILL SWITCH) ---
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php"); exit;
}

$isAdmin = (strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];

// --- BUSCAR DADOS EXTRAS PARA O MODAL DE PERFIL (Baseado nas fotos) ---
$p_first_name = $usuarioLogado;
$p_last_name = '';
$p_email = '';
$p_celular = '';
$p_data_nasc = '';
$p_criado = '';

try {
    $dadosPerfil = false;

    // 1. Primeiro verifica na tabela admin (se for admin)
    if ($isAdmin) {
        $st_pf = $connUser->prepare("SELECT * FROM admin WHERE usuario = ? LIMIT 1");
        $st_pf->execute([$usuarioLogado]);
        $dadosPerfil = $st_pf->fetch(PDO::FETCH_ASSOC);
    }
    
    // 2. Se não for admin ou não encontrou, verifica revenda
    if (!$dadosPerfil) {
        $st_pf = $connUser->prepare("SELECT * FROM rev WHERE usuario = ? LIMIT 1");
        $st_pf->execute([$usuarioLogado]);
        $dadosPerfil = $st_pf->fetch(PDO::FETCH_ASSOC);
    }
    
    // 3. Se ainda não encontrou, verifica usuário normal
    if(!$dadosPerfil) {
        $st_pf = $connUser->prepare("SELECT * FROM usuario WHERE usuario = ? LIMIT 1");
        $st_pf->execute([$usuarioLogado]);
        $dadosPerfil = $st_pf->fetch(PDO::FETCH_ASSOC);
    }

    if($dadosPerfil) {
        $p_first_name = !empty($dadosPerfil['nome']) ? $dadosPerfil['nome'] : $usuarioLogado;
        $p_last_name = $dadosPerfil['sobrenome'] ?? '';
        $p_email = $dadosPerfil['email'] ?? '';
        $p_celular = (!empty($dadosPerfil['celular'])) ? $dadosPerfil['celular'] : ($dadosPerfil['whatsapp'] ?? '');
        
        // Tratar a data para exibição correta (dd/mm/yyyy)
        if (!empty($dadosPerfil['data_nascimento']) && $dadosPerfil['data_nascimento'] != '0000-00-00 00:00:00') {
            $p_data_nasc = date('d/m/Y', strtotime($dadosPerfil['data_nascimento']));
        }
        
        $p_criado = $dadosPerfil['data_cadastro'] ?? '';
    }
} catch(Exception $e){}


// --- SALVAR INFORMAÇÕES DO PERFIL ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao_perfil']) && $_POST['acao_perfil'] === 'salvar') {
    $senha_nova = trim($_POST['senha_perfil'] ?? '');
    
    // Define se o usuário está na tabela 'admin', 'rev' ou 'usuario'
    $tb_alvo = 'rev';
    
    if ($isAdmin) {
        $chk2 = $connUser->prepare("SELECT id FROM admin WHERE usuario = ? LIMIT 1");
        $chk2->execute([$usuarioLogado]);
        if($chk2->fetch()) {
            $tb_alvo = 'admin';
        }
    }

    if ($tb_alvo !== 'admin') {
        $chk = $connUser->prepare("SELECT id FROM rev WHERE usuario = ? LIMIT 1");
        $chk->execute([$usuarioLogado]);
        if(!$chk->fetch()) { 
            $tb_alvo = 'usuario'; 
        }
    }

    // Todos podem atualizar seus próprios dados
    $n_nome = trim($_POST['nome_perfil'] ?? '');
    $n_sobr = trim($_POST['sobrenome_perfil'] ?? '');
    $n_mail = trim($_POST['email_perfil'] ?? '');
    $n_cel  = trim($_POST['celular_perfil'] ?? '');
    $n_nasc = trim($_POST['data_nasc_perfil'] ?? '');

    // Formatação correta para o MySQL (TIMESTAMP)
    $n_nasc_sql = null;
    if (!empty($n_nasc)) {
        if (strpos($n_nasc, '/') !== false) {
            $dt = explode('/', $n_nasc);
            if (count($dt) == 3) {
                $n_nasc_sql = $dt[2] . '-' . $dt[1] . '-' . $dt[0] . ' 00:00:00';
            }
        } else {
            $n_nasc_sql = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $n_nasc)));
        }
    }

    if ($tb_alvo == 'admin') {
        $upd = "UPDATE admin SET nome=?, sobrenome=?, email=?, celular=? WHERE usuario=?";
        try { $connUser->prepare($upd)->execute([$n_nome, $n_sobr, $n_mail, $n_cel, $usuarioLogado]); } catch(Exception $e) {}
    } elseif($tb_alvo == 'rev') {
        if (!empty($n_nasc_sql)) {
            $upd = "UPDATE rev SET nome=?, sobrenome=?, email=?, celular=?, data_nascimento=? WHERE usuario=?";
            try { $connUser->prepare($upd)->execute([$n_nome, $n_sobr, $n_mail, $n_cel, $n_nasc_sql, $usuarioLogado]); } catch(Exception $e) {}
        } else {
            $upd = "UPDATE rev SET nome=?, sobrenome=?, email=?, celular=? WHERE usuario=?";
            try { $connUser->prepare($upd)->execute([$n_nome, $n_sobr, $n_mail, $n_cel, $usuarioLogado]); } catch(Exception $e) {}
        }
    } else {
        if (!empty($n_nasc_sql)) {
            $upd = "UPDATE usuario SET nome=?, sobrenome=?, email=?, celular=?, data_nascimento=? WHERE usuario=?";
            try { 
                $connUser->prepare($upd)->execute([$n_nome, $n_sobr, $n_mail, $n_cel, $n_nasc_sql, $usuarioLogado]); 
            } catch(Exception $e) {
                // Fallback
                $upd_fallback = "UPDATE usuario SET nome=?, email=?, whatsapp=? WHERE usuario=?";
                try { $connUser->prepare($upd_fallback)->execute([$n_nome, $n_mail, $n_cel, $usuarioLogado]); } catch(Exception $ex) {}
            }
        } else {
            $upd = "UPDATE usuario SET nome=?, sobrenome=?, email=?, celular=? WHERE usuario=?";
            try { 
                $connUser->prepare($upd)->execute([$n_nome, $n_sobr, $n_mail, $n_cel, $usuarioLogado]); 
            } catch(Exception $e) {
                $upd_fallback = "UPDATE usuario SET nome=?, email=?, whatsapp=? WHERE usuario=?";
                try { $connUser->prepare($upd_fallback)->execute([$n_nome, $n_mail, $n_cel, $usuarioLogado]); } catch(Exception $ex) {}
            }
        }
    }

    // Alterar a senha, se preenchida
    if (!empty($senha_nova)) {
        try { $connUser->prepare("UPDATE $tb_alvo SET senha=? WHERE usuario=?")->execute([$senha_nova, $usuarioLogado]); } catch(Exception $e) {}
    }
    
    echo "<script>alert('Perfil atualizado com sucesso!'); location.href='index.php';</script>";
    exit;
}

// --- LÓGICA DO BADGE DO TOPO (ESTILO RETANGULAR DA IMAGEM) ---
$vencimentoFormatado = "";
if (!$isAdmin) {
    $stmtCheck = $connUser->prepare("SELECT bloqueado, data_premio FROM rev WHERE usuario = ? LIMIT 1");
    $stmtCheck->execute([$usuarioLogado]);
    $me = $stmtCheck->fetch(PDO::FETCH_ASSOC);

    if ($me) {
        $isBloq = ($me['bloqueado'] == 'sim');
        $val_venc = $me['data_premio'];
        $parsed_venc = is_numeric($val_venc) ? (int)$val_venc : strtotime(str_replace('/', '-', $val_venc));
        $isVenc = ($parsed_venc > 0 && $parsed_venc < time());

        if (is_numeric($val_venc)) {
            $vencimentoFormatado = date('d/m/Y', (int)$val_venc);
        } else {
            $vencimentoFormatado = $parsed_venc ? date('d/m/Y', $parsed_venc) : $val_venc;
        }

        if ($isBloq || $isVenc) {
            $motivo = $isBloq ? "BLOQUEADO POR FALTA DE PAGAMENTO" : "PLANO VENCIDO";
            die("
                <!DOCTYPE html>
                <html lang='pt-br'>
                <head>
                    <meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'>
                    <title>Acesso Negado</title>
                    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
                    <style>body{background:#151521;color:#fff;display:flex;align-items:center;justify-content:center;height:100vh;text-align:center;font-family:sans-serif;}</style>
                </head>
                <body>
                    <div>
                        <h1 class='text-danger fw-bold' style='font-size: 4rem;'>⛔</h1>
                        <h2 class='fw-bold text-uppercase'>ACESSO SUSPENSO</h2>
                        <p class='lead text-white'>$motivo</p>
                        <a href='sair.php' class='btn btn-outline-light mt-4 px-5'>Sair do Painel</a>
                    </div>
                </body>
                </html>
            ");
        }
    }
}

// Design do botão Administrador/Vencimento baseado na imagem (Retangular)
$badgeTopo = $isAdmin 
    ? '<span style="background: #cd4c4d; color: #fff; padding: 6px 14px; border-radius: 4px; font-size: 0.75rem; font-weight: 400; letter-spacing: 0.5px; white-space: nowrap; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">Administrador</span>'
    : '<span style="background: #ff9f43; color: #fff; padding: 6px 14px; border-radius: 4px; font-size: 0.75rem; font-weight: 400; letter-spacing: 0.5px; white-space: nowrap; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">Venc: ' . $vencimentoFormatado . '</span>';

// --- BUSCAR DADOS DO USUÁRIO ---
$meuDono = 'Administrador';
try {
    $stmtMe = $connUser->prepare("SELECT CadUser FROM usuario WHERE usuario = ?");
    $stmtMe->execute([$usuarioLogado]);
    $resMe = $stmtMe->fetch(PDO::FETCH_ASSOC);
    if($resMe && !empty($resMe['CadUser'])) { $meuDono = $resMe['CadUser']; }
} catch (Exception $e) {}

// --- SALVAR PREFERÊNCIAS LINK DE TESTE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao_pref']) && $_POST['acao_pref'] === 'salvar_config_teste') {
    $email = $_POST['email_copia'];
    $ativo = isset($_POST['receber_copia']) ? 'sim' : 'nao';
    $connUser->exec("CREATE TABLE IF NOT EXISTS usuario_pref (id INT AUTO_INCREMENT PRIMARY KEY, usuario VARCHAR(50) UNIQUE, email_copia VARCHAR(100), receber_copia ENUM('sim','nao'))");
    $sql = "INSERT INTO usuario_pref (usuario, email_copia, receber_copia) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE email_copia = VALUES(email_copia), receber_copia = VALUES(receber_copia)";
    try {
        $connUser->prepare($sql)->execute([$usuarioLogado, $email, $ativo]);
        echo "<script>alert('Configurações salvas!'); location.href='index.php';</script>";
    } catch (Exception $e) { }
}

// --- CONFIGS VISUAIS ---
$nomePainel = "IPTV PANEL"; $corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
} catch (Exception $e) { }

// --- FUNÇÃO TODA REDE ---
if (!function_exists('obterTodaRede')) {
    function obterTodaRede($conn, $dono) {
        $rede = [$dono];
        $buscar = [$dono];
        while (!empty($buscar)) {
            $atual = array_shift($buscar);
            $st = $conn->prepare("SELECT usuario FROM rev WHERE CadUser = ?");
            $st->execute([$atual]);
            $subs = $st->fetchAll(PDO::FETCH_COLUMN);
            foreach ($subs as $sub) {
                if (!in_array($sub, $rede)) {
                    $rede[] = $sub;
                    $buscar[] = $sub;
                }
            }
        }
        return $rede;
    }
}

// --- ESTATÍSTICAS CORRIGIDAS ---
$ativos = 0; $esgotados = 0; $bloqueados = 0; $testes_ativos = 0;
$agora = time();

try {
    if ($isAdmin) {
        $stmt_u = $connUser->query("SELECT data_premio, bloqueado, conexao FROM usuario");
        $stmt_t = $connUser->query("SELECT data_premio, bloqueado FROM teste");
    } else {
        $minha_rede = obterTodaRede($connUser, $usuarioLogado);
        $placeholders = implode(',', array_fill(0, count($minha_rede), '?'));
        
        $stmt_u = $connUser->prepare("SELECT data_premio, bloqueado, conexao FROM usuario WHERE CadUser IN ($placeholders)");
        $stmt_u->execute($minha_rede);
        
        $stmt_t = $connUser->prepare("SELECT data_premio, bloqueado FROM teste WHERE CadUser IN ($placeholders)");
        $stmt_t->execute($minha_rede);
    }
    
    while ($u = $stmt_u->fetch(PDO::FETCH_ASSOC)) {
        $qtd_telas = (!empty($u['conexao']) && is_numeric($u['conexao'])) ? (int)$u['conexao'] : 1;
        $venc = is_numeric($u['data_premio']) ? (int)$u['data_premio'] : strtotime(str_replace('/', '-', $u['data_premio']));
        if ($u['bloqueado'] == 'sim') { $bloqueados += $qtd_telas; } elseif ($venc > 0 && $venc < time()) { $esgotados += $qtd_telas; } else { $ativos += $qtd_telas; }
    }
    while ($t = $stmt_t->fetch(PDO::FETCH_ASSOC)) {
        $venc_t = is_numeric($t['data_premio']) ? (int)$t['data_premio'] : strtotime(str_replace('/', '-', $t['data_premio']));
        if ($t['bloqueado'] != 'sim' && $venc_t > $agora) { $testes_ativos++; }
    }
} catch (Exception $e) { }

// IP Real Servidor
$ip_servidor_real = ""; $nome_servidor_real = "CSP";
try {
    $srv = $connGeral->query("SELECT nome, url FROM painel WHERE block != 'sim' LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($srv) {
        $ip_servidor_real = trim(str_replace(['http://', 'https://', '/'], '', $srv['url']));
        $nome_servidor_real = $srv['nome'];
    }
} catch (Exception $e) { }

// Operadoras e Máscaras
$lista_operadoras = [];
try {
    if ($isAdmin) {
        $lista_operadoras = $connGeral->query("SELECT id, nome, url, porta FROM perfil WHERE bloqueado IS NULL OR bloqueado != 'sim'")->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $st_rev = $connUser->prepare("SELECT perfil FROM rev WHERE usuario = ?");
        $st_rev->execute([$usuarioLogado]);
        $perfis_liberados = $st_rev->fetchColumn();
        if (!empty($perfis_liberados)) {
            $nomes_perfis = explode(',', $perfis_liberados);
            $in_query = str_repeat('?,', count($nomes_perfis) - 1) . '?';
            $st_p = $connGeral->prepare("SELECT id, nome, url, porta FROM perfil WHERE nome IN ($in_query) AND (bloqueado IS NULL OR bloqueado != 'sim')");
            $st_p->execute($nomes_perfis);
            $lista_operadoras = $st_p->fetchAll(PDO::FETCH_ASSOC);
        }
    }

    foreach ($lista_operadoras as $key => $op) {
        $lista_operadoras[$key]['porta_real'] = $op['porta'];
        $stmtMasc = $connGeral->prepare("SELECT nome, url, porta FROM mascaraurl WHERE perfil = ? AND CadUser = ? AND bloqueado != 'sim' LIMIT 1");
        $stmtMasc->execute([$op['id'], $usuarioLogado]);
        $mascara = $stmtMasc->fetch(PDO::FETCH_ASSOC);
        if ($mascara) {
            $lista_operadoras[$key]['nome'] = (!empty($mascara['nome'])) ? $mascara['nome'] : $op['nome'];
            $lista_operadoras[$key]['url'] = (!empty($mascara['url'])) ? $mascara['url'] : $op['url'];
            $lista_operadoras[$key]['porta'] = (!empty($mascara['porta'])) ? $mascara['porta'] : $op['porta'];
        }
    }
} catch (Exception $e) { }

$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$urlTeste = $protocol . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/cadtest.php?r=" . base64_encode($usuarioLogado);
$pref_email = ""; $pref_ativo = "nao";
try {
    $stmtPref = $connUser->prepare("SELECT email_copia, receber_copia FROM usuario_pref WHERE usuario = ?");
    $stmtPref->execute([$usuarioLogado]);
    $resPref = $stmtPref->fetch(PDO::FETCH_ASSOC);
    if($resPref) { $pref_email = $resPref['email_copia']; $pref_ativo = $resPref['receber_copia']; }
} catch (Exception $e) { }

$total_msg_nao_lidas = 0;
try {
    $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
    $stmtMsg->execute([$usuarioLogado]);
    $total_msg_nao_lidas = $stmtMsg->fetchColumn();
} catch (Exception $e) { } 

function checkStatusReal($ip, $porta) {
    if (empty($ip) || empty($porta)) return false;
    $conexao = @fsockopen($ip, $porta, $errno, $errstr, 0.2); 
    if ($conexao) { fclose($conexao); return true; }
    return false;
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard | <?= htmlspecialchars($nomePainel) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <?php include 'tema_global.php'; ?>

    <style>
        /* =========================================================
           VARIÁVEIS DE CORES E TEMA (CLARO/ESCURO)
           ========================================================= */
        :root { 
            --primary: <?= $corPrimaria ?>; 
            --bg-body: #151521; 
            --bg-card: #1e1e2d; 
            --text-color: #d0d2d6; 
            --border-color: #2b2b40; 
            
            /* Overlays Escuros: Misturam preto sobre a Cor Primária */
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85); 
        }
        
        body.light-mode { 
            --bg-body: #f4f5f8; 
            --bg-card: #ffffff; 
            --text-color: #5e5873; 
            --border-color: #ebe9f1; 
            
            /* Overlays Claros: Mantêm a cor vibrante no tema claro */
            --overlay-desk: rgba(255, 255, 255, 0.1); 
            --overlay-mob: rgba(255, 255, 255, 0); /* Totalmente transparente para mostrar a cor pura */
        }
        
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-track { background: var(--bg-body); }
        ::-webkit-scrollbar-thumb { background: #444; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: var(--primary); }

        /* SIDEBAR DESKTOP & MOBILE */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        .main-content { margin-left: 260px; padding: 0; transition: 0.3s; min-height: 100vh; }
        .pointer { cursor: pointer !important; }
        
        /* =========================================
           HEADER (DESKTOP)
           ========================================= */
        .top-header { 
            /* Aplica o degradê com overlay escuro por cima da cor primária personalizada */
            background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); 
            padding: 15px 30px; 
            display: flex; 
            align-items: center; 
            justify-content: space-between; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.3); 
            margin-bottom: 30px; 
            border-bottom: 1px solid rgba(255,255,255,0.1); 
        }
        
        .header-row-title { display: flex; align-items: center; flex-grow: 1; position: relative; }
        .header-title { font-size: 1.5rem; font-weight: 800; color: #fff; letter-spacing: 1px; text-transform: uppercase; margin: 0; }
        .header-icons { display: flex; align-items: center; gap: 10px; }
        .icons-group { display: flex; align-items: center; gap: 8px; }
        
        .btn-icon { color: #fff; background: rgba(255,255,255,0.15); border: none; width: 42px; height: 42px; min-width: 42px; min-height: 42px; flex-shrink: 0; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: 0.2s; position: relative; cursor: pointer; text-decoration: none; }
        .btn-icon:hover { background: rgba(255,255,255,0.3); transform: translateY(-2px); color: #fff; }
        .badge-notif { position: absolute; top: 0; right: 0; width: 12px; height: 12px; background: #ea5455; border-radius: 50%; border: 2px solid var(--bg-card); }
        .mobile-toggle { display: none; color: #fff; font-size: 1.8rem; background: none; border: none; cursor: pointer; padding: 0 10px; }
        
        .content-wrapper { padding: 0 30px 30px 30px; position: relative; z-index: 10; }
        
        /* CARDS ESTATÍSTICAS */
        .stat-card-animated { background: var(--bg-card); border-radius: 12px; padding: 35px 20px; min-height: 250px; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; border: 1px solid var(--border-color); margin-bottom: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); transition: 0.3s; }
        .stat-card-animated:hover { transform: translateY(-5px); box-shadow: 0 8px 15px rgba(0,0,0,0.2); }
        .anim-icon-container { height: 100px; display: flex; align-items: center; justify-content: center; margin-bottom: 15px; }
        .anim-icon-container img { max-width: 100px; max-height: 100px; object-fit: contain; } 
        .stat-card-animated h2 { margin: 0; font-weight: 800; font-size: 2.8rem; color: #fff; line-height: 1.2; }
        .stat-card-animated p { color: #a6a6b7; font-weight: 600; font-size: 0.9rem; letter-spacing: 1px; margin: 0; text-transform: uppercase; }

        .section-card { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); margin-bottom: 25px; overflow: hidden; width: 100%; }
        .section-header { padding: 15px 20px; border-bottom: 1px solid var(--border-color); font-weight: 600; font-size: 1.1rem; color: #fff; display: flex; justify-content: space-between; align-items: center; }
        .section-body { padding: 20px; }
        .url-box { background: #2b2b40; border: 1px solid #444; color: #a6a6b7; padding: 12px; border-radius: 6px; font-family: monospace; font-size: 0.9rem; word-break: break-all; margin-bottom: 15px; }
        .btn-custom-light { background: #fff; color: #5e5873; border: 1px solid #d8d6de; font-weight: 600; padding: 8px 16px; border-radius: 6px; transition: 0.2s; }
        .btn-custom-info { background: #00cfe8; color: #fff; border: none; font-weight: 600; padding: 8px 16px; border-radius: 6px; float: right; cursor: pointer; text-decoration: none; }
        .btn-custom-purple { background: var(--primary); color: #fff; border: none; font-weight: 600; padding: 10px 20px; border-radius: 6px; width: 100%; margin-top: 10px; }
        
        .table-responsive { overflow-x: auto; -webkit-overflow-scrolling: touch; width: 100%; }
        .table-custom { width: 100%; border-collapse: collapse; min-width: 500px; }
        .table-custom th { text-align: left; padding: 12px 15px; color: #b9b9c3; font-size: 0.8rem; text-transform: uppercase; font-weight: 600; border-bottom: 1px solid var(--border-color); background: #252535; white-space: nowrap; }
        .table-custom td { padding: 12px 15px; border-bottom: 1px solid var(--border-color); font-size: 0.9rem; color: #fff; vertical-align: middle; white-space: nowrap; }
        
        .status-badge { padding: 4px 10px; border-radius: 4px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; }
        .status-online { background: rgba(40, 199, 111, 0.2); color: #28c76f; border: 1px solid rgba(40, 199, 111, 0.2); }
        .status-offline { background: rgba(234, 84, 85, 0.2); color: #ea5455; border: 1px solid rgba(234, 84, 85, 0.2); }
        
        .overlay { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }

        /* MONITORAMENTO VPS */
        .vps-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-top: 15px; }
        .vps-card { background: #222234; border-radius: 12px; padding: 20px 10px; text-align: center; border: 1px solid #333; position: relative; overflow: hidden; box-shadow: inset 0 0 20px rgba(0,0,0,0.2); }
        .vps-title { font-size: 0.8rem; text-transform: uppercase; color: #a6a6b7; font-weight: 700; letter-spacing: 1px; margin-bottom: 15px; }
        
        .flex-wrapper { display: flex; justify-content: center; align-items: center; width: 100%; padding: 15px 0; }
        .single-chart { width: 130px; height: 130px; position: relative; margin: 0 auto; } 
        .circular-chart { display: block; width: 100%; height: 100%; filter: drop-shadow(0px 0px 8px rgba(0,0,0,0.5)); }
        
        .circle-bg { fill: none; stroke: #2b2b40; stroke-width: 2.5; }
        .circle { fill: none; stroke-width: 2.5; stroke-linecap: round; transition: stroke-dasharray 1.5s ease-out; }
        .percentage { fill: #fff; font-family: sans-serif; font-size: 0.45em; text-anchor: middle; font-weight: bold; }
        .info-text { fill: #a6a6b7; font-family: sans-serif; font-size: 0.18em; text-anchor: middle; }
        
        .cpu-chart .circle { stroke: #00cfe8; filter: drop-shadow(0 0 5px #00cfe8); }
        .ram-chart .circle { stroke: #7367f0; filter: drop-shadow(0 0 5px #7367f0); }
        .disk-chart .circle { stroke: #ff9f43; filter: drop-shadow(0 0 5px #ff9f43); }
        
        .net-icon { font-size: 2.5rem; color: #28c76f; text-shadow: 0 0 15px #28c76f; margin-bottom: 10px; animation: pulse 2s infinite; }
        .net-stats { display: flex; justify-content: space-between; margin-top: 15px; border-top: 1px solid #333; padding-top: 15px; }
        .net-box { width: 48%; background: rgba(0,0,0,0.2); border-radius: 8px; padding: 10px 5px; }
        .net-val { font-size: 1.1rem; font-weight: bold; color: #fff; white-space: nowrap; }
        .net-label { font-size: 0.65rem; color: #a6a6b7; text-transform: uppercase; }
        .tx-color { color: #00cfe8; }
        .rx-color { color: #28c76f; }
        
        @keyframes pulse { 0% { transform: scale(1); filter: brightness(1); } 50% { transform: scale(1.1); filter: brightness(1.5); text-shadow: 0 0 25px #28c76f; } 100% { transform: scale(1); filter: brightness(1); } }
        .live-dot { height: 8px; width: 8px; background-color: #28c76f; border-radius: 50%; display: inline-block; margin-right: 5px; box-shadow: 0 0 8px #28c76f; animation: blink 1s infinite; }
        @keyframes blink { 0% { opacity: 1; } 50% { opacity: 0.4; } 100% { opacity: 1; } }

        /* =========================================
           HEADER - LAYOUT MOBILE (IGUAL A IMAGEM)
           ========================================= */
        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); box-shadow: none; z-index: 1050; } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; width: 100%; }
            .content-wrapper { padding: 0 15px 30px 15px; }
            .stat-card-animated { min-height: 220px; padding: 25px 15px; }
            
            /* O Top Header no mobile escurece a cor usando overlay profundo */
            .top-header { 
                flex-direction: column; 
                padding: 15px 20px; 
                align-items: stretch; 
                background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); 
                border-bottom: none; 
            }
            
            /* Linha 1: Título e Menu Hambúrguer */
            .header-row-title { width: 100%; justify-content: center; margin-bottom: 15px; }
            .header-title { text-align: center; margin: 0 auto; font-family: 'Times New Roman', Times, serif; font-size: 1.8rem; font-weight: 400; letter-spacing: 2px; } 
            .mobile-toggle { display: block !important; position: absolute; right: 0; top: 50%; transform: translateY(-50%); padding: 0; color: #a6a6b7; font-size: 1.5rem; } 
            
            /* Linha 2: Badge e Ícones */
            .header-icons { width: 100%; justify-content: space-between; flex-direction: row; margin-top: 0; }
            .badge-mobile { margin-right: auto !important; }
            .icons-group { justify-content: flex-end; gap: 8px; flex-wrap: nowrap; }
            
            /* Ícones transparentes e menores igual a imagem */
            .btn-icon { width: 30px; height: 30px; min-width: 30px; min-height: 30px; font-size: 0.95rem; background: transparent; color: #a6a6b7; }
            .btn-icon[href="sair.php"] { color: #ea5455 !important; }
            
            /* Ajuste dos gráficos Mobile para não espremer */
            .vps-grid { grid-template-columns: 1fr 1fr; gap: 15px; } 
        }
        
        @media (max-width: 500px) {
            .vps-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

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

<main class="main-content">
    <div class="top-header">
        
        <!-- ROW 1 (MOBILE): Título Centralizado e Menu à direita -->
        <div class="header-row-title">
            <div class="header-title"><?= htmlspecialchars($nomePainel) ?></div>
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="d-none d-lg-block ms-4"><?= $badgeTopo ?></div>
        </div>
        
        <!-- ROW 2 (MOBILE): Badge à esquerda e Ícones à direita -->
        <div class="header-icons">
            <div class="d-lg-none badge-mobile"><?= $badgeTopo ?></div>
            
            <div class="icons-group">
                <button class="btn-icon" onclick="toggleTheme()" title="Alternar Tema"><i class="fas fa-sun" id="themeIcon"></i></button>
                <a href="https://api.whatsapp.com/send?phone=47988870797" target="_blank" class="btn-icon"><i class="fab fa-whatsapp"></i></a>
                <button class="btn-icon" data-bs-toggle="modal" data-bs-target="#modalPerfil"><i class="fas fa-user"></i></button>
                <a href="suporte.php" class="btn-icon"><i class="fas fa-envelope"></i><?php if(isset($total_msg_nao_lidas) && $total_msg_nao_lidas > 0): ?><span class="badge-notif"></span><?php endif; ?></a>
                <a href="sair.php" class="btn-icon"><i class="fas fa-power-off"></i></a>
            </div>
        </div>
        
    </div>

    <div class="content-wrapper">
        <div class="row">
            <div class="col-12 col-md-6 col-xl-3 pointer" onclick="location.href='clientes.php';"><div class="stat-card-animated"><div class="anim-icon-container"><img src="img/img/ativo.gif"></div><h2><?= $ativos ?></h2><p>Ativos</p></div></div>
            <div class="col-12 col-md-6 col-xl-3 pointer" onclick="location.href='clientes.php?status=esgotados';"><div class="stat-card-animated"><div class="anim-icon-container"><img src="img/img/esgotados.gif"></div><h2><?= $esgotados ?></h2><p>Esgotados</p></div></div>
            <div class="col-12 col-md-6 col-xl-3 pointer" onclick="location.href='clientes.php?status=bloqueados';"><div class="stat-card-animated"><div class="anim-icon-container"><img src="img/img/bloqueios.gif"></div><h2><?= $bloqueados ?></h2><p>Bloqueadas</p></div></div>
            <div class="col-12 col-md-6 col-xl-3 pointer" onclick="location.href='testes.php';"><div class="stat-card-animated"><div class="anim-icon-container"><img src="img/img/testes.gif"></div><h2><?= $testes_ativos ?></h2><p>Testes Ativos</p></div></div>
        </div>

        <div class="section-card"><div class="section-header">Url de Teste</div><div class="section-body"><div class="url-box" id="urlTesteTexto"><?= $urlTeste ?></div><div class="d-flex justify-content-between"><button class="btn-custom-light pointer" onclick="copiarUrl()"><i class="fas fa-link me-2"></i>Copiar Link</button><button class="btn-custom-info pointer" data-bs-toggle="modal" data-bs-target="#modalConfigTeste">Configurações</button></div></div></div>

        <div class="section-card"><div class="section-header">Status do Cliente</div><div class="section-body"><p class="text-white-50 mb-3 small">Clique em verificar para atualizar o estado da sua conexão.</p><div class="text-end"><button class="btn-custom-purple pointer" onclick="location.reload()">Verificar Status</button></div></div></div>

        <div class="section-card">
            <div class="section-header">Informações da Operadora</div>
            <div class="table-responsive">
                <table class="table-custom">
                    <thead><tr><th>OPERADORA</th><th>URL</th><th>PORTA</th></tr></thead>
                    <tbody>
                        <?php if(count($lista_operadoras) > 0): foreach($lista_operadoras as $s): ?><tr><td><?= htmlspecialchars($s['nome']) ?></td><td><?= htmlspecialchars($s['url']) ?></td><td><?= htmlspecialchars($s['porta']) ?></td></tr><?php endforeach; else: ?><tr><td colspan="3" class="text-center text-muted py-3">Nenhuma operadora disponível</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="section-card">
            <div class="section-header">Status do Servidor (Tempo Real)</div>
            <div class="table-responsive">
                <table class="table-custom">
                    <thead><tr><th>SERVIDOR</th><th>OPERADORA</th><th class="text-center">STATUS</th></tr></thead>
                    <tbody>
                        <?php if(count($lista_operadoras) > 0 && !empty($ip_servidor_real)): foreach($lista_operadoras as $s): $isOnline = checkStatusReal($ip_servidor_real, $s['porta_real']); ?>
                        <tr><td><?= htmlspecialchars($nome_servidor_real) ?></td><td><?= htmlspecialchars($s['nome']) ?></td><td class="text-center"><?php if($isOnline): ?><span class="status-badge status-online">Online</span><?php else: ?><span class="status-badge status-offline">Offline</span><?php endif; ?></td></tr>
                        <?php endforeach; else: ?><tr><td colspan="3" class="text-center text-muted py-3">Configure o Servidor no Menu Admin.</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if ($isAdmin): ?>
        <div class="section-card mt-4" id="vps-monitor">
            <div class="section-header">
                <span><i class="fas fa-server text-info me-2"></i> Performance da Máquina</span>
                <span><span class="live-dot"></span><span style="font-size: 0.8rem; color: #28c76f; font-weight: bold; text-transform: uppercase;">Monitoramento Ativo</span></span>
            </div>
            <div class="section-body">
                <div class="vps-grid">
                    
                    <div class="vps-card">
                        <div class="vps-title"><i class="fas fa-microchip me-2"></i>Uso de CPU</div>
                        <div class="flex-wrapper">
                            <div class="single-chart cpu-chart">
                                <svg viewBox="0 0 36 36" class="circular-chart">
                                    <path class="circle-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
                                    <path class="circle" stroke-dasharray="0, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" id="svg-cpu"/>
                                    <text x="18" y="20.35" class="percentage" id="text-cpu">0%</text>
                                    <text x="18" y="24" class="info-text">Processamento</text>
                                </svg>
                            </div>
                        </div>
                    </div>

                    <div class="vps-card">
                        <div class="vps-title"><i class="fas fa-memory me-2"></i>Uso de RAM</div>
                        <div class="flex-wrapper">
                            <div class="single-chart ram-chart">
                                <svg viewBox="0 0 36 36" class="circular-chart">
                                    <path class="circle-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
                                    <path class="circle" stroke-dasharray="0, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" id="svg-ram"/>
                                    <text x="18" y="20.35" class="percentage" id="text-ram">0%</text>
                                    <text x="18" y="24" class="info-text">Memória Física</text>
                                </svg>
                            </div>
                        </div>
                    </div>

                    <div class="vps-card">
                        <div class="vps-title"><i class="fas fa-hdd me-2"></i>Armazenamento</div>
                        <div class="flex-wrapper">
                            <div class="single-chart disk-chart">
                                <svg viewBox="0 0 36 36" class="circular-chart">
                                    <path class="circle-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
                                    <path class="circle" stroke-dasharray="0, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" id="svg-disk"/>
                                    <text x="18" y="20.35" class="percentage" id="text-disk">0%</text>
                                    <text x="18" y="24" class="info-text">Disco (SSD)</text>
                                </svg>
                            </div>
                        </div>
                    </div>

                    <div class="vps-card">
                        <div class="vps-title"><i class="fas fa-network-wired me-2"></i>Tráfego de Rede</div>
                        <div class="flex-wrapper" style="flex-direction: column;">
                            <i class="fas fa-wifi net-icon"></i>
                            <span style="color: #a6a6b7; font-size: 0.8rem; letter-spacing: 1px;">Conexão Estável</span>
                        </div>
                        <div class="net-stats">
                            <div class="net-box">
                                <div class="net-label">Enviados</div>
                                <div class="net-val tx-color" id="text-tx">0.00 GB</div>
                            </div>
                            <div class="net-box">
                                <div class="net-label">Recebidos</div>
                                <div class="net-val rx-color" id="text-rx">0.00 GB</div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        <?php endif; ?>

    </div>
</main>

<div class="modal fade" id="modalPerfil" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <form method="POST" class="modal-content" style="background: var(--bg-body); border: 1px solid var(--border-color);">
            <input type="hidden" name="acao_perfil" value="salvar">
            <div class="modal-header border-bottom-0 pb-0">
                <h4 class="modal-title w-100 fw-bold" style="color: var(--text-color); font-size: 1.5rem;">
                    <i class="fas fa-cog me-1" style="color: var(--primary);"></i> Editar Perfil
                </h4>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4 pt-2">
                <div class="row g-4">
                    <div class="col-md-5">
                        <div class="card border-0 shadow-sm" style="border-radius: 10px; background: var(--bg-card);">
                            <div class="card-body text-center p-4">
                                <h5 class="fw-bold mb-1" style="color: var(--text-color);"><i class="fas fa-user me-2"></i><?= htmlspecialchars($p_first_name) ?> <?= htmlspecialchars($p_last_name) ?></h5>
                                <p class="small mb-4" style="color: #a6a6b7;"><?= $isAdmin ? 'Administrador' : 'Revendedor' ?></p>

                                <div style="width: 120px; height: 120px; background: var(--bg-body); border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px auto; font-size: 4rem; color: var(--primary); border: 1px solid var(--border-color);">
                                    <i class="fas fa-user"></i>
                                </div>
                                
                                <button type="button" class="btn btn-outline-info btn-sm rounded-pill px-4 mb-4 fw-bold" style="border-color: #4fd1c5; color: #4fd1c5;">Alterar Foto</button>

                                <div class="input-group input-group-sm mb-2">
                                    <span class="input-group-text bg-transparent border-end-0" style="border-color: var(--border-color); color: var(--text-color);">Usuário</span>
                                    <input type="text" class="form-control border-start-0 text-end" style="border-color: var(--border-color); background: rgba(0,0,0,0.2); color: var(--text-color);" value="<?= htmlspecialchars($usuarioLogado) ?>" disabled>
                                </div>
                                <div class="input-group input-group-sm mb-2">
                                    <span class="input-group-text bg-transparent border-end-0" style="border-color: var(--border-color); color: var(--text-color);">E-mail</span>
                                    <input type="text" name="email_perfil" class="form-control border-start-0 text-end" style="border-color: var(--border-color); background: var(--bg-body); color: var(--text-color);" value="<?= htmlspecialchars($p_email) ?>">
                                </div>
                                <div class="input-group input-group-sm mb-3">
                                    <span class="input-group-text bg-transparent border-end-0" style="border-color: var(--border-color); color: var(--text-color);">Senha</span>
                                    <input type="text" name="senha_perfil" class="form-control border-start-0 text-end" style="border-color: var(--border-color); background: var(--bg-body); color: var(--text-color);" placeholder="Nova senha...">
                                </div>

                                <div class="text-start mb-4">
                                    <button type="submit" class="btn btn-outline-info btn-sm rounded-pill px-4 fw-bold" style="border-color: #4fd1c5; color: #4fd1c5;">Salvar</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-7">
                        <div class="card border-0 shadow-sm mb-4" style="border-radius: 10px; background: var(--bg-card);">
                            <div class="card-body p-4">
                                <h6 class="fw-bold mb-1" style="color: var(--text-color);"><i class="fas fa-pen me-2"></i>Perfil</h6>
                                <p class="small border-bottom pb-3 mb-3" style="color: #a6a6b7; border-color: var(--border-color) !important;">Edite abaixo suas informações.<br>Mantenha seus dados sempre atualizados.</p>
                                
                                <div class="row mb-2 align-items-center">
                                    <div class="col-4 small fw-bold" style="color: var(--text-color);">Nome</div>
                                    <div class="col-8"><input type="text" name="nome_perfil" class="form-control form-control-sm" style="background: var(--bg-body); border-color: var(--border-color); color: var(--text-color);" value="<?= htmlspecialchars($p_first_name) ?>"></div>
                                </div>
                                <div class="row mb-2 align-items-center">
                                    <div class="col-4 small fw-bold" style="color: var(--text-color);">Sobrenome</div>
                                    <div class="col-8"><input type="text" name="sobrenome_perfil" class="form-control form-control-sm" style="background: var(--bg-body); border-color: var(--border-color); color: var(--text-color);" value="<?= htmlspecialchars($p_last_name) ?>"></div>
                                </div>
                                <div class="row mb-2 align-items-center">
                                    <div class="col-4 small fw-bold" style="color: var(--text-color);">Celular</div>
                                    <div class="col-8"><input type="text" name="celular_perfil" class="form-control form-control-sm" style="background: var(--bg-body); border-color: var(--border-color); color: var(--text-color);" value="<?= htmlspecialchars($p_celular) ?>"></div>
                                </div>
                                <div class="row mb-3 align-items-center">
                                    <div class="col-4 small fw-bold" style="color: var(--text-color);">Nascimento</div>
                                    <div class="col-8">
                                        <div class="input-group input-group-sm">
                                            <input type="text" name="data_nasc_perfil" class="form-control border-end-0" style="background: var(--bg-body); border-color: var(--border-color); color: var(--text-color);" value="<?= htmlspecialchars($p_data_nasc) ?>">
                                            <span class="input-group-text text-white border-0" style="background-color: var(--primary);"><i class="fas fa-calendar-alt"></i></span>
                                        </div>
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-outline-info btn-sm rounded-pill px-4 fw-bold" style="border-color: #4fd1c5; color: #4fd1c5;">Salvar</button>
                            </div>
                        </div>

                        <div class="card border-0 shadow-sm" style="border-radius: 10px; background: var(--bg-card);">
                            <div class="card-body p-4">
                                <h6 class="fw-bold mb-1" style="color: var(--text-color);"><i class="fas fa-info-circle me-2 text-muted"></i>Informações</h6>
                                <p class="small border-bottom pb-3 mb-3" style="color: #a6a6b7; border-color: var(--border-color) !important;">Uma rápida informação sobre você</p>
                                
                                <ul class="list-group list-group-flush small bg-transparent">
                                    <li class="list-group-item bg-transparent px-0 d-flex justify-content-between align-items-center" style="border-color: dashed var(--border-color); color: var(--text-color);">
                                        <span class="fw-bold w-25">Acesso em</span>
                                        <span class="text-end w-75" style="color: #a6a6b7; word-break: break-all;"><?= date('H:i d.m.Y') ?></span>
                                    </li>
                                    <li class="list-group-item bg-transparent px-0 d-flex justify-content-between align-items-center" style="border-color: dashed var(--border-color); color: var(--text-color);">
                                        <span class="fw-bold w-25">Último IP</span>
                                        <span class="text-end w-75" style="color: #a6a6b7; word-break: break-all;"><?= $_SERVER['REMOTE_ADDR'] ?></span>
                                    </li>
                                    <li class="list-group-item bg-transparent px-0 d-flex justify-content-between align-items-center" style="border-color: dashed var(--border-color); color: var(--text-color);">
                                        <span class="fw-bold w-25">Criado em</span>
                                        <span class="text-end w-75" style="color: #a6a6b7; word-break: break-all;"><?= !empty($p_criado) ? date('H:i d.m.Y', strtotime($p_criado)) : '---' ?></span>
                                    </li>
                                    <li class="list-group-item bg-transparent px-0 d-flex justify-content-between align-items-center" style="border-color: dashed var(--border-color); color: var(--text-color);">
                                        <span class="fw-bold w-25">Grupo</span>
                                        <span class="text-end w-75" style="color: #a6a6b7; word-break: break-all;"><?= $isAdmin ? 'Administrador' : 'Revendedor' ?></span>
                                    </li>
                                    <li class="list-group-item bg-transparent px-0 d-flex justify-content-between align-items-center border-bottom-0" style="color: var(--text-color);">
                                        <span class="fw-bold w-25">Nascimento</span>
                                        <span class="text-end w-75" style="color: #a6a6b7; word-break: break-all;"><?= !empty($p_data_nasc) ? $p_data_nasc : '---' ?></span>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalConfigTeste" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark border-secondary text-white"><form method="POST"><input type="hidden" name="acao_pref" value="salvar_config_teste"><div class="modal-header border-secondary"><h5>Configurar Cópia</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><div class="mb-3"><label>E-mail para Cópia</label><input type="email" name="email_copia" class="form-control bg-dark text-white border-secondary" value="<?= htmlspecialchars($pref_email) ?>"></div><div class="form-check form-switch"><input class="form-check-input" type="checkbox" name="receber_copia" id="switchReceber" <?= $pref_ativo == 'sim' ? 'checked' : '' ?>><label class="form-check-label">Ativar envio</label></div></div><div class="modal-footer border-secondary"><button type="submit" class="btn btn-primary w-100 pointer">Salvar</button></div></form></div></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { 
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        sidebar.classList.toggle('show'); 
        overlay.classList.toggle('show'); 
    }
    
    function copiarUrl() { 
        navigator.clipboard.writeText(document.getElementById('urlTesteTexto').innerText).then(() => alert("URL copiada!")); 
    }

    // --- SISTEMA DE TEMA CLARO/ESCURO ---
    function toggleTheme() {
        const body = document.body;
        const icon = document.getElementById('themeIcon');
        
        body.classList.toggle('light-mode');
        
        if (body.classList.contains('light-mode')) {
            localStorage.setItem('theme', 'light');
            icon.classList.remove('fa-sun');
            icon.classList.add('fa-moon');
        } else {
            localStorage.setItem('theme', 'dark');
            icon.classList.remove('fa-moon');
            icon.classList.add('fa-sun');
        }
    }

    // --- SCRIPT PARA MONITORAMENTO EM TEMPO REAL ---
    <?php if ($isAdmin): ?>
    function animateChart(elSvg, elTxt, targetValue) {
        if(elSvg && elTxt) {
            // Garante que o valor seja tratado como número
            let val = parseInt(targetValue) || 0;
            // Atualiza o círculo (0 a 100)
            elSvg.style.strokeDasharray = val + ", 100";
            // Atualiza o texto central
            elTxt.textContent = val + "%";
        }
    }

    function carregarMonitor() {
        // Busca os dados do arquivo monitor_json.php que você testou e funcionou
        fetch('monitor_json.php?t=' + Date.now())
            .then(response => {
                if (!response.ok) throw new Error('Falha ao ler monitor_json.php');
                return response.json();
            })
            .then(data => {
                // Verifica se os dados existem antes de aplicar nos IDs
                if (data.cpu !== undefined) {
                    animateChart(document.getElementById('svg-cpu'), document.getElementById('text-cpu'), data.cpu);
                    animateChart(document.getElementById('svg-ram'), document.getElementById('text-ram'), data.ram);
                    animateChart(document.getElementById('svg-disk'), document.getElementById('text-disk'), data.disk);
                    
                    // Atualiza os textos de tráfego de rede
                    if(document.getElementById('text-tx')) document.getElementById('text-tx').textContent = data.tx;
                    if(document.getElementById('text-rx')) document.getElementById('text-rx').textContent = data.rx;
                }
            })
            .catch(err => {
                console.error("Monitor status:", err);
            });
    }

    // Executa assim que o painel abrir e repete a cada 5 segundos
    document.addEventListener("DOMContentLoaded", function() {
        carregarMonitor();
        setInterval(carregarMonitor, 5000);
    });
    <?php endif; ?>
</script>
</body>
</html>
