<?php
session_start();
// --- FORÇA O FUSO HORÁRIO DE BRASÍLIA ---
date_default_timezone_set('America/Sao_Paulo'); 
require_once 'conexao.php';

// --- 1. TRAVA DE SEGURANÇA TOTAL ---
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) {
            die("Acesso Negado: Bloqueado ou Vencido");
        }
    }
}

// --- 2. CONFIGURAÇÕES VISUAIS E DADOS DO CSP ---
$nomePainel = "IPTV PANEL"; $corPrimaria = "#7367f0"; 
$IP_CSP = ""; $PORTA_CSP = ""; $USUARIO_CSP = ""; $SENHA_CSP = "";

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'];
    }
    
    $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) { }

    $dadosCSP = $connGeral->query("SELECT url, porta, usuario, senha FROM painel LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($dadosCSP) {
        $IP_CSP = trim($dadosCSP['url']);
        $PORTA_CSP = trim($dadosCSP['porta']);
        $USUARIO_CSP = trim($dadosCSP['usuario']);
        $SENHA_CSP = trim($dadosCSP['senha']);
    }
} catch (Exception $e) { }

// =========================================================================
// 3. PROCESSAR BOTÕES DE AÇÃO (DERRUBAR E BLOQUEAR)
// =========================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao_monitor'])) {
    header('Content-Type: application/json');
    $acao = $_POST['acao_monitor'];
    $user_login = trim($_POST['user_login']);
    
    $pode_editar = false;
    if ($isAdmin) {
        $pode_editar = true;
    } else {
        $stCheck = $connUser->prepare("SELECT id FROM usuario WHERE usuario = ? AND CadUser = ? UNION SELECT id FROM teste WHERE usuario = ? AND CadUser = ? LIMIT 1");
        $stCheck->execute([$user_login, $usuarioLogado, $user_login, $usuarioLogado]);
        if ($stCheck->rowCount() > 0) $pode_editar = true;
    }

    if ($pode_editar) {
        if (($acao === 'derrubar' || $acao === 'bloquear') && !empty($IP_CSP)) {
            $auth = base64_encode("{$USUARIO_CSP}:{$SENHA_CSP}");
            $ch_kick = curl_init("http://{$IP_CSP}:{$PORTA_CSP}/xmlHandler?command=kick-user&name=" . urlencode($user_login));
            curl_setopt($ch_kick, CURLOPT_HTTPHEADER, ["Authorization: Basic $auth"]);
            curl_setopt($ch_kick, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch_kick, CURLOPT_TIMEOUT, 5);
            curl_exec($ch_kick);
            curl_close($ch_kick);
        }
        if ($acao === 'bloquear') {
            $connUser->prepare("UPDATE usuario SET bloqueado='sim' WHERE usuario=?")->execute([$user_login]);
            $connUser->prepare("UPDATE teste SET bloqueado='sim' WHERE usuario=?")->execute([$user_login]);
        }
        echo json_encode(['status' => 'sucesso']); exit;
    }
    echo json_encode(['status' => 'erro']); exit;
}

$online_users = [];
$revendedores_lista = [];

// --- 4. CONEXÃO CSP ---
if (!empty($IP_CSP) && !empty($PORTA_CSP)) {
    $auth = base64_encode("{$USUARIO_CSP}:{$SENHA_CSP}");
    $ch = curl_init("http://{$IP_CSP}:{$PORTA_CSP}/xmlHandler?command=proxy-users");
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Basic $auth", "Connection: close"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $xml_bruto = trim(curl_exec($ch));
    curl_close($ch);

    if (!empty($xml_bruto)) {
        $xml = @simplexml_load_string($xml_bruto);
        if ($xml) {
            foreach ($xml->xpath('//user') as $u) {
                $login = (string)$u['name'];
                if (empty($login) || $login === '*') continue;
                $sessoes = $u->xpath('.//session');
                foreach ($sessoes as $f) {
                    $ip = (string)$f['host'] ?: (string)$f['ip'];
                    $canal = "Menu";
                    $srvs = $f->xpath('.//service');
                    if (!empty($srvs)) $canal = (string)$srvs[0]['name'];

                    $dono_c = 'Admin';
                    $st = $connUser->prepare("SELECT CadUser FROM usuario WHERE usuario = ? UNION SELECT CadUser FROM teste WHERE usuario = ? LIMIT 1");
                    $st->execute([$login, $login]);
                    if ($r = $st->fetch()) $dono_c = empty($r['CadUser']) ? 'Admin' : $r['CadUser'];

                    if ($isAdmin || $dono_c === $usuarioLogado) {
                        if ($isAdmin && !in_array($dono_c, $revendedores_lista)) $revendedores_lista[] = $dono_c;
                        $online_users[] = [
                            'id' => md5($login . $ip), 'login' => $login, 'ip' => $ip, 
                            'canal' => $canal, 'dono' => $dono_c, 'flags' => (string)$f['flags'] ?: (string)$u['flags'],
                            'tempo' => (string)$f['duration']
                        ];
                    }
                }
            }
        }
    }
}
sort($revendedores_lista);

