<?php
session_start();
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) { header("Location: login.php"); exit; }
require_once 'conexao.php';

$isAdmin = (strtolower($_SESSION['nivel'] ?? '') === 'admin');
$usuarioLogado = $_SESSION['usuario'];
$filter_rev = $_GET['revendedor'] ?? ''; // Pega o revendedor selecionado no filtro

// --- 1. BUSCA CONFIGURAÇÕES DO SITE (NOME E COR) ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config WHERE id=1 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) { }

// --- 2. BUSCA LISTA DE REVENDEDORES (PARA O SELECT DO ADMIN) ---
$lista_revendedores = [];
if ($isAdmin) {
    try {
        $lista_revendedores = $connUser->query("SELECT usuario FROM rev ORDER BY usuario ASC")->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) { }
}

// --- 3. BUSCA DADOS DO SERVIDOR CSP ---
$csp_ip = ''; $csp_port = ''; $csp_user = ''; $csp_pass = '';
try {
    $srv = $connGeral->query("SELECT url, porta, usuario, senha FROM servidor ORDER BY id DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($srv) {
        $csp_ip = $srv['url']; $csp_port = $srv['porta'];
        $csp_user = $srv['usuario']; $csp_pass = $srv['senha'];
    }
} catch (Exception $e) { }

// --- 4. LÓGICA DE SCRAPING CSP ---
$lista_online = [];
if ($csp_ip) {
    $url = "http://$csp_ip:$csp_port/"; 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_USERPWD, "$csp_user:$csp_pass");
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $html = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code == 200 && !empty($html)) {
        $dom = new DOMDocument();
        @$dom->loadHTML($html);
        $xpath = new DOMXPath($dom);
        $linhas = $xpath->query("//tr");

        foreach ($linhas as $linha) {
            $colunas = $linha->getElementsByTagName('td');
            if ($colunas->length >= 4) {
                $nome_user = preg_replace('/\s+/', '', trim($colunas->item(0)->nodeValue));
                $tempo = trim($colunas->item(3)->nodeValue);

                if (!empty($nome_user) && $nome_user != 'User' && strpos($tempo, 's') !== false) {
                    $revenda = "---";
                    try {
                        $stmt = $connUser->prepare("SELECT CadUser FROM usuario WHERE usuario = ? UNION SELECT CadUser FROM teste WHERE usuario = ?");
                        $stmt->execute([$nome_user, $nome_user]);
                        $dado = $stmt->fetchColumn();
                        if($dado) $revenda = $dado;
                    } catch(Exception $e){}

                    // APLICAÇÃO DOS FILTROS (HIERARQUIA E SELECT)
                    if (!$isAdmin && $revenda !== $usuarioLogado) continue; 
                    if ($isAdmin && $filter_rev !== '' && $revenda !== $filter_rev) continue;

                    $lista_online[] = [
                        'usuario' => $nome_user,
                        'ip' => trim($colunas->item(2)->nodeValue),
                        'tempo' => $tempo,
                        'revenda' => $revenda
                    ];
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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; }
        body { background: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); padding: 20px; border-right: 1px solid #333; transition: 0.3s; z-index: 1050; overflow-y: auto; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 10px 12px; border-radius: 8px; margin-bottom: 2px; display: flex; align-items: center; gap: 10px; transition: 0.2s; text-decoration: none; font-size: 0.9rem; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 20px 0 10px 12px; }
        .card-custom { background: var(--bg-card); border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; }
        .form-select { background: #2b2b40 !important; border: 1px solid #444 !important; color: #fff !important; }
        .fw-white { color: #ffffff !important; font-weight: 700; text-shadow: 1px 1px 2px rgba(0,0,0,0.5); }
        .badge-rev { background: rgba(115, 103, 240, 0.2); color: var(--primary); padding: 4px 8px; border-radius: 4px; font-weight: bold; font-size: 0.8rem; }
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; padding: 15px; } .mobile-toggle { display: block !important; } }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; margin-bottom: 20px; }
        .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">
    <h4 class="mb-4 fw-bold text-white text-center"><i class="fas fa-tv text-primary"></i> <?= htmlspecialchars($nomePainel) ?></h4>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">Administração</div>
            <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Gerenciar Perfis</a>
            <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores DNS</a>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Gestão de Admins</a>
            <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> Config. E-mail</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backups</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Config. Geral</a>
        <?php endif; ?>
        <div class="nav-group-title">Operacional</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="status_online.php" class="nav-link active"><i class="fas fa-wifi"></i> Monitor Online</a>
        <hr class="border-secondary mt-4"><a href="sair.php" class="nav-link text-danger"><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 flex-wrap gap-3">
        <h3 class="fw-bold fw-white m-0">Usuários Online</h3>
        
        <div class="d-flex gap-2">
            <?php if($isAdmin): ?>
            <form method="GET" class="d-flex gap-2">
                <select name="revendedor" class="form-select form-select-sm" style="min-width: 180px;" onchange="this.form.submit()">
                    <option value="">Todos Revendedores</option>
                    <?php foreach($lista_revendedores as $r): ?>
                        <option value="<?= $r['usuario'] ?>" <?= $filter_rev == $r['usuario'] ? 'selected' : '' ?>><?= $r['usuario'] ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
            <?php endif; ?>
            <button onclick="location.reload()" class="btn btn-primary btn-sm fw-bold"><i class="fas fa-sync-alt"></i></button>
        </div>
    </div>

    <div class="card card-custom overflow-hidden shadow-lg">
        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0 align-middle">
                <thead>
                    <tr class="text-white-50 small text-uppercase">
                        <th class="ps-4">Status</th>
                        <th>Usuário</th>
                        <th>Revendedor</th>
                        <th>IP</th>
                        <th>Tempo</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($lista_online)): ?>
                        <tr><td colspan="5" class="text-center py-5 text-white-50">Nenhum usuário conectado para este filtro.</td></tr>
                    <?php else: ?>
                        <?php foreach($lista_online as $u): ?>
                        <tr>
                            <td class="ps-4"><span class="badge bg-success px-3">ONLINE</span></td>
                            <td class="fw-white"><?= htmlspecialchars($u['usuario']) ?></td>
                            <td><span class="badge-rev"><?= htmlspecialchars($u['revenda']) ?></span></td>
                            <td class="text-white-50 small"><?= htmlspecialchars($u['ip']) ?></td>
                            <td class="text-info fw-bold"><?= htmlspecialchars($u['tempo']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </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>
