<?php
require_once __DIR__.'/includes/config.php';
require_login();
cleanup_old_online_clients();

$db = db();
$timeout = clients_online_timeout_seconds();
$cutoff = date('Y-m-d H:i:s', time() - $timeout);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['clear_offline'])) {
        $stmt = $db->prepare('DELETE FROM client_online_status WHERE ultima_atividade < :cutoff');
        $stmt->bindValue(':cutoff', $cutoff, SQLITE3_TEXT);
        $stmt->execute();
        header('Location: clientes_online.php?ok=offline_removidos'); exit;
    }
    if (isset($_POST['clear_all'])) {
        $db->exec('DELETE FROM client_online_status');
        header('Location: clientes_online.php?ok=limpo'); exit;
    }
}

$q = trim($_GET['q'] ?? '');
$where = '1=1';
$params = [];
if ($q !== '') {
    $where .= ' AND (usuario LIKE :q OR senha LIKE :q OR mac LIKE :q OR android_id LIKE :q OR canal LIKE :q OR ip LIKE :q OR modelo LIKE :q)';
    $params[':q'] = '%' . $q . '%';
}

$sql = "SELECT *, CASE WHEN ultima_atividade >= :cutoff AND status='online' THEN 1 ELSE 0 END AS online_now
        FROM client_online_status
        WHERE $where
        ORDER BY online_now DESC, ultima_atividade DESC
        LIMIT 300";
$stmt = $db->prepare($sql);
$stmt->bindValue(':cutoff', $cutoff, SQLITE3_TEXT);
foreach($params as $k=>$v){ $stmt->bindValue($k, $v, SQLITE3_TEXT); }
$res = $stmt->execute();
$rows = [];
while($r = $res->fetchArray(SQLITE3_ASSOC)){ $rows[] = $r; }

$onlineCount = count_online_clients();
$totalCount = (int)$db->querySingle('SELECT COUNT(*) FROM client_online_status');
$watchingCount = (int)$db->querySingle("SELECT COUNT(*) FROM client_online_status WHERE canal <> '' AND ultima_atividade >= '".SQLite3::escapeString($cutoff)."'");

include __DIR__.'/includes/header.php';
?>

<div class="grid stats-grid">
    <div class="stat-card"><div class="stat-icon">🟢</div><div class="stat-label">Online agora</div><div class="stat-value"><?=h($onlineCount)?></div><div class="stat-note">ativos nos últimos <?=$timeout?>s</div></div>
    <div class="stat-card"><div class="stat-icon">📺</div><div class="stat-label">Assistindo canal</div><div class="stat-value"><?=h($watchingCount)?></div><div class="stat-note">com canal informado</div></div>
    <div class="stat-card"><div class="stat-icon">📡</div><div class="stat-label">Registrados</div><div class="stat-value"><?=h($totalCount)?></div><div class="stat-note">dispositivos já vistos</div></div>
    <div class="stat-card"><div class="stat-icon">🔄</div><div class="stat-label">Atualização</div><div class="stat-value">30s</div><div class="stat-note">recarrega automático</div></div>
</div>

<div class="card" style="margin-top:18px">
    <h2>📡 Clientes Online</h2>
    <p class="muted">Esta tela já está pronta para receber dados do APK. Depois vamos ligar o aplicativo na API <b>api/status_cliente.php</b>.</p>

    <?php if(!empty($_GET['ok'])): ?><p class="ok">Ação executada com sucesso.</p><?php endif; ?>

    <form method="get" style="display:grid;grid-template-columns:1fr auto;gap:10px;align-items:end">
        <div>
            <label>Pesquisar</label>
            <input type="text" name="q" value="<?=h($q)?>" placeholder="Usuário, senha, MAC, Android ID, canal, IP ou modelo">
        </div>
        <button class="btn" type="submit">🔎 Buscar</button>
    </form>

    <div style="display:flex;gap:10px;flex-wrap:wrap;margin:8px 0 16px">
        <a class="btn dark" href="clientes_online.php">🔄 Atualizar</a>
        <form method="post" onsubmit="return confirm('Apagar clientes offline antigos?')"><button class="btn gray" name="clear_offline" value="1" type="submit">🧹 Limpar offline</button></form>
        <form method="post" onsubmit="return confirm('Apagar TODO o histórico de clientes online?')"><button class="btn red" name="clear_all" value="1" type="submit">🗑️ Limpar tudo</button></form>
    </div>

    <div style="overflow:auto">
        <table>
            <tr>
                <th>Status</th>
                <th>Usuário</th>
                <th>Senha</th>
                <th>Canal atual</th>
                <th>MAC</th>
                <th>Android ID</th>
                <th>IP</th>
                <th>Dispositivo</th>
                <th>Última atividade</th>
            </tr>
            <?php if(!$rows): ?>
            <tr><td colspan="9" class="muted">Nenhum cliente registrado ainda. Depois que ligarmos o APK, eles aparecerão aqui.</td></tr>
            <?php endif; ?>
            <?php foreach($rows as $r):
                $isOnline = ((int)$r['online_now'] === 1);
            ?>
            <tr>
                <td><?= $isOnline ? '<span class="ok">🟢 Online</span>' : '<span class="bad">⚫ Offline</span>' ?></td>
                <td><?=h($r['usuario'])?></td>
                <td><?=h($r['senha'])?></td>
                <td><span class="pill"><?=h($r['canal'] ?: '-')?></span></td>
                <td><?=h($r['mac'] ?: '-')?></td>
                <td><?=h($r['android_id'] ?: '-')?></td>
                <td><?=h($r['ip'] ?: '-')?></td>
                <td><?=h($r['modelo'] ?: '-')?></td>
                <td><?=h($r['ultima_atividade'])?></td>
            </tr>
            <?php endforeach; ?>
        </table>
    </div>
</div>

<script>
setTimeout(function(){ window.location.reload(); }, 30000);
</script>
<?php include __DIR__.'/includes/footer.php'; ?>
