<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/functions.php';
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
start_session();
$u = $_SESSION['user'] ?? null;
if (!$u) { http_response_code(401); echo "event: close\ndata: unauthorized\n\n"; exit; }
$uid = (int)$u['id'];
$lastId = (int)($_GET['last_id'] ?? 0);
for ($i=0; $i<5; $i++) {
  $stmt = $pdo->prepare("SELECT id, title, body, created_at FROM notifications WHERE user_id=? AND id>? ORDER BY id ASC");
  $stmt->execute([$uid, $lastId]);
  $rows = $stmt->fetchAll();
  foreach ($rows as $n) {
    $lastId = (int)$n['id'];
    $data = json_encode($n, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    echo "id: {$lastId}\n";
    echo "event: message\n";
    echo "data: {$data}\n\n";
  }
  @ob_flush(); @flush();
  sleep(1);
}
echo ":\n\n";
