<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/revenda_schema.php';

revenda_ensure_schema($db);

function db_has_column(PDO $db, string $table, string $col): bool {
    $st = $db->query("PRAGMA table_info(".$table.")");
    while ($r = $st->fetch(PDO::FETCH_ASSOC)) {
        if (($r["name"] ?? "") === $col) return true;
    }
    return false;
}


$db->exec("CREATE TABLE IF NOT EXISTS online_status (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    mac TEXT NOT NULL UNIQUE,
    usuario_id INTEGER,
    is_online INTEGER NOT NULL DEFAULT 0,
    content_type TEXT,
    content_title TEXT,
    content_logo TEXT,
    content_url TEXT,
    position_ms INTEGER,
    duration_ms INTEGER,
    is_playing INTEGER,
    app_screen TEXT,
    app_version TEXT,
    ip TEXT,
    cidade TEXT,
    estado TEXT,
    device_type TEXT DEFAULT 'tv',
    last_seen INTEGER,
    created_at INTEGER,
    updated_at INTEGER
);");

function geo_by_ip(string $ip): array {
    if (!$ip || $ip === "127.0.0.1") return ["cidade"=>"—","estado"=>"—"];
    $url = "http://ip-api.com/json/".$ip."?fields=status,city,regionName";
    $ctx = stream_context_create(["http"=>["timeout"=>2]]);
    $r = @file_get_contents($url,false,$ctx);
    if (!$r) return ["cidade"=>"—","estado"=>"—"];
    $j = json_decode($r,true);
    if (!$j || ($j["status"] ?? "") !== "success") return ["cidade"=>"—","estado"=>"—"];
    return [
        "cidade"=>trim((string)($j["city"] ?? "")) ?: "—",
        "estado"=>trim((string)($j["regionName"] ?? "")) ?: "—"
    ];
}

function formatar_mac($macRaw): string {
    $m = strtoupper(preg_replace('/[^A-F0-9]/', '', (string)$macRaw));
    $m = substr($m, 0, 12);
    if (strlen($m) !== 12) return "—";
    return implode(":", str_split($m, 2));
}

if (!db_has_column($db, "online_status", "cidade")) {
    try { $db->exec("ALTER TABLE online_status ADD COLUMN cidade TEXT"); } catch(Throwable $e){}
}

if (!db_has_column($db, "online_status", "estado")) {
    try { $db->exec("ALTER TABLE online_status ADD COLUMN estado TEXT"); } catch(Throwable $e){}
}

if (!db_has_column($db, "online_status", "device_type")) {
    try { $db->exec("ALTER TABLE online_status ADD COLUMN device_type TEXT DEFAULT 'tv'"); } catch(Throwable $e){}
}
if (!db_has_column($db, "online_status", "usuario_id")) {
    try { $db->exec("ALTER TABLE online_status ADD COLUMN usuario_id INTEGER DEFAULT 0"); } catch(Throwable $e){}
}

$timeout = time() - 120;
$db->prepare("DELETE FROM online_status WHERE last_seen < ?")->execute([$timeout]);
try {
    $db->exec("UPDATE online_status SET usuario_id = COALESCE((
        SELECT u.usuario_id FROM usuarios u
        WHERE REPLACE(UPPER(u.mac), ':', '') = REPLACE(UPPER(online_status.mac), ':', '')
        ORDER BY CASE WHEN COALESCE(u.usuario_id,0)>0 THEN 0 ELSE 1 END, u.rowid DESC
        LIMIT 1
    ), usuario_id, 0)");
    $db->exec("CREATE INDEX IF NOT EXISTS idx_online_status_usuario ON online_status(usuario_id)");
} catch (Throwable $e) {}

