<?php
declare(strict_types=1);

session_start();

$dbPath = dirname(__DIR__) . "/api/db.db";

try {
    $db = new PDO("sqlite:" . $dbPath, null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
} catch (Throwable $e) {
    die("Erro SQLite");
}

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;
}

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){}
}

$timeout = time() - 60;
$db->prepare("DELETE FROM online_status WHERE last_seen < ?")->execute([$timeout]);

$q = $db->query("
    SELECT 
        o.*,
        u.nome_cliente
    FROM online_status o
    LEFT JOIN usuarios u ON REPLACE(UPPER(u.mac), ':', '') = REPLACE(UPPER(o.mac), ':', '')
    ORDER BY o.last_seen DESC
");

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

include "./includes/header.php";
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

<style>
.dns-wrap{
    width:100%;
    max-width:none;
    margin:0;
    padding:0 18px;
}
.dns-card{
    border-radius:18px;
    overflow:hidden;
    width:100%;
    margin-bottom:18px;
}
.dns-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:18px 22px;
}
.dns-title{
    display:flex;
    align-items:center;
    gap:14px;
}
.dns-title .ic{
    width:44px;
    height:44px;
    min-width:44px;
    border-radius:14px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    display:flex;
    align-items:center;
    justify-content:center;
}
.dns-title .ic i{
    font-size:24px;
    color:#198754;
}
.dns-title h5{
    margin:0;
    font-weight:900;
}
.dns-title span{
    display:block;
    margin-top:3px;
    font-size:13px;
    color:rgba(255,255,255,.55);
}
.badge-soft{
    display:inline-flex;
    align-items:center;
    gap:7px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(25,135,84,.10);
    border:1px solid rgba(25,135,84,.20);
    color:#198754;
    font-weight:900;
    white-space:nowrap;
}
.table{
    margin:0;
}
.table thead th{
    font-size:12px;
    text-transform:uppercase;
    letter-spacing:.6px;
    opacity:.75;
    font-weight:1000;
    white-space:nowrap;
}
.table td{
    padding-top:14px;
    padding-bottom:14px;
    vertical-align:middle;
}
.mac{
    font-weight:1000;
    letter-spacing:.2px;
    white-space:nowrap;
}
.content-title{
    font-weight:1000;
}
.sub{
    font-size:12px;
    opacity:.75;
    margin-top:2px;
}
.small-muted{
    font-size:12px;
    color:rgba(255,255,255,.55);
}
.badge{
    border-radius:999px;
    padding:7px 10px;
    font-weight:1000;
    letter-spacing:.2px;
}
.progress-pill{
    font-weight:1000;
    border-radius:999px;
    padding:7px 12px;
    display:inline-flex;
    align-items:center;
    gap:7px;
    border:1px solid rgba(13,110,253,.18);
    background:rgba(13,110,253,.08);
    color:#0d6efd;
    white-space:nowrap;
}
.device-pill{
    font-weight:1000;
    border-radius:999px;
    padding:7px 12px;
    display:inline-flex;
    align-items:center;
    gap:7px;
    border:1px solid rgba(13,110,253,.18);
    background:rgba(13,110,253,.08);
    color:#0d6efd;
    white-space:nowrap;
}
.device-pill.is-mobile{
    border-color:rgba(25,135,84,.18);
    background:rgba(25,135,84,.10);
    color:#198754;
}
.device-pill.is-tv{
    border-color:rgba(255,193,7,.20);
    background:rgba(255,193,7,.10);
    color:#a36b00;
}
.details-btn{
    border-radius:14px;
    min-height:38px;
    font-weight:900;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:7px;
}
.sensitive-modal-list{
    display:flex;
    flex-direction:column;
    gap:10px;
}
.sensitive-row{
    display:flex;
    justify-content:space-between;
    gap:14px;
    align-items:center;
    border:1px solid rgba(0,0,0,.08);
    background:rgba(0,0,0,.025);
    border-radius:14px;
    padding:10px 12px;
}
.sensitive-row small{
    color:#444;
    font-weight:900;
}
.sensitive-row strong{
    color:#000;
    text-align:right;
    word-break:break-word;
}
.modal-content{
    border-radius:20px !important;
    overflow:hidden;
}
.modal-header{
    background:rgba(0,0,0,.02);
    border-bottom:1px solid rgba(0,0,0,.06);
}
.modal-footer .btn{
    border-radius:14px;
    font-weight:900;
}
#onlineDetailsModal.manual-show{
    display:block !important;
    opacity:1 !important;
    background:rgba(0,0,0,.58);
}
#onlineDetailsModal.manual-show .modal-dialog{
    transform:none !important;
}
body.modal-open-manual{
    overflow:hidden;
}
@media(max-width:575px){
    .dns-wrap{
        padding:0 8px;
    }
    .dns-header{
        align-items:flex-start;
        padding:16px;
    }
    .dns-title .ic{
        width:40px;
        height:40px;
        min-width:40px;
    }
    .dns-title .ic i{
        font-size:22px;
    }
    .dns-title h5{
        font-size:18px;
    }
    .badge-soft{
        padding:7px 10px;
        font-size:12px;
    }
}
</style>

