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

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

$BASE = "https://updates.viso360.com.br/luiz";    // ajuste se mudar depois

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 : [];
}

function save_db($path, $db) {
  file_put_contents($path, json_encode($db, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function new_token() {
  return bin2hex(random_bytes(32)); // 64 chars
}

$body = file_get_contents('php://input');
$req = json_decode($body, true);
if (!is_array($req)) {
  http_response_code(400);
  echo json_encode(["allowed" => false, "error" => "invalid_json"]);
  exit;
}

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

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

$db = load_db($dbPath);
$rec = $db[$mac] ?? null;

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

$digilink_ver = trim($rec["digilink_ver"] ?? "");
$cld24_ver = trim($rec["cld24_ver"] ?? "");

$manifest = [];

if ($digilink_ver !== "") {
  $manifest["DIGILINK"] = [
    "version" => $digilink_ver,
    "url"     => $BASE . "/releases/DIGILINK/" . $digilink_ver . "/app.bin",
    "sha256"  => "TESTE_HASH"
  ];
}
if ($cld24_ver !== "") {
  $manifest["CLD24"] = [
    "version" => $cld24_ver,
    "url"     => $BASE . "/releases/CLD24/" . $cld24_ver . "/app.hex",
    "sha256"  => "TESTE_HASH"
  ];
}

// se não tem token salvo ainda, gera no 1º contato
if (empty($rec["token"])) {
  $rec["token"] = new_token();
  $rec["updated_at"] = gmdate("c");
  $db[$mac] = $rec;
  save_db($dbPath, $db);

  echo json_encode(["allowed" => true, "token" => $rec["token"], "manifest" => $manifest]);
  exit;
}

// já tem token: valida
if ($token_in === "" || $token_in !== $rec["token"]) {
  http_response_code(403);
  echo json_encode(["allowed" => false]);
  exit;
}

echo json_encode(["allowed" => true, "manifest" => $manifest]);
