<?php
header('Content-Type: application/json; charset=utf-8');

/* anti cache forte */
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('X-Accel-Buffering: no');

$ADMIN_PASS = "1234";

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

if ($pass !== $ADMIN_PASS) {
    http_response_code(401);
    echo json_encode(["ok"=>false,"error"=>"401"]);
    exit;
}

if (!$mac) {
    http_response_code(400);
    echo json_encode(["ok"=>false,"error"=>"mac"]);
    exit;
}

$reportsDir = __DIR__ . "/storage/reports";

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

if (!file_exists($reportFile)) {
    echo json_encode([
        "ok" => true,
        "exists" => false
    ]);
    exit;
}

/* timestamp do arquivo */
$mtime = filemtime($reportFile);

/* tenta ler várias vezes caso esteja sendo escrito */
$data = null;

for ($i = 0; $i < 6; $i++) {

    clearstatcache(true, $reportFile);

    $raw = @file_get_contents($reportFile);

    if ($raw !== false) {

        $tmp = json_decode($raw, true);

        if (is_array($tmp)) {
            $data = $tmp;
            break;
        }
    }

    usleep(30000); // 30ms
}

if (!$data) {
    echo json_encode([
        "ok"=>false,
        "error"=>"json_incomplete"
    ]);
    exit;
}

echo json_encode([
    "ok" => true,
    "exists" => true,
    "mtime" => $mtime,
    "received_at" => $data["received_at"] ?? null,
    "fw"   => $data["data"]["fw"] ?? null,
    "door" => $data["data"]["door"] ?? null
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);