// AJAX GHOST REFRESH
if (isset($_GET['ajax'])) {
    foreach($online_users as $u) {
        echo '<tr class="user-row" id="usr_'.$u['id'].'" data-login="'.$u['login'].'" data-flags="'.$u['flags'].'">
            <td><span class="dot-online"></span>'.$u['login'].'</td>
            <td class="ip-text">'.$u['ip'].'</td>
            <td class="text-warning fw-bold">'.$u['canal'].'</td>
            <td class="text-center text-secondary small dono-cel">'.$u['dono'].'</td>
            <td class="text-center text-success fw-bold">'.$u['tempo'].'</td>
            <td class="text-center">
                <button class="btn btn-sm btn-warning rounded-circle" onclick="derrubarUser(\''.$u['login'].'\')"><i class="fas fa-plug"></i></button>
                <button class="btn btn-sm btn-danger rounded-circle ms-1" onclick="bloquearUser(\''.$u['login'].'\')"><i class="fas fa-lock"></i></button>
            </td>
        </tr>';
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>


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



    <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; --text-color: #d0d2d6; --border-color: #2b2b40; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; margin: 0; 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; left: 0; }
        .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; }
        .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; position: sticky; top:0; z-index: 1000; }
        
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer; margin-right: 15px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }

        .card-monitor { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 15px; margin: 20px; overflow: hidden; }
        .table-online th { background: rgba(0,0,0,0.2); color: #adb5bd; font-size: 0.75rem; text-transform: uppercase; padding: 12px; }
        .table-online td { border-bottom: 1px solid var(--border-color); padding: 12px; font-size: 0.85rem; vertical-align: middle; }
        .dot-online { width: 8px; height: 8px; background: #28c76f; border-radius: 50%; display: inline-block; margin-right: 8px; box-shadow: 0 0 5px #28c76f; }
        
        .controls-wrapper { padding: 15px; display: flex; flex-wrap: wrap; gap: 10px; }
        .search-container { position: relative; flex: 1; min-width: 200px; }
        .search-container input { background: #151521; border: 1px solid #333; color: white; border-radius: 20px; padding: 8px 15px 8px 40px; width: 100%; }
        .search-container i { position: absolute; left: 15px; top: 11px; color: var(--primary); }
        .filter-select { background: #151521; border: 1px solid #333; color: white; border-radius: 10px; padding: 8px 15px; flex: 1; min-width: 150px; }

        @media (max-width: 992px) {
            .sidebar { left: -260px; }
            .sidebar.show { left: 0; }
            .main-content { margin-left: 0; }
            .mobile-toggle { display: block; }
            .overlay.show { display: block; }
            .controls-wrapper { flex-direction: column; }
        }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>


<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>
            <h5 class="m-0 text-white fw-bold">MONITORAMENTO</h5>
        </div>
        <button onclick="location.reload()" class="btn btn-sm btn-outline-light rounded-pill"><i class="fas fa-sync"></i></button>
    </div>

    <div class="card-monitor shadow">
        <ul class="nav nav-tabs px-3 pt-3" id="monitorTabs">
            <li class="nav-item"><button class="nav-link active" onclick="trocarAba('geral')">Monitor Geral</button></li>
            <?php if ($isAdmin): ?>
                <li class="nav-item"><button class="nav-link text-warning" onclick="trocarAba('reshare')">Controle Reshare</button></li>
            <?php endif; ?>
        </ul>

        <div class="controls-wrapper">
            <div class="search-container"><i class="fas fa-search"></i><input type="text" id="inputBusca" placeholder="Pesquisar..." onkeyup="filtrarTabela()"></div>
            <?php if ($isAdmin): ?>
                <select id="filtroRevenda" class="filter-select" onchange="filtrarTabela()">
                    <option value="todos">Todos Revendedores</option>
                    <?php foreach($revendedores_lista as $rev): ?><option value="<?= $rev ?>"><?= $rev ?></option><?php endforeach; ?>
                </select>
            <?php endif; ?>
            <select id="filtroQtd" class="filter-select" onchange="mudarLimite()"><option value="10">10 por pág.</option><option value="100">100 por pág.</option></select>
            <span class="badge bg-success rounded-pill p-2" id="badge-count"><?= count($online_users) ?> Online</span>
        </div>

        <!-- TABELA GERAL -->
        <div id="aba-geral">
            <div class="table-responsive">
                <table class="table-online w-100">
                    <thead>
                        <tr><th>USUÁRIO</th><th>IP</th><th>CANAL</th><th class="text-center">REVENDA</th><th class="text-center">TEMPO</th><th class="text-center">AÇÕES</th></tr>
                    </thead>
                    <tbody id="tabela-corpo">
                        <?php foreach($online_users as $u): ?>
                        <tr class="user-row" data-login="<?= $u['login'] ?>" data-flags="<?= $u['flags'] ?>">
                            <td><span class="dot-online"></span><?= $u['login'] ?></td>
                            <td class="ip-text"><?= $u['ip'] ?></td>
                            <td class="text-warning fw-bold"><?= $u['canal'] ?></td>
                            <td class="text-center text-secondary dono-cel"><?= $u['dono'] ?></td>
                            <td class="text-center text-success fw-bold"><?= $u['tempo'] ?></td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-warning rounded-circle" onclick="derrubarUser('<?= $u['login'] ?>')"><i class="fas fa-plug"></i></button>
                                <button class="btn btn-sm btn-danger rounded-circle ms-1" onclick="bloquearUser('<?= $u['login'] ?>')"><i class="fas fa-lock"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- TABELA RESHARE -->
        <div id="aba-reshare" style="display:none;">
            <div class="table-responsive">
                <table class="table-online w-100">
                    <thead>
                        <tr><th>USUÁRIO</th><th>IP</th><th>REVENDA</th><th class="text-center">FLAGS</th><th class="text-center">ALERTA</th><th class="text-center">AÇÕES</th></tr>
                    </thead>
                    <tbody id="tabela-reshare-corpo"></tbody>
                </table>
            </div>
        </div>
    </div>
    <?php include 'rodape.php'; ?>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    let abaAtual = 'geral';

    function toggleMenu() {
        document.getElementById('sidebar').classList.toggle('show');
        document.getElementById('overlay').classList.toggle('show');
    }

    function trocarAba(aba) {
        abaAtual = aba;
        document.querySelectorAll('#monitorTabs .nav-link').forEach(b => b.classList.remove('active'));
        event.currentTarget.classList.add('active');

        if(aba === 'geral') {
            document.getElementById('aba-geral').style.display = 'block';
            document.getElementById('aba-reshare').style.display = 'none';
        } else {
            document.getElementById('aba-geral').style.display = 'none';
            document.getElementById('aba-reshare').style.display = 'block';
            sincronizarReshare();
        }
        filtrarTabela();
    }

    function sincronizarReshare() {
        const reshareBody = document.getElementById('tabela-reshare-corpo');
        reshareBody.innerHTML = '';
        const logins = {};
        const rows = document.querySelectorAll('#tabela-corpo tr.user-row');
        
        rows.forEach(r => {
            let log = r.getAttribute('data-login');
            logins[log] = (logins[log] || 0) + 1;
        });

        rows.forEach(r => {
            let log = r.getAttribute('data-login');
            let flags = r.getAttribute('data-flags').toUpperCase();
            if (logins[log] > 1 || flags.includes('Z')) {
                let clone = r.cloneNode(true);
                // Ajustar colunas para o layout de Reshare
                let tds = clone.querySelectorAll('td');
                let ip = tds[1].innerText;
                let revenda = tds[3].innerText;
                let acoes = tds[5].innerHTML;

                clone.innerHTML = `
                    <td class="fw-bold text-info">${log}</td>
                    <td>${ip}</td>
                    <td class="text-center">${revenda}</td>
                    <td class="text-center"><span class="badge bg-secondary">${flags}</span></td>
                    <td class="text-center"><span class="badge bg-danger">ALERTA RESHARE</span></td>
                    <td class="text-center">${acoes}</td>
                `;
                reshareBody.appendChild(clone);
            }
        });
        if(reshareBody.innerHTML === '') reshareBody.innerHTML = '<tr><td colspan="6" class="text-center p-4">Nenhum reshare detectado.</td></tr>';
    }

    function filtrarTabela() {
        let busca = document.getElementById('inputBusca').value.toLowerCase();
        let rev = document.getElementById('filtroRevenda') ? document.getElementById('filtroRevenda').value : 'todos';
        let limite = parseInt(document.getElementById('filtroQtd').value);
        
        let seletor = abaAtual === 'geral' ? '#tabela-corpo tr' : '#tabela-reshare-corpo tr';
        let rows = Array.from(document.querySelectorAll(seletor));

        let filtradas = rows.filter(r => {
            let txt = r.innerText.toLowerCase();
            let donoTd = r.querySelector('.dono-cel');
            let dono = donoTd ? donoTd.innerText.trim() : 'Admin';
            return txt.includes(busca) && (rev === 'todos' || dono === rev);
        });

        rows.forEach(r => r.style.display = 'none');
        filtradas.slice(0, limite).forEach(r => r.style.display = '');
    }

    function mudarLimite() { filtrarTabela(); }
    function derrubarUser(l) { if(confirm("Derrubar "+l+"?")) acao('derrubar', l); }
    function bloquearUser(l) { if(confirm("Bloquear "+l+"?")) acao('bloquear', l); }
    function acao(t, l) {
        let f = new FormData(); f.append('acao_monitor', t); f.append('user_login', l);
        fetch('monitor.php', {method:'POST', body:f}).then(()=>location.reload());
    }

    setInterval(() => {
        fetch('monitor.php?ajax=1').then(r => r.text()).then(html => {
            document.getElementById('tabela-corpo').innerHTML = html;
            if(abaAtual === 'reshare') sincronizarReshare();
            filtrarTabela();
        });
    }, 15000);

    window.onload = filtrarTabela;
</script>
</body>
</html>