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

// anti cache (não é obrigatório aqui, mas ajuda em debug)
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

// DB central
$dbPath = __DIR__ . '/../../storage/devices_db.json';

// Onde salvar o ultimo status por MAC (simples)
$reportsDir = __DIR__ . '/../../storage/reports';
if (!is_dir($reportsDir)) {
  @mkdir($reportsDir, 0777, true);
}

function norm_mac($mac) {
  $mac = strtoupper(trim($mac));
  $mac = str_replace(["-", "."], ":", $mac);
  return $mac;
}

function load_db($path) {
  if (!file_exists($path)) return [];
  $db = json_decode(file_get_contents($path), true);
  return is_array($db) ? $db : [];
}

/**
 * Escrita atômica: escreve em .tmp e faz rename para o arquivo final.
 * Isso evita o dashboard ler JSON pela metade.
 */
function atomic_write_json($finalPath, $arr) {
  $tmp = $finalPath . ".tmp";
  $json = json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

  $fp = fopen($tmp, "wb");
  if (!$fp) return false;

  if (function_exists("flock")) @flock($fp, LOCK_EX);
  fwrite($fp, $json);
  fflush($fp);
  if (function_exists("fsync")) @fsync($fp);
  fclose($fp);

  return rename($tmp, $finalPath);
}

$body = file_get_contents('php://input');
$req = json_decode($body, true);

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

$project = $req["project"] ?? "";
$device  = $req["device"] ?? "";
$mac     = norm_mac($req["mac"] ?? "");
$token   = $req["token"] ?? "";

// Basico
if ($project !== "viso360" || $device !== "DIGILINK" || $mac === "" || $token === "") {
  http_response_code(400);
  echo json_encode(["ok" => false, "error" => "bad_request"]);
  exit;
}

// Valida MAC/token
$db = load_db($dbPath);
$rec = $db[$mac] ?? null;

if (!$rec || empty($rec["active"])) {
  http_response_code(403);
  echo json_encode(["ok" => false]);
  exit;
}

if (empty($rec["token"]) || $token !== $rec["token"]) {
  http_response_code(403);
  echo json_encode(["ok" => false]);
  exit;
}

// Salva ultimo payload por MAC
$safeMac = str_replace(":", "-", $mac);
$path = $reportsDir . "/" . $safeMac . ".json";

/**
 * server_counter: contador de quantos reports chegaram nesse MAC.
 * Prova o intervalo real, independente do dashboard.
 */
$counter = 0;
if (file_exists($path)) {
  $old = json_decode(@file_get_contents($path), true);
  if (is_array($old) && isset($old["server_counter"])) {
    $counter = (int)$old["server_counter"];
  }
}
$counter++;

// Monta saída
$out = [
  "mac" => $mac,
  "server_counter" => $counter,
  "server_time" => microtime(true),  // tempo real do servidor (segundos, com fração)
  "received_at" => gmdate("c"),
  "data" => $req
];

// Grava (ATÔMICO)
$ok = atomic_write_json($path, $out);
if (!$ok) {
  http_response_code(500);
  echo json_encode(["ok" => false, "error" => "write_failed"]);
  exit;
}

echo json_encode(["ok" => true, "server_counter" => $counter]);