<?php
// register_serial.php
// Simple script to register serial numbers

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

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

// Initialize devices array
$devices = [];

// Load existing devices if file exists
if (file_exists($devicesFile)) {
    $jsonContent = file_get_contents($devicesFile);
    if ($jsonContent !== false) {
        $devices = json_decode($jsonContent, true) ?: [];
    }
}

// Check if serial was provided via GET
if (isset($_GET['serial'])) {
    $serial = trim($_GET['serial']);
    
    if (empty($serial)) {
        echo "Error: Please enter a serial number";
    } else {
        // Check if serial already exists
        $serialExists = false;
        foreach ($devices as $device) {
            if (isset($device['serial']) && $device['serial'] === $serial) {
                $serialExists = true;
                break;
            }
        }
        
        if ($serialExists) {
            echo "Error: Serial number '$serial' is already registered";
        } else {
            // Add new serial with timestamp
            $newDevice = [
                'serial' => $serial,
                'registered_at' => date('Y-m-d H:i:s'),
                'id' => uniqid()
            ];
            
            $devices[] = $newDevice;
            
            // Save to file
            if (file_put_contents($devicesFile, json_encode($devices, JSON_PRETTY_PRINT))) {
                echo "Success: Serial number '$serial' has been registered successfully!";
            } else {
                echo "Error: Could not save serial number";
            }
        }
    }
} else {
    echo "Error: No serial number provided";
}
?>