<?php
// Retrieve the data from the GET request with validation
$mac = isset($_GET['mac']) ? trim($_GET['mac']) : '';
$devID = isset($_GET['devID']) ? trim($_GET['devID']) : '';
$deviceName = isset($_GET['deviceName']) ? trim($_GET['deviceName']) : '';

// Validate that at least MAC is provided
if (empty($mac)) {
    http_response_code(400);
    echo json_encode(['error' => 'MAC address is required']);
    exit;
}

// Create an associative array with the retrieved data
$data = array(
    'mac' => strtoupper($mac),
    'devID' => $devID,
    'deviceName' => $deviceName,
    'timestamp' => date('Y-m-d H:i:s')
);

// Define the path and filename for the JSON file
$filename = '../a/rtx/request.json';

// Ensure the directory exists
$dir = dirname($filename);
if (!is_dir($dir)) {
    mkdir($dir, 0777, true);
}

// Check if the JSON file exists
if (file_exists($filename)) {
    // Read the existing JSON data from the file
    $jsonData = file_get_contents($filename);
    
    // Decode the JSON data into an associative array
    $existingData = json_decode($jsonData, true);
    
    // Validate JSON decode
    if (!is_array($existingData)) {
        $existingData = [];
    }
    
    // Add the new record to the existing data
    $existingData[] = $data;
    
    // Convert the updated data back to JSON format
    $jsonData = json_encode($existingData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} else {
    // If the file doesn't exist, create a new JSON array
    $jsonData = json_encode([$data], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}

// Save the JSON data to the file
if (file_put_contents($filename, $jsonData)) {
    http_response_code(200);
    echo json_encode(['success' => true, 'message' => 'Data saved successfully']);
} else {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to save data']);
}
?>
