<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$ipsListStmt = $pdo->prepare("SELECT id, label, host, last_status, last_latency_ms FROM monitored_ips WHERE user_id = ? ORDER BY last_status ASC, created_at DESC");
$ipsListStmt->execute([$user['id']]);
$ipsList = $ipsListStmt->fetchAll();

$ip = null;
if ($id) {
    $stmt = $pdo->prepare("SELECT * FROM monitored_ips WHERE id = ? AND user_id = ?");
    $stmt->execute([$id, $user['id']]);
    $ip = $stmt->fetch();
}

if (!$ip) {
$offlineCount = count(array_filter($ipsList, fn($i) => $i['last_status'] === 'offline'));
?>
<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; }
</style>

<div class="card" style="border:none; box-shadow:none; background:transparent; padding:0;">
    <div style="margin-bottom: 24px; display:flex; justify-content:space-between; align-items:flex-end; flex-wrap:wrap; gap:12px;">
        <div>
            <h2 style="font-size: 1.8rem; font-weight:800; color:#0f172a; margin:0 0 4px;">Inspeção de Conexão</h2>
            <p style="color:#64748b; margin:0;">Selecione uma extremidade mapeada para auditar o registro de atividades e latências (Data-Logs).</p>
        </div>
        <?php if ($offlineCount > 0): ?>
            <span style="display:inline-flex; align-items:center; gap:8px; background:#fef2f2; border:1px solid #fecaca; color:#dc2626; font-weight:700; font-size:0.85rem; padding:8px 16px; border-radius:99px;">
                <span class="pulse-dot" style="width:8px; height:8px; border-radius:50%; background:#ef4444; display:inline-block;"></span>
                <?php echo $offlineCount; ?> offline agora
            </span>
        <?php endif; ?>
    </div>

    <?php if (empty($ipsList)): ?>
        <div style="text-align:center; padding: 60px; background:#fff; border-radius:24px; border:1px dashed #cbd5e1;">
            <p style="font-size:1.1rem; color:#64748b; margin-bottom:16px;">Nenhum Host sendo mapeado no momento.</p>
            <a href="index.php?page=user_ip_form" class="primary-button">Adicionar meu primeiro IP</a>
        </div>
    <?php else: ?>
        <div style="display:grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; align-items: stretch;">
            <?php foreach ($ipsList as $item):
                $status   = $item['last_status'];
                $isOnline  = $status === 'online';
                $isOffline = $status === 'offline';

                // Badge
                $badgeBg    = $isOnline  ? '#dcfce7' : ($isOffline ? '#fee2e2' : '#f1f5f9');
                $badgeColor = $isOnline  ? '#16a34a' : ($isOffline ? '#dc2626' : '#64748b');

                // Card visual por status
                $cardBorder    = $isOnline  ? '1px solid #bbf7d0' : ($isOffline ? '1px solid #fca5a5' : '1px solid #e2e8f0');
                $cardBg        = $isOnline  ? '#f0fdf4'           : ($isOffline ? '#fff5f5'           : '#fff');
                $cardAccent    = $isOnline  ? '#22c55e'           : ($isOffline ? '#ef4444'           : '#94a3b8');
                $latencyText   = $item['last_latency_ms'] !== null ? (int)$item['last_latency_ms'] . ' ms' : '—';
                $latencyColor  = $item['last_latency_ms'] !== null && (int)$item['last_latency_ms'] > 200 ? '#ca8a04' : $badgeColor;
            ?>
                <a href="index.php?page=user_logs&id=<?php echo $item['id']; ?>" style="text-decoration:none; display:flex;">
                    <div style="display:flex; flex-direction:column; width:100%; background:<?php echo $cardBg; ?>; border-radius:16px; border:<?php echo $cardBorder; ?>; border-left:4px solid <?php echo $cardAccent; ?>; transition:all 0.2s cubic-bezier(0.4,0,0.2,1); box-shadow:0 4px 6px -1px rgba(0,0,0,0.05); overflow:hidden;"
                         onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='0 20px 25px -5px rgba(0,0,0,0.1)'"
                         onmouseout="this.style.transform='none'; this.style.boxShadow='0 4px 6px -1px rgba(0,0,0,0.05)'">

                        <!-- Corpo do card — cresce para igualar altura -->
                        <div style="flex:1; padding:20px 20px 16px;">
                            <!-- Nome + Badge -->
                            <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:12px;">
                                <h3 style="margin:0; font-size:1.2rem; font-weight:800; color:#0f172a; line-height:1.3; overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical;"><?php echo h($item['label']); ?></h3>
                                <span style="display:inline-flex; align-items:center; gap:5px; font-size:0.72rem; font-weight:700; text-transform:uppercase; padding:5px 10px; border-radius:99px; background:<?php echo $badgeBg; ?>; color:<?php echo $badgeColor; ?>; white-space:nowrap; flex-shrink:0; margin-left:10px;">
                                    <span <?php echo $isOffline ? 'class="pulse-dot"' : ''; ?> style="width:6px; height:6px; border-radius:50%; background:<?php echo $cardAccent; ?>; display:inline-block;"></span>
                                    <?php echo $status ? strtoupper($status) : 'UNKNOWN'; ?>
                                </span>
                            </div>

                            <!-- IP/Host em destaque laranja -->
                            <code style="display:block; font-size:1rem; font-weight:700; color:#ea580c; background:#fff7ed; padding:6px 10px; border-radius:8px; border:1.5px solid #fed7aa; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; letter-spacing:0.03em; margin-bottom:12px;"><?php echo h($item['host']); ?></code>

                            <!-- Latência -->
                            <div style="font-size:1rem; font-weight:700; color:#475569;">
                                Latência:
                                <strong style="font-size:1.05rem; color:<?php echo $latencyColor; ?>;"><?php echo $latencyText; ?></strong>
                            </div>
                        </div>

                        <!-- Rodapé fixo no fundo -->
                        <div style="padding:10px 20px; background:<?php echo $isOffline ? 'rgba(239,68,68,0.06)' : 'rgba(0,0,0,0.02)'; ?>; border-top:1px solid <?php echo $isOffline ? '#fca5a5' : '#e2e8f0'; ?>; display:flex; align-items:center; gap:8px; color:<?php echo $isOffline ? '#dc2626' : '#3b82f6'; ?>; font-weight:600; font-size:0.85rem;">
                            <?php echo $isOffline ? '⚠️ Ver histórico de quedas' : '🔎 Consultar DataLogs'; ?>
                            <span style="margin-left:auto;">&rarr;</span>
                        </div>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
