<?php
// Server-Sent Events stream for instant updates (status + gallery)
set_time_limit(0);
ignore_user_abort(true);

header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('X-Accel-Buffering: no');

function sse_send($event, $data) {
  echo "event: " . $event . "\n";
  echo "data: " . $data . "\n\n";
  @ob_flush();
  @flush();
}

function safe_json_read($path, $fallback) {
  if (!file_exists($path)) return $fallback;
  $raw = @file_get_contents($path);
  if ($raw === false) return $fallback;
  $trim = trim($raw);
  if ($trim === '') return $fallback;
  // validate json, but if invalid return fallback
  json_decode($trim, true);
  if (json_last_error() !== JSON_ERROR_NONE) return $fallback;
  return $trim;
}

$statusPath = __DIR__ . '/status.json';
$galleryPath = __DIR__ . '/gallery.json';

$lastStatusM = @filemtime($statusPath);
$lastGalleryM = @filemtime($galleryPath);

// initial push
sse_send('status', safe_json_read($statusPath, '{"status":"available","text":"Aktuálně přijímáme nové zakázky"}'));
sse_send('gallery', safe_json_read($galleryPath, '{"items":[]}'));

// keep alive + watch for changes (up to ~2 minutes; browser auto-reconnects)
$start = time();
while (time() - $start < 120) {
  clearstatcache();

  $sm = @filemtime($statusPath);
  if ($sm !== false && $sm !== $lastStatusM) {
    $lastStatusM = $sm;
    sse_send('status', safe_json_read($statusPath, '{"status":"available","text":"Aktuálně přijímáme nové zakázky"}'));
  }

  $gm = @filemtime($galleryPath);
  if ($gm !== false && $gm !== $lastGalleryM) {
    $lastGalleryM = $gm;
    sse_send('gallery', safe_json_read($galleryPath, '{"items":[]}'));
  }

  echo ": keep-alive\n\n";
  @ob_flush();
  @flush();
  usleep(800000); // 0.8s
}
