<?php
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'];

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');
        $isVenc = ((int)$me['data_premio'] > 0 && (int)$me['data_premio'] < time());
        if ($isBloq || $isVenc) {
            $motivo = $isBloq ? "BLOQUEADO PELO ADMINISTRADOR" : "PLANO VENCIDO";
            die("<!DOCTYPE html><html lang='pt-br'><head><meta charset='UTF-8'><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;}</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-muted'>$motivo</p><a href='sair.php' class='btn btn-outline-light mt-4 px-5'>Sair do Painel</a></div></body></html>");
        }
    }
}

// --- 2. CONFIGURAÇÕES 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) { }

// --- 3. DADOS CSP (PORTA 1991) ---
$senha_csp = ''; 
try {
    $conf_csp = $connGeral->query("SELECT senha_servidor FROM configuracao LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf_csp) { $senha_csp = trim($conf_csp['senha_servidor']); }
} catch (Exception $e) { }

$online_users = [];
$erro = "";

// --- 4. CONEXÃO COM A API DO CSP 0.9.0 ---
if (!empty($senha_csp)) {
    $url = "http://127.0.0.1:1991/xmlHandler?command=proxy-users";
    $ch = curl_init();
    $auth = base64_encode("sandisk:$senha_csp");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Basic $auth", "Connection: close"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $xml_bruto = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code == 200 && !empty($xml_bruto)) {
        libxml_use_internal_errors(true);
        $xml = @simplexml_load_string($xml_bruto);
        if ($xml) {
            // Lendo atributos conforme a Imagem 17 e a documentação
            foreach ($xml->xpath('//user') as $s) {
                $login = (string)$s['name'];
                if (!empty($login) && $login !== '*' && !in_array(strtolower($login), ['sandisk', 'admin', 'mapa', 'copo'])) {
                    $nome_real = $login;
                    try {
                        $stmtU = $connUser->prepare("SELECT nome FROM usuario WHERE usuario = ? UNION SELECT nome FROM teste WHERE usuario = ? LIMIT 1");
                        $stmtU->execute([$login, $login]);
                        $res_n = $stmtU->fetchColumn();
                        if ($res_n) $nome_real = $res_n;
                    } catch(Exception $e) {}

                    $online_users[] = [
                        'nome'   => $nome_real,
                        'login'  => $login,
                        'ip'     => (string)$s['ip'],        // Coluna 2
                        'canal'  => (string)$s['service'],   // Coluna 10
                        'tempo'  => (string)$s['connected']  // Coluna 3
                    ];
                }
            }
        }
    } else { $erro = "Aguardando sincronização com o servidor."; }
}
?>

<!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>Monitor Online | <?= 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">
    <style>
        :root { --primary: <?= $corPrimaria ?>; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #d0d2d6; --border-color: #2b2b40; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        /* Sidebar Estilo IPTV */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .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; transition: 0.3s; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        
        /* Tabela Ultra Dark e Compacta */
        .card-monitor { background: var(--bg-card) !important; border: 1px solid var(--border-color); border-radius: 15px; overflow: hidden; }
        .table-responsive-custom { overflow-x: auto; -webkit-overflow-scrolling: touch; }
        .table-online { width: 100%; white-space: nowrap; border-collapse: collapse; }
        .table-online th, .table-online td { padding: 8px 12px; font-size: 0.85rem; border-bottom: 1px solid var(--border-color); vertical-align: middle; }
        .table-online th { background: rgba(0,0,0,0.2); color: #888; text-transform: uppercase; font-weight: 700; font-size: 0.75rem; }
        
        /* Visibilidade do Nome - Branco Puro */
        .nome-destaque { color: #ffffff !important; font-weight: 700; text-shadow: 0 0 1px rgba(255,255,255,0.2); }
        .dot-online { width: 8px; height: 8px; background: #28c76f; border-radius: 50%; display: inline-block; margin-right: 5px; box-shadow: 0 0 5px #28c76f; }

        @media (max-width: 992px) {
            .sidebar { transform: translateX(-100%); }
            .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; }
            .mobile-toggle { display: block !important; }
        }
        .mobile-toggle { display: none; color: #fff; font-size: 1.5rem; background: none; border: none; margin-right: 15px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>

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

<nav class="sidebar" id="sidebar">
    <div class="text-center mb-4"><h4 class="fw-bold text-white"><?= htmlspecialchars($nomePainel) ?></h4></div>
    <div class="nav flex-column">
        <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">ADMINISTRATIVO</div>
            <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Perfis</a>
            <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores</a>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Admins</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configurações</a>
            <a href="gerenciar_ips.php" class="nav-link"><i class="fas fa-shield-halved"></i> Firewall IPs</a>
            <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backup</a>
        <?php endif; ?>

        <div class="nav-group-title">MENU</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</a>
        <a href="monitor.php" class="nav-link active"><i class="fas fa-wifi"></i> Monitor</a>
        <a href="config_mp_revenda.php" class="nav-link"><i class="fas fa-wallet"></i> Pagamento</a>
        <a href="gerenciar_planos.php" class="nav-link"><i class="fas fa-tags"></i> Planos</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
        <a href="gerador_robo.php" class="nav-link"><i class="fas fa-robot"></i> WhatsAuto</a>
        
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title">Monitoramento</div>
        </div>
        <div class="header-icons">
            <a href="sair.php" class="btn-icon" style="background: rgba(234,84,85,0.2); color: #ea5455; padding: 10px; border-radius: 50%; text-decoration: none;"><i class="fas fa-power-off"></i></a>
        </div>
    </div>

    <div class="container-fluid p-2 p-md-4">
        <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
            <h4 class="fw-bold m-0"><i class="fas fa-broadcast-tower text-primary me-2"></i> Canais Ativos</h4>
            <button onclick="location.reload()" class="btn btn-primary btn-sm px-4 shadow"><i class="fas fa-sync-alt me-1"></i> ATUALIZAR</button>
        </div>

        <?php if($erro): ?><div class="alert alert-danger border-0 shadow-sm"><?= $erro ?></div><?php endif; ?>

        <div class="card card-monitor">
            <div class="p-3 border-bottom border-secondary d-flex justify-content-between align-items-center">
                <span class="badge bg-success px-3 py-2 rounded-pill"><i class="fas fa-users me-2"></i> <?= count($online_users) ?> Online</span>
                <small class="text-muted d-md-none">Deslize para o lado <i class="fas fa-arrow-right"></i></small>
            </div>
            <div class="table-responsive-custom">
                <table class="table-online">
                    <thead>
                        <tr>
                            <th>NOME DO CLIENTE</th>
                            <th>USUÁRIO</th>
                            <th>IP RECEPTOR</th>
                            <th>CANAL ASSISTINDO</th>
                            <th class="text-end">TEMPO</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($online_users)): ?>
                            <tr><td colspan="5" class="text-center py-5 text-muted small">Nenhum receptor ativo no momento.</td></tr>
                        <?php else: ?>
                            <?php foreach($online_users as $u): ?>
                            <tr>
                                <td class="nome-destaque"><span class="dot-online"></span><?= htmlspecialchars($u['nome']) ?></td>
                                <td class="text-info"><?= htmlspecialchars($u['login']) ?></td>
                                <td class="font-monospace opacity-50"><?= htmlspecialchars($u['ip']) ?></td>
                                <td class="text-warning fw-bold"><?= htmlspecialchars($u['canal']) ?></td>
                                <td class="text-end text-success fw-bold"><?= htmlspecialchars($u['tempo']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
</script>
</body>
</html>