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

// Verifica Login
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header("Location: login.php"); exit;
}

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

// --- 1. BUSCAR DADOS DE CONEXÃO ---
$csp_dados = [];
try {
    $stmt = $connGeral->query("SELECT url, porta, usuario, senha, protocolo FROM painel LIMIT 1");
    $csp_dados = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) { }

$nomePainel = "IPTV PANEL"; 
try {
    $conf = $connGeral->query("SELECT NomePainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf && !empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
} catch (Exception $e) { }

// --- 2. RASTREADOR DE FRAMES ---
$clientes_online = [];
$total_online = 0;
$log_diagnostico = [];

if ($csp_dados) {
    $ip   = $csp_dados['url'];
    $port = $csp_dados['porta'];
    $user = $csp_dados['usuario'];
    $pass = $csp_dados['senha'];
    $prot = $csp_dados['protocolo'] ?: 'http';

    function requisicao($url, $u, $p) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_USERPWD, "$u:$p");
        curl_setopt($ch, CURLOPT_TIMEOUT, 8);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
        $res = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return ['body' => $res, 'code' => $code];
    }

    // 1. Conecta na Raiz
    $url_raiz = "{$prot}://{$ip}:{$port}/";
    $log_diagnostico[] = "1. Acessando raiz: $url_raiz";
    $req = requisicao($url_raiz, $user, $pass);

    if ($req['code'] == 200) {
        $html_raiz = $req['body'];
        
        // 2. Extrai TODOS os Frames
        $urls_para_checar = [];
        
        // Usa DOMDocument para achar frames com precisão
        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        @$dom->loadHTML($html_raiz);
        
        $frames = $dom->getElementsByTagName('frame');
        foreach ($frames as $frame) {
            $src = $frame->getAttribute('src');
            if (!empty($src)) {
                $urls_para_checar[] = $src;
            }
        }

        // Se não achou frames, adiciona 'status' manual como fallback
        if (empty($urls_para_checar)) {
            $log_diagnostico[] = "Nenhum frame detectado. Tentando URLs manuais.";
            $urls_para_checar[] = "status"; 
            $urls_para_checar[] = "status.html";
        }

        $log_diagnostico[] = "2. Frames encontrados: " . implode(", ", $urls_para_checar);

        // 3. Verifica cada Frame até achar a tabela
        $achou_tabela = false;

        foreach ($urls_para_checar as $url_relativa) {
            if ($achou_tabela) break;

            // Monta URL completa
            $url_frame = "{$prot}://{$ip}:{$port}/" . ltrim($url_relativa, '/');
            $log_diagnostico[] = ">> Checando: $url_frame";
            
            $reqFrame = requisicao($url_frame, $user, $pass);
            
            if ($reqFrame['code'] == 200) {
                $html = $reqFrame['body'];
                
                // Verifica se tem cara de tabela de status (Headers comuns)
                if (stripos($html, 'User') !== false && stripos($html, 'Connected') !== false) {
                    $log_diagnostico[] = "✅ Tabela encontrada neste frame!";
                    $achou_tabela = true;

                    // Parse da Tabela
                    $domT = new DOMDocument();
                    libxml_use_internal_errors(true);
                    @$domT->loadHTML($html);
                    $xpath = new DOMXPath($domT);
                    $linhas = $xpath->query("//tr");

                    foreach ($linhas as $linha) {
                        $cols = $linha->getElementsByTagName('td');
                        
                        // Layout da sua foto (User | # | IP | Connected | ... | Service)
                        if ($cols->length >= 4) {
                            $u_raw = trim($cols->item(0)->textContent); // Coluna 0: User
                            $i_raw = trim($cols->item(2)->textContent); // Coluna 2: IP
                            
                            // Canal (Última coluna)
                            $c_raw = "---";
                            if($cols->length > 0) {
                                $c_raw = trim($cols->item($cols->length - 1)->textContent);
                            }

                            // Limpeza
                            $u_clean = preg_replace('/\s+/', '', $u_raw);
                            
                            // Filtra cabeçalhos e linhas de sistema
                            if (empty($u_clean) || stripos($u_clean, 'User') !== false || stripos($u_clean, 'Capacity') !== false) continue;

                            // Validação no Banco
                            $sqlCheck = "SELECT CadUser, nome FROM usuario WHERE usuario = :u UNION SELECT CadUser, 'Teste' as nome FROM teste WHERE usuario = :u";
                            $stmt = $connUser->prepare($sqlCheck);
                            $stmt->execute([':u' => $u_clean]);
                            $d = $stmt->fetch(PDO::FETCH_ASSOC);

                            if ($d) {
                                if ($isAdmin || $d['CadUser'] == $usuarioLogado) {
                                    $clientes_online[] = [
                                        'usuario' => $u_clean,
                                        'nome'    => $d['nome'],
                                        'dono'    => $d['CadUser'],
                                        'ip'      => $i_raw,
                                        'canal'   => $c_raw
                                    ];
                                    $total_online++;
                                }
                            } else {
                                if($isAdmin && count($clientes_online) < 5) {
                                    $log_diagnostico[] = "Usuário na CSP ignorado (não está no banco): $u_clean";
                                }
                            }
                        }
                    }
                }
            }
        }
        
        if (!$achou_tabela) {
            $log_diagnostico[] = "❌ Nenhum frame continha a tabela de usuários.";
        }

    } else {
        $log_diagnostico[] = "Erro ao conectar na raiz. HTTP: {$req['code']}";
    }
} else {
    $log_diagnostico[] = "Sem configuração no banco.";
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clientes 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: #7367f0; --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; }
        .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; padding: 30px; transition: 0.3s; }
        .card-custom { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-color); }
        .table-custom { width: 100%; border-collapse: collapse; }
        .table-custom th { text-align: left; padding: 15px; color: #b9b9c3; font-size: 0.85rem; text-transform: uppercase; font-weight: 700; border-bottom: 1px solid var(--border-color); background: #252535; }
        .table-custom td { padding: 15px; border-bottom: 1px solid var(--border-color); font-size: 0.95rem; color: #fff; vertical-align: middle; }
        .status-dot { width: 10px; height: 10px; background: #28c76f; border-radius: 50%; display: inline-block; box-shadow: 0 0 8px #28c76f; margin-right: 8px; }
        .badge-canal { background: rgba(115, 103, 240, 0.15); color: #7367f0; padding: 5px 10px; border-radius: 4px; font-size: 0.8rem; font-weight: 600; border: 1px solid rgba(115, 103, 240, 0.3); }
        .mobile-toggle { display: none; color: #fff; font-size: 1.5rem; background: none; border: none; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } .mobile-toggle { display: block; } }
    </style>
</head>
<body>

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

<nav class="sidebar" id="sidebar">
    <div class="nav flex-column mt-4">
        <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="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configurações</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="clientes_online.php" class="nav-link active"><i class="fas fa-wifi"></i> Online Agora</a>
        <a href="monitor.php" class="nav-link"><i class="fas fa-bell"></i> Monitor</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">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-0">Clientes Conectados</h3>
            <p class="text-white-50 mb-0">Monitoramento: <span class="text-info"><?= $ip ?>:<?= $port ?></span></p>
        </div>
        <button class="btn btn-primary" onclick="location.reload()"><i class="fas fa-sync-alt me-2"></i>Atualizar</button>
    </div>

    <div class="row mb-4">
        <div class="col-12 col-md-4">
            <div class="card bg-dark border-secondary p-3">
                <h5 class="text-white-50 small mb-1">TOTAL ONLINE</h5>
                <h2 class="text-success fw-bold m-0"><?= $total_online ?></h2>
            </div>
        </div>
    </div>

    <div class="card card-custom overflow-hidden shadow-lg">
        <div class="table-responsive">
            <table class="table-custom">
                <thead>
                    <tr>
                        <th>Usuário</th>
                        <th>Canal</th>
                        <th>IP</th>
                        <th>Dono</th>
                        <th class="text-end">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($clientes_online) > 0): ?>
                        <?php foreach($clientes_online as $c): ?>
                        <tr>
                            <td>
                                <div class="fw-bold text-white"><?= htmlspecialchars($c['usuario']) ?></div>
                                <div class="text-white-50 small"><?= htmlspecialchars($c['nome']) ?></div>
                            </td>
                            <td><span class="badge-canal"><?= htmlspecialchars($c['canal']) ?></span></td>
                            <td class="text-info font-monospace"><?= htmlspecialchars($c['ip']) ?></td>
                            <td class="text-warning"><?= htmlspecialchars($c['dono']) ?></td>
                            <td class="text-end"><span class="status-dot"></span> <span class="fw-bold text-success" style="font-size:0.85rem">ON</span></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="5" class="text-center py-5"><p class="text-white-50 m-0">Nenhum cliente conectado ou encontrado no banco.</p></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if($isAdmin): ?>
    <div class="card mt-5 bg-black border-danger">
        <div class="card-header border-danger text-danger fw-bold">DIAGNÓSTICO TÉCNICO</div>
        <div class="card-body p-3 text-start">
            <div style="font-family: monospace; font-size: 0.75rem; color: #00ff00; background: #111; padding: 10px; border-radius: 5px;">
                <?php foreach($log_diagnostico as $log): ?>
                    <div>> <?= $log ?></div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

</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>