$sqlOnline = "
    SELECT 
        o.*,
        u.nome_cliente,
        COALESCE(u.usuario_id, o.usuario_id, 0) AS dono_id,
        r.nome AS revenda_nome,
        r.username AS revenda_username
    FROM online_status o
    LEFT JOIN usuarios u ON u.rowid = (
        SELECT ux.rowid FROM usuarios ux
        WHERE REPLACE(UPPER(ux.mac), ':', '') = REPLACE(UPPER(o.mac), ':', '')
        ORDER BY CASE WHEN COALESCE(ux.usuario_id,0)>0 THEN 0 ELSE 1 END, ux.rowid DESC
        LIMIT 1
    )
    LEFT JOIN revendedores r ON r.id = COALESCE(u.usuario_id, o.usuario_id, 0)
";
$paramsOnline = [];
if ($isRev) {
    $sqlOnline .= " WHERE COALESCE(u.usuario_id, o.usuario_id, 0) = ?";
    $paramsOnline[] = $revId;
}
$sqlOnline .= " ORDER BY o.last_seen DESC";
$q = $db->prepare($sqlOnline);
$q->execute($paramsOnline);
$rows = $q ? $q->fetchAll(PDO::FETCH_ASSOC) : [];

foreach ($rows as $r) {
    $cidade = trim((string)($r["cidade"] ?? ""));
    $estado = trim((string)($r["estado"] ?? ""));

    if ($cidade === "" || $estado === "") {
        $geo = geo_by_ip((string)($r["ip"] ?? ""));
        $up = $db->prepare("UPDATE online_status SET cidade=?, estado=? WHERE id=?");
        $up->execute([$geo["cidade"], $geo["estado"], (int)$r["id"]]);
    }
}