<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" style="padding:26px 8px;">
                                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"] ?? "—");

                            $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 style="display:flex;flex-direction:column;">
                                        <span style="font-weight:1000;"><?= htmlspecialchars($cliente ?: "—", ENT_QUOTES, 'UTF-8') ?></span>
                                        <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 style="display:flex;flex-direction: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>

<script>
window.ONLINES_MODAL_OPEN = false;

document.addEventListener("DOMContentLoaded", function () {
    function setText(id, value) {
        var el = document.getElementById(id);
        if (el) el.textContent = value && String(value).trim() !== "" ? value : "—";
    }

    function openOnlineDetails(button) {
        setText("odCliente", button.getAttribute("data-cliente"));
        setText("odMac", button.getAttribute("data-mac"));
        setText("odConteudo", button.getAttribute("data-conteudo"));
        setText("odTipo", button.getAttribute("data-tipo"));
        setText("odLocal", button.getAttribute("data-local"));
        setText("odLast", button.getAttribute("data-last"));
        setText("odIp", button.getAttribute("data-ip"));

        var modal = document.getElementById("onlineDetailsModal");
        if (!modal) return;

        window.ONLINES_MODAL_OPEN = true;

        if (window.bootstrap && window.bootstrap.Modal) {
            window.bootstrap.Modal.getOrCreateInstance(modal).show();
            return;
        }

        modal.classList.add("show", "manual-show");
        modal.removeAttribute("aria-hidden");
        modal.setAttribute("aria-modal", "true");
        document.body.classList.add("modal-open-manual");
    }

    function closeOnlineDetails() {
        var modal = document.getElementById("onlineDetailsModal");
        if (!modal) return;

        window.ONLINES_MODAL_OPEN = false;

        if (window.bootstrap && window.bootstrap.Modal) {
            var instance = window.bootstrap.Modal.getInstance(modal);
            if (instance) {
                instance.hide();
                return;
            }
        }

        modal.classList.remove("show", "manual-show");
        modal.setAttribute("aria-hidden", "true");
        modal.removeAttribute("aria-modal");
        document.body.classList.remove("modal-open-manual");
    }

    document.addEventListener("click", function (event) {
        var detailsButton = event.target.closest(".btn-online-details");
        if (detailsButton) {
            event.preventDefault();
            openOnlineDetails(detailsButton);
            return;
        }

        var closeButton = event.target.closest("[data-bs-dismiss='modal']");
        if (closeButton && closeButton.closest("#onlineDetailsModal")) {
            event.preventDefault();
            closeOnlineDetails();
            return;
        }

        if (event.target && event.target.id === "onlineDetailsModal") {
            closeOnlineDetails();
        }
    });

    var modal = document.getElementById("onlineDetailsModal");
    if (modal) {
        modal.addEventListener("hidden.bs.modal", function () {
            window.ONLINES_MODAL_OPEN = false;
        });
        modal.addEventListener("shown.bs.modal", function () {
            window.ONLINES_MODAL_OPEN = true;
        });
    }

    document.addEventListener("keydown", function (event) {
        if (event.key === "Escape" && window.ONLINES_MODAL_OPEN) {
            closeOnlineDetails();
        }
    });
});
</script>

<script src="assets/js/onlines-1.js?v=2"></script>

<?php include "./includes/footer.php"; ?>