<?php
header('Content-Type: application/json');
$pdo = db();

// 1. Resumo (Cards Superiores)
$summaryStmt = $pdo->prepare("
    SELECT 
        COUNT(*) AS total_ips,
        SUM(CASE WHEN last_status='online' AND active=1 THEN 1 ELSE 0 END) AS online_ips,
        SUM(CASE WHEN last_status='offline' AND active=1 THEN 1 ELSE 0 END) AS offline_ips
    FROM monitored_ips
    WHERE user_id = ?
");
$summaryStmt->execute([$user['id']]);
$summary = $summaryStmt->fetch() ?: [];

$latencyStmt = $pdo->prepare("
    SELECT AVG(pl.latency_ms) 
    FROM ping_logs pl
    JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
    WHERE mi.user_id = ? AND mi.active=1 AND pl.checked_at >= (NOW() - INTERVAL 1 DAY)
");
$latencyStmt->execute([$user['id']]);
$avgLatRaw = $latencyStmt->fetchColumn();
$avgLat24 = $avgLatRaw !== null ? round((float)$avgLatRaw, 1) : null;

// 2. Incidentes Recentes (Timeline de Alertas/Erros das últimas 24hs)
$incidentsStmt = $pdo->prepare("
    SELECT a.sent_at, a.status, a.message, mi.label
    FROM alerts_sent a
    JOIN monitored_ips mi ON mi.id = a.monitored_ip_id
    WHERE mi.user_id = ? AND a.sent_at >= (NOW() - INTERVAL 1 DAY)
    ORDER BY a.sent_at DESC
    LIMIT 4
");
$incidentsStmt->execute([$user['id']]);
$incidentsRaw = $incidentsStmt->fetchAll();

$incidents = [];
foreach ($incidentsRaw as $row) {
    // Formatar hora
    $time = (new DateTime($row['sent_at']))->format('H:i');
    $color = ($row['status'] === 'failed' || stripos($row['message'], 'offline') !== false) ? 'red' : 'green';
    $incidents[] = [
        'time' => $time,
        'label' => $row['label'],
        'color' => $color,
        'message' => 'Mudou para ' . ($color==='red'?'OFFLINE':'ONLINE')
    ];
}

// 3. Status individual de cada IP e seus dados (incluindo Hitórico visual das últimas 15 execuções)
$ipsStmt = $pdo->prepare("SELECT id, label, host, last_status, last_latency_ms, last_check_at, interval_seconds, active FROM monitored_ips WHERE user_id = ? ORDER BY created_at DESC");
$ipsStmt->execute([$user['id']]);
$allIps = $ipsStmt->fetchAll();

// Histórico para a barra (Health Bar)
$historyByIp = [];
if (!empty($allIps)) {
    $ids = array_column($allIps, 'id');
    $histStmt = $pdo->prepare("SELECT status FROM ping_logs WHERE monitored_ip_id = ? ORDER BY checked_at DESC LIMIT 15");
    foreach ($ids as $ipId) {
        $histStmt->execute([$ipId]);
        $historyByIp[$ipId] = array_reverse($histStmt->fetchAll(PDO::FETCH_COLUMN));
    }
}

$ipsData = [];
$dbTz = new DateTimeZone('UTC');
$now = new DateTimeImmutable('now', $dbTz);

foreach ($allIps as $ip) {
    if (empty($ip['last_check_at'])) {
        $nextText = 'Próximo: agora';
    } else {
        try {
            $last = new DateTimeImmutable($ip['last_check_at'], $dbTz);
            $next = $last->modify('+' . (int)$ip['interval_seconds'] . ' seconds');
            $diff = $next->getTimestamp() - $now->getTimestamp();
            if ($diff <= 0) $nextText = 'Próximo: agora';
            elseif ($diff < 60) $nextText = "Próximo: em {$diff}s";
            else $nextText = 'Próximo: em ' . floor($diff / 60) . 'min';
        } catch (Exception $e) { $nextText = 'Próximo: --'; }
    }
    
    // Calcula histórico de barrinhas de cor
    $barHTML = '';
    if (!empty($historyByIp[$ip['id']])) {
        foreach ($historyByIp[$ip['id']] as $histStatus) {
            $bg = $histStatus === 'online' ? '#22c55e' : '#ef4444';
            $barHTML .= "<span style='display:inline-block;width:6px;height:12px;border-radius:2px;margin-right:2px;background:{$bg};opacity:0.8;'></span>";
        }
    } else {
        $barHTML = "<small style='color:#94a3b8;'>Sem histórico</small>";
    }

    $ipsData[] = [
        'id' => $ip['id'],
        'status' => $ip['last_status'] ?: 'unknown',
        'active' => (int)$ip['active'],
        'latency' => $ip['last_latency_ms'] !== null ? $ip['last_latency_ms'] . ' ms' : 'N/A',
        'next_check' => $nextText,
        'history_html' => $barHTML,
        'risk' => ($ip['last_latency_ms'] !== null && (int)$ip['last_latency_ms'] >= 200)
    ];
}

// Emite JSON
echo json_encode([
    'summary' => [
        'total' => (int)$summary['total_ips'],
        'online' => (int)$summary['online_ips'],
        'offline' => (int)$summary['offline_ips'],
        'lat24' => $avgLat24 !== null ? $avgLat24 . ' ms' : '—',
    ],
    'incidents' => $incidents,
    'ips' => $ipsData
]);
exit;
