<?php
// Get the serial from query parameter
$serial = isset($_GET['serial']) ? trim($_GET['serial']) : '';

if (empty($serial)) {
    die("UNAUTHORIZED");
}

// Create Auth_devices directory if it doesn't exist
$authDir = __DIR__ . '/Auth_devices';
if (!is_dir($authDir)) {
    if (!mkdir($authDir, 0755, true)) {
        die("UNAUTHORIZED");
    }
}

// Path to devices.json file
$devicesFile = $authDir . '/devices.json';

// Check if devices.json exists
if (!file_exists($devicesFile)) {
    die("UNAUTHORIZED");
}

// Load existing devices
$jsonContent = file_get_contents($devicesFile);
if ($jsonContent === false) {
    die("UNAUTHORIZED");
}

$devices = json_decode($jsonContent, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    die("UNAUTHORIZED");
}

if (!is_array($devices)) {
    die("UNAUTHORIZED");
}

// Check if serial exists in devices.json
$isAuthorized = false;
foreach ($devices as $device) {
    if (isset($device['serial']) && trim($device['serial']) === $serial) {
        $isAuthorized = true;
        break;
    }
}

if ($isAuthorized) {
    echo "AUTHORIZED";
} else {
    echo "UNAUTHORIZED";
}
?>