<?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;
}

// Clientes ativos não devem retornar à fila de captura.
$db_path = dirname(__DIR__) . '/a/.eggziedb.db';
$mac_normalizado = strtoupper($mac);
if (file_exists($db_path)) {
    $db_ativo = new SQLite3($db_path);
    $stmt_ativo = $db_ativo->prepare('SELECT 1 FROM ibo WHERE UPPER(TRIM(mac_address)) = :mac LIMIT 1');
    if ($stmt_ativo) {
        $stmt_ativo->bindValue(':mac', $mac_normalizado, SQLITE3_TEXT);
        if ($stmt_ativo->execute()->fetchArray(SQLITE3_NUM)) {
            $db_ativo->close();
            echo json_encode(['success' => true, 'status' => 'active', 'message' => 'MAC already belongs to an active client']);
            exit;
        }
    }
    $db_ativo->close();
}

// Create an associative array with the retrieved data
$data = array(
    'mac' => $mac_normalizado,
    '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']);
}
?>