require_once __DIR__ . '/../includes/header.php';
?>
<div class="dns-wrap">
    <div class="card radius-10 dns-card">
        <div class="card-header bg-transparent dns-header">
            <div class="dns-title">
                <div class="ic"><i class="bi bi-broadcast"></i></div>
                <div>
                    <h5>Usuários Online</h5>
                    <span>Monitoramento em tempo real com conteúdo atual, progresso e localização por IP</span>
                </div>
            </div>

            <div class="dns-actions d-flex gap-2 flex-wrap">
                <span class="badge-soft"><i class="bi bi-wifi"></i> Online: <?= count($rows) ?></span>
                <span class="badge-soft"><i class="bi bi-arrow-repeat"></i> Atualiza: 10s</span>
            </div>
        </div>

        <div class="card-body table-responsive p-0">
            <table class="table table-hover table-sm align-middle">
                <thead>
                    <tr>
                        <th>Status</th>
                        <th>Cliente</th>
                        <th>MAC</th>
                        <th>Dispositivo</th>
                        <th>Conteúdo</th>
                        <th>Progresso</th>
                        <th class="text-center">Detalhes</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!$rows): ?>
                        <tr>
                            <td colspan="7" class="text-center text-muted empty-state-cell">
                                Nenhum usuário online agora
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($rows as $o): ?>
                            <?php
                            $progresso = "—";
                            if ((int)($o["duration_ms"] ?? 0) > 0) {
                                $p = (int)(((int)$o["position_ms"] * 100) / (int)$o["duration_ms"]);
                                if ($p < 0) $p = 0;
                                if ($p > 100) $p = 100;
                                $progresso = $p . "%";
                            }

                            $lastSeen = date("d/m/Y H:i:s", (int)($o["last_seen"] ?? time()));
                            $local = trim(((string)($o["cidade"] ?? "—")) . " / " . ((string)($o["estado"] ?? "—")));
                            $macFormatado = formatar_mac($o["mac"] ?? "");
                            $cliente = (string)($o["nome_cliente"] ?? "—");
                            $revendaLabel = trim((string)($o["revenda_nome"] ?? ""));
                            if ($revendaLabel === '') $revendaLabel = trim((string)($o["revenda_username"] ?? ""));

                            $tipo = strtoupper((string)($o["content_type"] ?? "—"));
                            $conteudo = (string)($o["content_title"] ?? "—");

                            $isPlaying = (int)($o["is_playing"] ?? 0) === 1;
                            $statusBadge = $isPlaying
                                ? "<span class='badge bg-success'><i class='bi bi-play-fill'></i> Tocando</span>"
                                : "<span class='badge bg-warning text-dark'><i class='bi bi-pause-fill'></i> Pausado</span>";

                            $deviceTypeRaw = strtolower(trim((string)($o["device_type"] ?? "tv")));
                            $isMobile = in_array($deviceTypeRaw, ["mobile","phone","celular","smartphone","android_mobile"], true);
                            $deviceLabel = $isMobile ? "MOBILE" : "TV";
                            $deviceIcon = $isMobile ? "bi-phone-fill" : "bi-tv-fill";
                            $deviceClass = $isMobile ? "is-mobile" : "is-tv";
                            $deviceBadge = "<span class='device-pill {$deviceClass}'><i class='bi {$deviceIcon}'></i> {$deviceLabel}</span>";
                            ?>
                            <tr>
                                <td><?= $statusBadge ?></td>

                                <td>
                                    <div class="d-flex flex-column">
                                        <span class="fw-1000"><?= htmlspecialchars($cliente ?: "—", ENT_QUOTES, 'UTF-8') ?></span>
                                        <?php if ($isAdmin && $revendaLabel !== ''): ?><span class="sub text-muted"><i class="bi bi-person-badge"></i> Revenda: <?= htmlspecialchars($revendaLabel, ENT_QUOTES, 'UTF-8') ?></span><?php endif; ?>
                                        <span class="sub text-muted"><i class="bi bi-clock-history"></i> <?= $lastSeen ?></span>
                                    </div>
                                </td>

                                <td class="mac"><?= htmlspecialchars($macFormatado, ENT_QUOTES, 'UTF-8') ?></td>

                                <td><?= $deviceBadge ?></td>

                                <td>
                                    <div class="d-flex flex-column">
                                        <span class="content-title"><?= htmlspecialchars($conteudo ?: "—", ENT_QUOTES, 'UTF-8') ?></span>
                                        <span class="sub text-muted"><i class="bi bi-film"></i> Player do app</span>
                                    </div>
                                </td>

                                <td>
                                    <?= $progresso === "—"
                                        ? "<span class='small-muted'>—</span>"
                                        : "<span class='progress-pill'><i class='bi bi-bar-chart-fill'></i> {$progresso}</span>"
                                    ?>
                                </td>

                                <td class="text-center">
                                    <button type="button" class="btn btn-light btn-sm btn-online-details details-btn"
                                        data-cliente="<?= htmlspecialchars($cliente ?: '—', ENT_QUOTES, 'UTF-8') ?>"
                                        data-mac="<?= htmlspecialchars($macFormatado, ENT_QUOTES, 'UTF-8') ?>"
                                        data-tipo="<?= htmlspecialchars($tipo ?: '—', ENT_QUOTES, 'UTF-8') ?>"
                                        data-local="<?= htmlspecialchars($local ?: '—', ENT_QUOTES, 'UTF-8') ?>"
                                        data-last="<?= htmlspecialchars($lastSeen, ENT_QUOTES, 'UTF-8') ?>"
                                        data-ip="<?= htmlspecialchars((string)($o["ip"] ?? "—"), ENT_QUOTES, 'UTF-8') ?>"
                                        data-conteudo="<?= htmlspecialchars($conteudo ?: '—', ENT_QUOTES, 'UTF-8') ?>">
                                        <i class="bi bi-eye-fill"></i> Ver info
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="onlineDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-shield-lock"></i> Informações sensíveis</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="sensitive-modal-list">
                    <div class="sensitive-row"><small>Cliente</small><strong id="odCliente">—</strong></div>
                    <div class="sensitive-row"><small>MAC</small><strong id="odMac">—</strong></div>
                    <div class="sensitive-row"><small>Conteúdo</small><strong id="odConteudo">—</strong></div>
                    <div class="sensitive-row"><small>Tipo</small><strong id="odTipo">—</strong></div>
                    <div class="sensitive-row"><small>Localização</small><strong id="odLocal">—</strong></div>
                    <div class="sensitive-row"><small>Última atividade</small><strong id="odLast">—</strong></div>
                    <div class="sensitive-row"><small>IP</small><strong id="odIp">—</strong></div>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Fechar</button>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>