<?php
header('Content-Type: application/json');

// #36 Rate limiting: mínimo 5s entre chamadas por sessão
if (session_status() === PHP_SESSION_NONE) session_start();
$_lastApi = $_SESSION['api_dashboard_last'] ?? 0;
if (time() - $_lastApi < 5) {
    header('X-Cache: HIT');
    // Retorna cache existente se disponível
    $_cached = dash_cache_get('api_dash_rl_' . ($user['id'] ?? 0), 5);
    if ($_cached !== null) { echo json_encode($_cached); exit; }
}
$_SESSION['api_dashboard_last'] = time();
$pdo = db();

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

// Latência 24h — usa o mesmo cache do dashboard (TTL 30s)
// Se o cache existir, evita a query pesada sobre ping_logs
$_logStats = get_dash_log_stats($pdo, $user['id']);
$avgLat24  = $_logStats['avg_lat'];

// 2. Eventos recentes — mudanças de status das últimas 24h (via ping_logs + LAG)
$evStmt = $pdo->prepare("
    SELECT sub.status, sub.checked_at, sub.label
    FROM (
        SELECT pl.status, pl.checked_at, mi.label,
               LAG(pl.status) OVER (PARTITION BY pl.monitored_ip_id ORDER BY pl.checked_at ASC) AS prev_status
        FROM ping_logs pl
        JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
        WHERE mi.user_id = ?
          AND pl.checked_at >= NOW() - INTERVAL '1 day'
    ) sub
    WHERE sub.prev_status IS DISTINCT FROM sub.status
    ORDER BY sub.checked_at DESC
    LIMIT 10
");
$evStmt->execute([$user['id']]);
$incidentsRaw = $evStmt->fetchAll();

// Se não houve transições, mostra o último check de cada IP (status atual)
if (empty($incidentsRaw)) {
    $evStmt = $pdo->prepare("
        SELECT DISTINCT ON (pl.monitored_ip_id) pl.status, pl.checked_at, mi.label
        FROM ping_logs pl
        JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
        WHERE mi.user_id = ?
        ORDER BY pl.monitored_ip_id, pl.checked_at DESC
    ");
    $evStmt->execute([$user['id']]);
    $incidentsRaw = $evStmt->fetchAll();
}

$userTz    = new DateTimeZone($user['timezone'] ?? 'America/Sao_Paulo');
$incidents = [];
foreach ($incidentsRaw as $row) {
    try { $dt = (new DateTimeImmutable($row['checked_at']))->setTimezone($userTz); }
    catch (Throwable) { continue; }
    $color   = $row['status'] === 'online' ? 'green' : 'red';
    $message = $row['status'] === 'online'  ? 'voltou ONLINE' : 'ficou OFFLINE';
    $incidents[] = [
        'time'    => $dt->format('H:i'),
        'label'   => $row['label'],
        'color'   => $color,
        'message' => $message,
        'status'  => $row['status'],
    ];
}

// 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();

// #29 Histórico das barrinhas em UMA query (window function — sem N+1)
$historyByIp = [];
if (!empty($allIps)) {
    $ids = array_column($allIps, 'id');
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $histAllStmt = $pdo->prepare("
        SELECT sub.monitored_ip_id, sub.status
        FROM (
            SELECT pl.monitored_ip_id, pl.status, pl.checked_at,
                   ROW_NUMBER() OVER (PARTITION BY pl.monitored_ip_id ORDER BY pl.checked_at DESC) AS rn
            FROM ping_logs pl
            WHERE pl.monitored_ip_id IN ($placeholders)
              AND pl.checked_at >= NOW() - INTERVAL '7 days'
        ) sub
        WHERE sub.rn <= 15
        ORDER BY sub.monitored_ip_id, sub.checked_at ASC
    ");
    $histAllStmt->execute($ids);
    while ($row = $histAllStmt->fetch()) {
        $historyByIp[(int)$row['monitored_ip_id']][] = $row['status'];
    }
}

$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)
    ];
}

// Monta resposta e salva no cache do rate-limiter
$_response = [
    '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
];
dash_cache_set('api_dash_rl_' . $user['id'], $_response);
echo json_encode($_response);
exit;
