<?php
// device_stream.php  (SSE)
$ADMIN_PASS = "1234";

$pass = $_GET["pass"] ?? "";
$mac  = $_GET["mac"] ?? "";

if ($pass !== $ADMIN_PASS) { http_response_code(401); exit; }
if ($mac === "") { http_response_code(400); exit; }

$reportsDir = __DIR__ . "/storage/reports";
$mac = strtoupper(trim($mac));
$reportFile = $reportsDir . "/" . str_replace(":", "-", $mac) . ".json";

// Headers SSE + anti-buffer + anti-cache
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");

// ajuda em vários setups
@ini_set("output_buffering", "off");
@ini_set("zlib.output_compression", 0);
@ini_set("implicit_flush", 1);
@set_time_limit(0);

// limpa buffers PHP
while (ob_get_level() > 0) { @ob_end_flush(); }
@ob_implicit_flush(true);

function sse_send($event, $dataArr) {
  echo "event: {$event}\n";
  echo "data: " . json_encode($dataArr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n";
  @flush();
}

$lastMtime = 0;

// manda um "hello" pra abrir rápido
sse_send("hello", ["ok"=>true, "mac"=>$mac]);

// loop: espera arquivo mudar e envia
while (true) {
  if (connection_aborted()) break;

  clearstatcache(true, $reportFile);

  if (file_exists($reportFile)) {
    $mtime = @filemtime($reportFile);
    if ($mtime && $mtime !== $lastMtime) {
      $lastMtime = $mtime;

      // tenta ler até JSON ficar válido (evita “meio arquivo”)
      $data = null;
      for ($i=0; $i<10; $i++) {
        $raw = @file_get_contents($reportFile);
        if ($raw !== false) {
          $tmp = json_decode($raw, true);
          if (is_array($tmp)) { $data = $tmp; break; }
        }
        usleep(20000); // 20ms
      }

      if ($data) {
        sse_send("report", [
          "mtime" => $lastMtime,
          "received_at" => $data["received_at"] ?? null,
          "fw" => $data["data"]["fw"] ?? null,
          "door" => $data["data"]["door"] ?? null
        ]);
      }
    }
  } else {
    // arquivo não existe ainda
    if ($lastMtime !== -1) {
      $lastMtime = -1;
      sse_send("report", ["exists"=>false]);
    }
  }

  usleep(150000); // 150ms (responsivo sem matar CPU)
}