<?php
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM ping_logs WHERE monitored_ip_id = ? ORDER BY checked_at DESC LIMIT 500");
$stmt->execute([$ip['id']]);
$logs = $stmt->fetchAll();

$onlineChecks = array_filter($logs, fn($l) => $l['status'] === 'online');
$uptime24h = count($logs) > 0 ? round((count($onlineChecks) / count($logs)) * 100, 1) : 0;
$offlineLogs = count($logs) - count($onlineChecks);
?>

<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 { transition: background 0.15s; }
.log-row:hover { background: #f0f9ff !important; }
</style>

<div>
    <div style="display:flex; justify-content:space-between; align-items:flex-end; margin-bottom:24px; flex-wrap:wrap; gap:16px;">
        <div>
            <a href="index.php?page=user_logs" style="display:inline-flex; align-items:center; gap:6px; margin-bottom:12px; color:#64748b; font-size:0.9rem; font-weight:600;">&larr; Voltar para Máquinas</a>
            <h2 style="font-size: 1.8rem; font-weight:800; color:#0f172a; margin:0 0 6px;">
                Logs: <span style="color:#3b82f6;"><?php echo h($ip['label']); ?></span>
            </h2>
            <code style="display:inline-block; color:#ea580c; font-size:1.1rem; font-weight:700; background:#fff7ed; padding:6px 14px; border-radius:8px; border:1.5px solid #fed7aa; letter-spacing:0.04em;"><?php echo h($ip['host']); ?></code>
        </div>
        <div style="display:flex; gap:16px; flex-wrap:wrap; align-items:flex-end;">
            <div style="text-align:right;">
                <small style="color:#64748b; font-weight:600; text-transform:uppercase; font-size:0.75rem; letter-spacing:0.05em;">Saúde Estimada</small>
                <div style="font-size:1.6rem; font-weight:800; color:<?php echo $uptime24h > 98 ? '#16a34a' : ($uptime24h > 90 ? '#ca8a04' : '#dc2626'); ?>;"><?php echo $uptime24h; ?>%</div>
            </div>
            <div style="border-left:1px solid #cbd5e1; padding-left:16px; text-align:right;">
                <small style="color:#64748b; font-weight:600; text-transform:uppercase; font-size:0.75rem; letter-spacing:0.05em;">Registros</small>
                <div style="font-size:1.6rem; font-weight:800; color:#0f172a;"><?php echo count($logs); ?></div>
            </div>
            <?php if ($offlineLogs > 0): ?>
            <div style="border-left:1px solid #cbd5e1; padding-left:16px; text-align:right;">
                <small style="color:#64748b; font-weight:600; text-transform:uppercase; font-size:0.75rem; letter-spacing:0.05em;">Quedas</small>
                <div style="font-size:1.6rem; font-weight:800; color:#dc2626;"><?php echo $offlineLogs; ?></div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Filtros -->
    <div style="display:flex; align-items:center; gap:8px; margin-bottom:16px; flex-wrap:wrap;">
        <span style="font-size:0.85rem; font-weight:600; color:#64748b;">Filtrar:</span>
        <button onclick="filterLogs('all')"    id="filter-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; transition:0.15s;">Todos (<?php echo count($logs); ?>)</button>
        <button onclick="filterLogs('online')"  id="filter-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; transition:0.15s;">Online (<?php echo count($onlineChecks); ?>)</button>
        <button onclick="filterLogs('offline')" id="filter-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; transition:0.15s;">Offline (<?php echo $offlineLogs; ?>)</button>
    </div>

    <div class="card" style="padding:0; overflow:hidden;">
        <table style="width:100%; border-collapse:collapse; text-align:left;" id="logs-table">
            <thead>
                <tr style="background:#f8fafc; border-bottom:2px solid #e2e8f0;">
                    <th style="padding:14px 24px; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; letter-spacing:0.05em;">#</th>
                    <th style="padding:14px 24px; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; letter-spacing:0.05em;">Timestamp / Data Exata</th>
                    <th style="padding:14px 24px; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; letter-spacing:0.05em;">Status de Conexão</th>
                    <th style="padding:14px 24px; font-weight:700; color:#475569; font-size:0.8rem; text-transform:uppercase; letter-spacing:0.05em; text-align:right;">Performance (Latência)</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($logs)): ?>
                <tr><td colspan="4" style="text-align:center; padding:40px; color:#94a3b8;">Nenhum registro encontrado ainda. Aguarde o primeiro Cron.</td></tr>
            <?php else: ?>
                <?php foreach ($logs as $index => $log):
                    $isOfflineRow = $log['status'] === 'offline';
                    $lat = $log['latency_ms'];

                    // Cor de fundo da linha
                    if ($isOfflineRow) {
                        $rowBg = 'background:#fff5f5;';
                        $rowBorderLeft = 'border-left:3px solid #ef4444;';
                    } else {
                        $rowBg = $index % 2 == 0 ? 'background:#fff;' : 'background:#fafafa;';
                        $rowBorderLeft = 'border-left:3px solid transparent;';
                    }

                    // Cor da latência por faixa
                    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>';
                    }
                ?>
                <tr class="log-row" data-status="<?php echo $log['status']; ?>"
                    style="border-bottom:1px solid #f1f5f9; <?php echo $rowBg . $rowBorderLeft; ?>">
                    <td style="padding:12px 24px; color:#94a3b8; font-size:0.8rem; font-family:monospace;"><?php echo count($logs) - $index; ?></td>
                    <td style="padding:12px 24px; color:#334155; font-family:monospace; font-size:0.9rem;">
                        <?php echo h($log['checked_at']); ?>
                    </td>
                    <td style="padding:12px 24px;">
                        <span style="display:inline-flex; align-items:center; gap:6px; font-size:0.78rem; font-weight:700; text-transform:uppercase; padding:4px 10px; border-radius:99px;
                            background:<?php echo $isOfflineRow ? '#fee2e2' : '#dcfce7'; ?>;
                            color:<?php echo $isOfflineRow ? '#dc2626' : '#16a34a'; ?>;">
                            <span <?php echo $isOfflineRow ? 'class="pulse-dot"' : ''; ?> style="display:block; width:6px; height:6px; border-radius:50%; background:currentColor;"></span>
                            <?php echo $isOfflineRow ? 'OFFLINE' : 'ONLINE'; ?>
                        </span>
                    </td>
                    <td style="padding:12px 24px; text-align:right;">
                        <?php echo $latHtml; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Legenda de cores de latência -->
    <div style="display:flex; align-items:center; gap:20px; margin-top:12px; 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 activeFilter = 'all';
    var filterBtns = {
        all:     document.getElementById('filter-all'),
        online:  document.getElementById('filter-online'),
        offline: document.getElementById('filter-offline'),
    };

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

    filterLogs('all');
    window.filterLogs = filterLogs;
})();
</script>

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