<?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 class="text-muted fs-8 mt-1">Live</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">Filmes</span>
                <span class="fs-2hx fw-bold text-warning" id="metric_movie">0</span>
                <div class="text-muted fs-8 mt-1">VOD</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">Séries</span>
                <span class="fs-2hx fw-bold text-success" id="metric_series">0</span>
                <div class="text-muted fs-8 mt-1">TV Shows</div>
            </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-header border-0 pt-5">
                <h3 class="card-title align-items-start flex-column">
                    <span class="card-label fw-bold fs-3 mb-1">Monitor de Atividade</span>
                    <span class="text-muted fw-semibold fs-7">MAC + Conteúdo + Dispositivo</span>
                </h3>
            </div>
            <div class="card-body">
                <div class="alert alert-dismissible bg-light-primary d-flex flex-column flex-sm-row p-5 mb-0">
                    <i class="ki-outline ki-notification-on fs-2hx text-primary me-4 mb-5 mb-sm-0"></i>
                    <div class="d-flex flex-column pe-0 pe-sm-10">
                        <h5 class="mb-1 text-primary">Monitoramento Ativo</h5>
                        <span class="fs-7">O sistema detecta novos acessos e emite um alerta sonoro automaticamente a cada 5 segundos.</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-header border-0 pt-5">
                <h3 class="card-title align-items-start flex-column">
                    <span class="card-label fw-bold fs-3 mb-1">Dispositivos</span>
                </h3>
            </div>
            <div class="card-body pt-2">
                <div id="device_summary" class="d-flex flex-column gap-3">
                    <div class="text-muted fs-7">Carregando dispositivos...</div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <div class="d-flex align-items-center position-relative my-1">
                <i class="ki-outline ki-magnifier fs-3 position-absolute ms-5"></i>
                <input type="text" id="search_monitor" class="form-control form-control-solid w-250px ps-13" placeholder="Buscar usuário ou MAC" />
            </div>
        </div>
        <div class="card-toolbar gap-3">
            <select id="type_filter" class="form-select form-select-solid w-150px">
                <option value="all">Todos os tipos</option>
                <option value="live">Live</option>
                <option value="movie">Filmes</option>
                <option value="series">Séries</option>
            </select>
            <button class="btn btn-primary" onclick="loadMonitor(true)">
                <i class="ki-outline ki-arrows-circle fs-2"></i> Atualizar Agora
            </button>
        </div>
    </div>
    
    <div class="card-body py-4">
        <div class="table-responsive d-none d-md-block">
            <table class="table align-middle table-row-dashed fs-6 gy-5" id="monitor_table_desktop">
                <thead>
                    <tr class="text-start text-muted fw-bold fs-7 text-uppercase gs-0">
                        <th class="min-w-125px">MAC / Usuário</th>
                        <th class="min-w-200px">Conteúdo</th>
                        <th class="min-w-100px">Tipo</th>
                        <th class="min-w-150px">Dispositivo</th>
                        <th class="min-w-100px">Online há</th>
                        <th class="text-end min-w-70px">Ações</th>
                    </tr>
                </thead>
                <tbody class="text-gray-600 fw-semibold" id="monitor_table_body_desktop"></tbody>
            </table>
        </div>

        <div class="d-block d-md-none" id="monitor_cards_mobile"></div>
    </div>
</div>

<div class="text-center text-muted fs-8 mt-10 mb-5">
    2026 © MaxRebrands · Monitor IPTV v2.0
</div>
';

include 'includes/layout.php';
?>

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

// Funções de Utilitário
function escapeHtml(t) { return String(t || "").replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#039;"}[m])); }

function shortDuration(s) {
    s = Math.max(0, 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 maps = {
        'live': '<span class="badge badge-light-primary">📺 LIVE</span>',
        'movie': '<span class="badge badge-light-warning">🎬 FILME</span>',
        'series': '<span class="badge badge-light-success">📼 SÉRIE</span>'
    };
    return maps[type] || type;
}

// Lógica de Áudio
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.type = 'sine';
    osc.frequency.setValueAtTime(880, audioCtx.currentTime);
    gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.5);
    osc.start();
    osc.stop(audioCtx.currentTime + 0.5);
}

