<?php
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = 'Monitor IPTV em Tempo Real';

$page_content = '
<div class="row g-3 g-md-5 mb-4">
    <div class="col-6 col-md-3">
        <div class="card card-flush h-100 border-0 shadow-sm">
            <div class="card-body p-4">
                <span class="text-gray-500 fw-semibold d-block fs-7 mb-1">Usuários online</span>
                <span class="fs-2hx fw-bold text-gray-900" id="metric_online">0</span>
                <div class="text-muted fs-8 mt-1"><span class="badge badge-light-success p-1">●</span> Auto 5s</div>
            </div>
        </div>
    </div>

    <div class="col-6 col-md-3">
        <div class="card card-flush h-100 border-0 shadow-sm">
            <div class="card-body p-4">
                <span class="text-gray-500 fw-semibold d-block fs-7 mb-1">Canais ao vivo</span>
                <span class="fs-2hx fw-bold text-primary" id="metric_live">0</span>
            </div>
        </div>
    </div>

    <div class="col-6 col-md-3">
        <div class="card card-flush h-100 border-0 shadow-sm">
            <div class="card-body p-4">
                <span class="text-gray-500 fw-semibold d-block fs-7 mb-1">Filmes</span>
                <span class="fs-2hx fw-bold text-warning" id="metric_movie">0</span>
            </div>
        </div>
    </div>

    <div class="col-6 col-md-3">
        <div class="card card-flush h-100 border-0 shadow-sm">
            <div class="card-body p-4">
                <span class="text-gray-500 fw-semibold d-block fs-7 mb-1">Séries</span>
                <span class="fs-2hx fw-bold text-success" id="metric_series">0</span>
            </div>
        </div>
    </div>
</div>

<div class="row g-5 mb-5">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="alert alert-primary">
                    Monitor IPTV ativo (atualização automática a cada 5s)
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div id="device_summary" class="text-muted fs-7">Carregando...</div>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body">

        <div class="d-flex gap-3 mb-4">
            <input type="text" id="search_monitor" class="form-control" placeholder="Buscar MAC ou conteúdo">
            <select id="type_filter" class="form-select w-200px">
                <option value="all">Todos</option>
                <option value="live">Live</option>
                <option value="movie">Filmes</option>
                <option value="series">Séries</option>
            </select>
        </div>

        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>MAC</th>
                        <th>Conteúdo</th>
                        <th>Tipo</th>
                        <th>Dispositivo</th>
                        <th>Tempo</th>
                    </tr>
                </thead>
                <tbody id="monitor_table"></tbody>
            </table>
        </div>

    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
let monitorData = [];
let previousMacSet = new Set();
let hasLoadedOnce = false;
let audioCtx = null;

// Util
function escapeHtml(t) {
    return String(t || '').replace(/[&<>"']/g, m => ({
        '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'
    }[m]));
}

function shortDuration(s) {
    s = Number(s || 0);
    if (s < 60) return s + "s";
    let m = Math.floor(s / 60);
    if (m < 60) return m + "m";
    let h = Math.floor(m / 60);
    return h + "h " + (m % 60) + "m";
}

function typeBadge(type) {
    const map = {
        live: '📺 LIVE',
        movie: '🎬 FILME',
        series: '📼 SÉRIE'
    };
    return map[type] || type;
}

// Som alerta
function playAlert() {
    if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    if (audioCtx.state === 'suspended') audioCtx.resume();

    const osc = audioCtx.createOscillator();
    const gain = audioCtx.createGain();

    osc.connect(gain);
    gain.connect(audioCtx.destination);

    osc.frequency.value = 880;
    gain.gain.value = 0.1;

    osc.start();
    osc.stop(audioCtx.currentTime + 0.3);
}

// Render
function renderMonitor() {
    const filter = document.getElementById('type_filter').value;
    const search = (document.getElementById('search_monitor').value || '').toLowerCase();

    const filtered = monitorData.filter(i => {
        const mac = String(i.mac || '').toLowerCase();
        const name = String(i.content_name || '').toLowerCase();

        const okType = filter === 'all' || i.content_type === filter;
        const okSearch = mac.includes(search) || name.includes(search);

        return okType && okSearch;
    });

    document.getElementById('monitor_table').innerHTML =
        filtered.map(i => `
        <tr>
            <td>${escapeHtml(i.mac || 'N/A')}</td>
            <td>${escapeHtml(i.content_name || 'N/A')}</td>
            <td>${typeBadge(i.content_type)}</td>
            <td>${escapeHtml(i.device || 'Desconhecido')}</td>
            <td>${shortDuration(i.online_seconds)}</td>
        </tr>
    `).join('');
}

// Load
function loadMonitor() {
    fetch('actions/monitor_actions.php', {
        headers: { 'Accept': 'application/json' },
        cache: 'no-store'
    })
    .then(r => r.text())
    .then(text => {
        let res;
        try {
            res = JSON.parse(text);
        } catch (e) {
            console.error("JSON inválido:", text);
            return;
        }

        if (!res || !res.success) return;

        monitorData = Array.isArray(res.data) ? res.data : [];

        const s = res.summary || {};

        document.getElementById('metric_online').innerText = s.online || 0;
        document.getElementById('metric_live').innerText = s.live || 0;
        document.getElementById('metric_movie').innerText = s.movie || 0;
        document.getElementById('metric_series').innerText = s.series || 0;

        const dev = res.devices || [];
        document.getElementById('device_summary').innerHTML =
            dev.length
                ? dev.map(d => `
                    <div>${escapeHtml(d.name || 'Device')} - ${d.count || 0}</div>
                `).join('')
                : 'Sem dispositivos';

        const currentMacs = new Set(monitorData.map(i => i.mac || ''));

        if (hasLoadedOnce) {
            const hasNew = [...currentMacs].some(m => !previousMacSet.has(m));
            if (hasNew) playAlert();
        }

        previousMacSet = currentMacs;
        hasLoadedOnce = true;

        renderMonitor();
    })
    .catch(err => console.error("Erro:", err));
}

// Init
document.addEventListener('DOMContentLoaded', () => {
    loadMonitor();
    setInterval(loadMonitor, 5000);

    document.getElementById('type_filter').addEventListener('change', renderMonitor);
    document.getElementById('search_monitor').addEventListener('input', renderMonitor);
});
</script>