<?php
require_once __DIR__ . '/../config/db_remote.php';

header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

@ini_set('output_buffering', 'off');
@ini_set('zlib.output_compression', 0);

$lastId = (int)($_GET['last_id'] ?? 0);

// Keep the stream open ~30s
$start = time();
while ((time() - $start) < 30) {
  $res = $mysqli->query("SELECT id, code, source_code, read_time FROM barcode_readings ORDER BY id DESC LIMIT 1");
  if ($res && ($row = $res->fetch_assoc())) {
    $id = (int)$row['id'];
    if ($id > $lastId) {
      $lastId = $id;
      echo "event: scan\n";
      echo "data: " . json_encode($row) . "\n\n";
      @ob_flush(); @flush();
    }
  }
  // heartbeat
  echo "event: ping\n";
  echo "data: {\"t\":".time().",\"last_id\":".$lastId."}\n\n";
  @ob_flush(); @flush();
  usleep(900000); // 0.9s
}
