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

// Filtro, busca e paginação
$filterStatus = in_array($_GET['status'] ?? '', ['online', 'offline']) ? $_GET['status'] : 'all';
$searchQ      = trim($_GET['q'] ?? '');
$currentPage  = max(1, (int)($_GET['p'] ?? 1));
$perPage      = 50;

// Totais globais (para contadores dos botões)
$cntRow = $pdo->query("SELECT COUNT(*) AS total, SUM(CASE WHEN pl.status='online' THEN 1 ELSE 0 END) AS online_ct
    FROM ping_logs pl
    JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
    JOIN users u ON u.id = mi.user_id")->fetch();
$totalAll     = (int)$cntRow['total'];
$totalOnline  = (int)$cntRow['online_ct'];
$totalOffline = $totalAll - $totalOnline;

// Condições da query filtrada
$where = [];
$params = [];
if ($filterStatus !== 'all') {
    $where[] = "pl.status = ?";
    $params[] = $filterStatus;
}
if ($searchQ !== '') {
    $where[] = "(mi.host LIKE ? OR mi.label LIKE ? OR u.email LIKE ? OR u.name LIKE ?)";
    $like = '%' . $searchQ . '%';
    $params = array_merge($params, [$like, $like, $like, $like]);
}
$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// Total filtrado para paginação
$filteredStmt = $pdo->prepare("SELECT COUNT(*) FROM ping_logs pl
    JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
    JOIN users u ON u.id = mi.user_id {$whereSQL}");
$filteredStmt->execute($params);
$filteredTotal = (int)$filteredStmt->fetchColumn();
$totalPages    = max(1, (int)ceil($filteredTotal / $perPage));
$currentPage   = min($currentPage, $totalPages);
$offset        = ($currentPage - 1) * $perPage;

// Logs da página
$stmt = $pdo->prepare("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
    {$whereSQL}
    ORDER BY pl.checked_at DESC LIMIT {$perPage} OFFSET {$offset}");
$stmt->execute($params);
$logs = $stmt->fetchAll();
?>

<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 $totalAll; ?></div>
                <div style="font-size:0.7rem; text-transform:uppercase; color:#64748b; letter-spacing:1px;">Total</div>
            </div>
        </div>
    </div>

    <!-- Filtros + Busca -->
    <?php $adminBase = 'index.php?page=admin_logs'; ?>
    <form method="get" action="index.php" style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
        <input type="hidden" name="page" value="admin_logs">
        <span style="font-size:0.85rem; font-weight:600; color:#64748b;">Filtrar:</span>
        <?php
        $adminFilters = [
            'all'     => ['label' => "Todos ({$totalAll})",        'border' => '#cbd5e1', 'bg' => '#fff',    'color' => '#475569'],
            'online'  => ['label' => "Online ({$totalOnline})",    'border' => '#bbf7d0', 'bg' => '#f0fdf4', 'color' => '#16a34a'],
            'offline' => ['label' => "Offline ({$totalOffline})",  'border' => '#fca5a5', 'bg' => '#fff5f5', 'color' => '#dc2626'],
        ];
        foreach ($adminFilters as $key => $f): ?>
            <a href="<?= h($adminBase . '&status=' . $key . '&q=' . urlencode($searchQ) . '&p=1') ?>"
               style="text-decoration:none; padding:6px 16px; border-radius:99px; border:1px solid <?= $f['border'] ?>; background:<?= $f['bg'] ?>; font-size:0.82rem; font-weight:700; color:<?= $f['color'] ?>; cursor:pointer;
               <?= $filterStatus === $key ? 'outline:2px solid #3b82f6; outline-offset:2px;' : '' ?>">
                <?= $f['label'] ?>
            </a>
        <?php endforeach; ?>

        <div style="position:relative; margin-left:auto; display:flex; gap:6px;">
            <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="hidden" name="status" value="<?= h($filterStatus) ?>">
            <input type="text" name="q" value="<?= h($searchQ) ?>" placeholder="Buscar host, usuário ou label..."
                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'">
            <button type="submit" style="padding:8px 16px; background:#3b82f6; color:#fff; border:none; border-radius:10px; font-size:0.88rem; font-weight:600; cursor:pointer;">Buscar</button>
            <?php if ($searchQ): ?>
                <a href="<?= h($adminBase . '&status=' . $filterStatus) ?>" style="padding:8px 12px; background:#f1f5f9; border:1px solid #e2e8f0; border-radius:10px; font-size:0.88rem; color:#64748b; text-decoration:none; display:flex; align-items:center;">✕</a>
            <?php endif; ?>
        </div>
        <?php if ($totalPages > 1): ?>
            <span style="width:100%; font-size:0.8rem; color:#94a3b8; font-weight:600;">
                Mostrando <?= $filteredTotal ?> registros — Página <?= $currentPage ?> de <?= $totalPages ?>
            </span>
        <?php endif; ?>
    </form>

    <!-- 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-size:1rem; font-weight:700;">Timeout</span>';
                    } elseif ($lat > 200) {
                        $latHtml = '<span style="color:#dc2626; font-size:1.15rem; font-weight:800;">' . (int)$lat . '</span> <span style="color:#94a3b8; font-size:0.88rem; font-weight:600;">ms</span>';
                    } elseif ($lat > 100) {
                        $latHtml = '<span style="color:#ca8a04; font-size:1.15rem; font-weight:800;">' . (int)$lat . '</span> <span style="color:#94a3b8; font-size:0.88rem; font-weight:600;">ms</span>';
                    } else {
                        $latHtml = '<span style="color:#16a34a; font-size:1.15rem; font-weight:800;">' . (int)$lat . '</span> <span style="color:#94a3b8; font-size:0.88rem; font-weight:600;">ms</span>';
                    }

                ?>
                <tr class="log-row-admin" data-status="<?php echo $l['status']; ?>"
                    style="border-bottom:1px solid #f1f5f9; <?php echo $rowBg; ?>">
                    <td style="padding:14px 20px; white-space:nowrap;">
                        <div style="font-family:monospace; font-size:1rem; font-weight:700; color:#0f172a;"><?php echo h(substr($l['checked_at'], 0, 10)); ?></div>
                        <div style="font-family:monospace; font-size:0.95rem; font-weight:600; color:#3b82f6; margin-top:2px;"><?php echo h(substr($l['checked_at'], 11, 8)); ?></div>
                    </td>
                    <td style="padding:14px 20px;">
                        <div style="font-weight:700; color:#0f172a; font-size:0.95rem;"><?php echo h($l['user_name']); ?></div>
                        <div style="font-size:0.8rem; color:#94a3b8; margin-top:2px;"><?php echo h($l['user_email']); ?></div>
                    </td>
                    <td style="padding:14px 20px;">
                        <div style="font-weight:700; color:#0f172a; font-size:0.95rem; margin-bottom:6px;"><?php echo h($l['label']); ?></div>
                        <code style="display:inline-block; font-size:0.95rem; font-weight:700; color:#ea580c; background:#fff7ed; padding:5px 10px; border-radius:8px; border:1.5px solid #fed7aa; letter-spacing:0.03em;"><?php echo h($l['host']); ?></code>
                    </td>
                    <td style="padding:14px 20px; text-align:center;">
                        <span style="display:inline-flex; align-items:center; gap:5px; font-size:0.82rem; font-weight:700; text-transform:uppercase; padding:6px 14px; border-radius:99px;
                            background:<?php echo $isOff ? '#fee2e2' : '#dcfce7'; ?>;
                            color:<?php echo $isOff ? '#dc2626' : '#16a34a'; ?>;">
                            <span <?php echo $isOff ? 'class="pulse-dot"' : ''; ?> style="width:7px; height:7px; border-radius:50%; background:currentColor; display:inline-block;"></span>
                            <?php echo $isOff ? 'OFFLINE' : 'ONLINE'; ?>
                        </span>
                    </td>
                    <td style="padding:14px 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>

    <!-- Paginação -->
    <?php if ($totalPages > 1): ?>
    <div style="display:flex; align-items:center; justify-content:center; gap:4px; margin-top:4px; flex-wrap:wrap;">
        <?php
        $pageBaseUrl = $adminBase . '&status=' . $filterStatus . '&q=' . urlencode($searchQ);
        if ($currentPage > 1): ?>
            <a href="<?= h($pageBaseUrl . '&p=' . ($currentPage - 1)) ?>" style="text-decoration:none; padding:7px 14px; border-radius:8px; border:1px solid #e2e8f0; background:#fff; color:#475569; font-size:0.85rem; font-weight:600;">← Anterior</a>
        <?php endif;
        $pStart = max(1, $currentPage - 2);
        $pEnd   = min($totalPages, $currentPage + 2);
        if ($pStart > 1): ?><span style="padding:0 4px; color:#94a3b8;">…</span><?php endif;
        for ($p = $pStart; $p <= $pEnd; $p++):
            $active = $p === $currentPage; ?>
            <a href="<?= h($pageBaseUrl . '&p=' . $p) ?>"
               style="text-decoration:none; padding:7px 13px; border-radius:8px; border:1px solid <?= $active ? '#3b82f6' : '#e2e8f0' ?>; background:<?= $active ? '#3b82f6' : '#fff' ?>; color:<?= $active ? '#fff' : '#475569' ?>; font-size:0.85rem; font-weight:700;"><?= $p ?></a>
        <?php endfor;
        if ($pEnd < $totalPages): ?><span style="padding:0 4px; color:#94a3b8;">…</span><?php endif;
        if ($currentPage < $totalPages): ?>
            <a href="<?= h($pageBaseUrl . '&p=' . ($currentPage + 1)) ?>" style="text-decoration:none; padding:7px 14px; border-radius:8px; border:1px solid #e2e8f0; background:#fff; color:#475569; font-size:0.85rem; font-weight:600;">Próxima →</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- 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>

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