<?php
require_once __DIR__ . '/../includes/header.php';
require_admin();
$pdo = db();

$stmt = $pdo->query("
    SELECT pl.*, mi.label, mi.host, u.email AS user_email, u.name AS user_name
    FROM ping_logs pl
    JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
    JOIN users u ON u.id = mi.user_id
    ORDER BY pl.checked_at DESC
    LIMIT 500
");
$logs = $stmt->fetchAll();

$totalOnline  = count(array_filter($logs, fn($l) => $l['status'] === 'online'));
$totalOffline = count($logs) - $totalOnline;
?>

<style>
@keyframes pulse-dot {
    0%, 100% { opacity: 1; transform: scale(1); }
    50%       { opacity: 0.4; transform: scale(1.5); }
}
.pulse-dot { animation: pulse-dot 1.4s ease-in-out infinite; }
.log-row-admin { transition: background 0.12s; }
.log-row-admin:hover { background: #f0f9ff !important; }
</style>

<div style="display:flex; flex-direction:column; gap:20px;">

    <!-- Header -->
    <div style="background:linear-gradient(135deg,#1e293b,#0f172a); border-radius:20px; padding:28px 32px; color:#f1f5f9; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:16px;">
        <div>
            <h2 style="margin:0 0 4px; font-size:1.6rem; font-weight:800;">📋 Logs Globais de Ping</h2>
            <p style="margin:0; color:#94a3b8; font-size:0.9rem;">Últimos 500 registros de todos os usuários</p>
        </div>
        <div style="display:flex; gap:20px; flex-wrap:wrap;">
            <div style="text-align:center;">
                <div style="font-size:1.6rem; font-weight:800; color:#22c55e;"><?php echo $totalOnline; ?></div>
                <div style="font-size:0.7rem; text-transform:uppercase; color:#64748b; letter-spacing:1px;">Online</div>
            </div>
            <div style="text-align:center;">
                <div style="font-size:1.6rem; font-weight:800; color:#ef4444;"><?php echo $totalOffline; ?></div>
                <div style="font-size:0.7rem; text-transform:uppercase; color:#64748b; letter-spacing:1px;">Offline</div>
            </div>
            <div style="text-align:center;">
                <div style="font-size:1.6rem; font-weight:800; color:#f1f5f9;"><?php echo count($logs); ?></div>
                <div style="font-size:0.7rem; text-transform:uppercase; color:#64748b; letter-spacing:1px;">Total</div>
            </div>
        </div>
    </div>

    <!-- Filtros + Busca -->
    <div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
        <span style="font-size:0.85rem; font-weight:600; color:#64748b;">Filtrar:</span>
        <button onclick="adminFilter('all')"    id="af-all"     style="padding:6px 16px; border-radius:99px; border:1px solid #cbd5e1; background:#fff; font-size:0.82rem; font-weight:700; color:#475569; cursor:pointer;">Todos (<?php echo count($logs); ?>)</button>
        <button onclick="adminFilter('online')"  id="af-online"  style="padding:6px 16px; border-radius:99px; border:1px solid #bbf7d0; background:#f0fdf4; font-size:0.82rem; font-weight:700; color:#16a34a; cursor:pointer;">Online (<?php echo $totalOnline; ?>)</button>
        <button onclick="adminFilter('offline')" id="af-offline" style="padding:6px 16px; border-radius:99px; border:1px solid #fca5a5; background:#fff5f5; font-size:0.82rem; font-weight:700; color:#dc2626; cursor:pointer;">Offline (<?php echo $totalOffline; ?>)</button>

        <div style="position:relative; margin-left:auto;">
            <svg width="16" height="16" fill="none" stroke="#94a3b8" viewBox="0 0 24 24" style="position:absolute; left:12px; top:50%; transform:translateY(-50%); pointer-events:none;">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
            </svg>
            <input type="text" id="admin-log-search" placeholder="Buscar host, usuário ou IP..."
                style="padding:8px 14px 8px 36px; border:1px solid #cbd5e1; border-radius:10px; font-size:0.88rem; outline:none; min-width:240px; font-family:inherit;"
                onfocus="this.style.borderColor='#3b82f6'" onblur="this.style.borderColor='#cbd5e1'">
        </div>
    </div>

    <!-- Tabela -->
    <div style="background:#fff; border-radius:16px; border:1px solid #e2e8f0; overflow:hidden;">
        <div style="overflow-x:auto;">
            <table style="width:100%; border-collapse:collapse; font-size:0.88rem;" id="admin-logs-table">
                <thead>
                    <tr style="background:#f8fafc; border-bottom:2px solid #e2e8f0;">
                        <th style="padding:14px 20px; text-align:left; font-weight:700; color:#475569; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.5px;">Data/Hora</th>
                        <th style="padding:14px 20px; text-align:left; font-weight:700; color:#475569; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.5px;">Usuário</th>
                        <th style="padding:14px 20px; text-align:left; font-weight:700; color:#475569; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.5px;">Host / Label</th>
                        <th style="padding:14px 20px; text-align:center; font-weight:700; color:#475569; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.5px;">Status</th>
                        <th style="padding:14px 20px; text-align:right; font-weight:700; color:#475569; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.5px;">Latência</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($logs as $index => $l):
                    $isOff = $l['status'] === 'offline';
                    $lat   = $l['latency_ms'];
                    $rowBg = $isOff
                        ? 'background:#fff5f5; border-left:3px solid #ef4444;'
                        : ($index % 2 == 0 ? 'background:#fff; border-left:3px solid transparent;' : 'background:#fafafa; border-left:3px solid transparent;');

                    if ($lat === null) {
                        $latHtml = '<span style="color:#94a3b8; font-weight:600;">Timeout</span>';
                    } elseif ($lat > 200) {
                        $latHtml = '<span style="color:#dc2626; font-weight:700;">' . (int)$lat . '</span> <small style="color:#94a3b8;">ms</small>';
                    } elseif ($lat > 100) {
                        $latHtml = '<span style="color:#ca8a04; font-weight:700;">' . (int)$lat . '</span> <small style="color:#94a3b8;">ms</small>';
                    } else {
                        $latHtml = '<span style="color:#16a34a; font-weight:700;">' . (int)$lat . '</span> <small style="color:#94a3b8;">ms</small>';
                    }

                    $searchData = strtolower($l['host'] . ' ' . $l['label'] . ' ' . $l['user_email'] . ' ' . $l['user_name'] . ' ' . $l['status']);
                ?>
                <tr class="log-row-admin" data-status="<?php echo $l['status']; ?>" data-search="<?php echo h($searchData); ?>"
                    style="border-bottom:1px solid #f1f5f9; <?php echo $rowBg; ?>">
                    <td style="padding:12px 20px; color:#334155; font-family:monospace; font-size:0.85rem; white-space:nowrap;">
                        <?php echo h($l['checked_at']); ?>
                    </td>
                    <td style="padding:12px 20px;">
                        <div style="font-weight:600; color:#0f172a; font-size:0.88rem;"><?php echo h($l['user_name']); ?></div>
                        <div style="font-size:0.75rem; color:#94a3b8;"><?php echo h($l['user_email']); ?></div>
                    </td>
                    <td style="padding:12px 20px;">
                        <div style="font-weight:700; color:#0f172a;"><?php echo h($l['label']); ?></div>
                        <code style="font-size:0.78rem; color:#64748b; background:#f1f5f9; padding:2px 6px; border-radius:4px;"><?php echo h($l['host']); ?></code>
                    </td>
                    <td style="padding:12px 20px; text-align:center;">
                        <span style="display:inline-flex; align-items:center; gap:5px; font-size:0.75rem; font-weight:700; text-transform:uppercase; padding:4px 10px; border-radius:99px;
                            background:<?php echo $isOff ? '#fee2e2' : '#dcfce7'; ?>;
                            color:<?php echo $isOff ? '#dc2626' : '#16a34a'; ?>;">
                            <span <?php echo $isOff ? 'class="pulse-dot"' : ''; ?> style="width:5px; height:5px; border-radius:50%; background:currentColor; display:inline-block;"></span>
                            <?php echo $isOff ? 'OFFLINE' : 'ONLINE'; ?>
                        </span>
                    </td>
                    <td style="padding:12px 20px; text-align:right;">
                        <?php echo $latHtml; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if (empty($logs)): ?>
            <div style="text-align:center; padding:60px; color:#94a3b8;">
                <div style="font-size:2.5rem;">📋</div>
                <p style="font-weight:600; margin-top:12px;">Nenhum log registrado ainda.</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Legenda -->
    <div style="display:flex; align-items:center; gap:20px; flex-wrap:wrap;">
        <span style="font-size:0.78rem; color:#64748b; font-weight:600;">Legenda latência:</span>
        <span style="font-size:0.78rem; color:#16a34a; font-weight:700;">● Ótimo (&lt;100ms)</span>
        <span style="font-size:0.78rem; color:#ca8a04; font-weight:700;">● Médio (100–200ms)</span>
        <span style="font-size:0.78rem; color:#dc2626; font-weight:700;">● Alto (&gt;200ms)</span>
        <span style="font-size:0.78rem; color:#94a3b8; font-weight:700;">● Timeout</span>
    </div>

</div>

<script>
(function () {
    var currentFilter = 'all';
    var searchVal = '';

    var filterBtns = {
        all:     document.getElementById('af-all'),
        online:  document.getElementById('af-online'),
        offline: document.getElementById('af-offline'),
    };
    var searchBox = document.getElementById('admin-log-search');

    function applyFilters() {
        var rows = document.querySelectorAll('#admin-logs-table tbody tr[data-status]');
        rows.forEach(function (row) {
            var statusMatch = currentFilter === 'all' || row.dataset.status === currentFilter;
            var searchMatch = !searchVal || (row.dataset.search || '').includes(searchVal);
            row.style.display = (statusMatch && searchMatch) ? '' : 'none';
        });
        Object.keys(filterBtns).forEach(function (k) {
            var btn = filterBtns[k];
            if (!btn) return;
            btn.style.outline = k === currentFilter ? '2px solid #3b82f6' : 'none';
            btn.style.outlineOffset = '2px';
        });
    }

    window.adminFilter = function (type) {
        currentFilter = type;
        applyFilters();
    };

    if (searchBox) {
        searchBox.addEventListener('input', function () {
            searchVal = this.value.trim().toLowerCase();
            applyFilters();
        });
    }

    applyFilters();
})();
</script>

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