<?php
/**
 * V4 Real-time: long-poll + SSE (XAMPP-friendly, no separate WebSocket server required).
 */
require_auth();
if (!function_exists('hv4_table_exists')) {
    json_ok([]);
}
$route = trim($_GET['r'] ?? '', '/');
$since = (int)($_GET['since'] ?? 0);
$user = current_user();

if ($route === 'realtime/stream') {
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('Connection: keep-alive');
    header('X-Accel-Buffering: no');
    @ini_set('output_buffering', 'off');
    @ini_set('zlib.output_compression', '0');
    $end = time() + 25;
    while (time() < $end) {
        $events = hv4_fetch_events($since, (int)$user['id']);
        foreach ($events as $ev) {
            echo "id: {$ev['id']}\n";
            echo 'data: ' . json_encode($ev, JSON_UNESCAPED_UNICODE) . "\n\n";
            $since = max($since, (int)$ev['id']);
        }
        if (empty($events)) echo ": keepalive\n\n";
        @ob_flush();
        @flush();
        sleep(2);
    }
    exit;
}

json_ok(hv4_fetch_events($since, (int)$user['id']));

function hv4_fetch_events(int $since, int $userId): array {
    if (!function_exists('hv4_table_exists') || !hv4_table_exists('system_events')) {
        return [];
    }
    $events = [];
    $stmt = db()->prepare('SELECT id, event_type, entity_type, entity_id, payload, created_at FROM system_events WHERE id > ? ORDER BY id ASC LIMIT 50');
    $stmt->execute([$since]);
    while ($row = $stmt->fetch()) {
        $row['payload'] = json_decode($row['payload'] ?? '{}', true);
        $events[] = $row;
    }
    if (hv4_table_exists('notification_inbox')) {
        $n = db()->prepare('SELECT id, title, body, category, link, created_at FROM notification_inbox WHERE user_id=? AND read_at IS NULL ORDER BY id DESC LIMIT 10');
        $n->execute([$userId]);
        foreach ($n->fetchAll() as $row) {
            $events[] = ['id' => 'n' . $row['id'], 'event_type' => 'notification', 'payload' => $row, 'created_at' => $row['created_at']];
        }
    }
    return $events;
}