function renderMonitor() {
    const filter = document.getElementById('type_filter').value;
    const searchTerm = document.getElementById('search_monitor').value.toLowerCase();
    
    const filtered = monitorData.filter(item => {
        const matchesType = filter === 'all' || item.content_type === filter;
        const matchesSearch = item.mac.toLowerCase().includes(searchTerm) || 
                             item.content_name.toLowerCase().includes(searchTerm);
        return matchesType && matchesSearch;
    });

    // Desktop
    const tbody = document.getElementById('monitor_table_body_desktop');
    tbody.innerHTML = filtered.map(item => `
        <tr>
            <td><div class="badge badge-light-dark fw-bold">${escapeHtml(item.mac)}</div></td>
            <td>
                <div class="d-flex align-items-center">
                    <div class="symbol symbol-40px me-3">
                        <img src="${item.content_icon || ''}" onerror="this.src='https://placehold.co/40x40?text=IPTV'">
                    </div>
                    <div class="d-flex flex-column">
                        <span class="text-gray-800 fw-bold">${escapeHtml(item.content_name)}</span>
                    </div>
                </div>
            </td>
            <td>${typeBadge(item.content_type)}</td>
            <td><span class="text-muted fs-7">${escapeHtml(item.device_bucket || item.device)}</span></td>
            <td>${shortDuration(item.online_seconds)}</td>
            <td class="text-end">
                <span class="badge badge-light-info">Ativo</span>
            </td>
        </tr>
    `).join('');

    // Mobile
    const mobileContainer = document.getElementById('monitor_cards_mobile');
    mobileContainer.innerHTML = filtered.map(item => `
        <div class="card border-0 bg-light-light mb-3">
            <div class="card-body p-4">
                <div class="d-flex align-items-center mb-2">
                    <div class="symbol symbol-40px me-3">
                        <img src="${item.content_icon || ''}" onerror="this.src='https://placehold.co/40x40?text=IPTV'">
                    </div>
                    <div class="flex-grow-1">
                        <div class="fw-bold">${escapeHtml(item.content_name)}</div>
                        <div class="text-muted fs-8">${item.mac}</div>
                    </div>
                    ${typeBadge(item.content_type)}
                </div>
                <div class="d-flex justify-content-between fs-8 text-muted">
                    <span>📱 ${escapeHtml(item.device_bucket)}</span>
                    <span>⏱️ ${shortDuration(item.online_seconds)}</span>
                </div>
            </div>
        </div>
    `).join('');
}

function loadMonitor(isManual = false) {
    fetch('actions/monitor_actions.php')
        .then(r => r.json())
        .then(res => {
            if (!res.success) return;
            
            monitorData = res.data || [];
            
            // Atualiza Métricas Topo
            document.getElementById('metric_online').innerText = res.summary.online;
            document.getElementById('metric_live').innerText = res.summary.live;
            document.getElementById('metric_movie').innerText = res.summary.movie;
            document.getElementById('metric_series').innerText = res.summary.series;

            // Dispositivos
            const devSummary = document.getElementById('device_summary');
            devSummary.innerHTML = (res.devices || []).map(d => `
                <div class="d-flex align-items-center justify-content-between bg-light-primary rounded p-2">
                    <span class="fw-bold fs-8">${d.name}</span>
                    <span class="badge badge-primary">${d.count}</span>
                </div>
            `).join('');

            // Alerta Sonoro
            const currentMacs = new Set(monitorData.map(i => i.mac));
            if (hasLoadedOnce) {
                let hasNew = false;
                currentMacs.forEach(mac => {
                    if (!previousMacSet.has(mac)) hasNew = true;
                });
                if (hasNew) playAlert();
            }
            
            previousMacSet = currentMacs;
            hasLoadedOnce = true;

            renderMonitor();

            if (isManual && typeof Swal !== 'undefined') {
                Swal.fire({ toast: true, position: 'top-end', icon: 'success', title: 'Monitor atualizado', showConfirmButton: false, timer: 1000 });
            }
        })
        .catch(e => console.error("Erro no monitor:", e));
}

document.addEventListener('DOMContentLoaded', () => {
    // Carregamento inicial
    loadMonitor();

    // Auto Refresh a cada 5 segundos
    setInterval(() => {
        loadMonitor(false);
    }, 5000);

    // Filtros e Busca em tempo real
    document.getElementById('type_filter').addEventListener('change', renderMonitor);
    document.getElementById('search_monitor').addEventListener('input', renderMonitor);

    // Desbloqueio de áudio por interação
    ['click', 'touchstart', 'keydown'].forEach(evt => {
        document.addEventListener(evt, () => {
            if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            if (audioCtx.state === 'suspended') audioCtx.resume();
        }, { once: true });
    });
});
</script>