<?php

// require './ZZ_prereq.php';
// Define the application path if not already set
if (!isset($apppath)) {
    $apppath = "/home/relayup/";
}

// Construct the full path to the VPN configuration file
$vpnConfigFile = $apppath . 'dev/vpn_config.cfg';

// Default content to be written to the VPN configuration file
$defaultContent = "RelayBandwidthRate 500 Mbits\nRelayBandwidthBurst 600 Mbits\nShutdownWaitLength 10\nMetricsPort 127.0.0.1:8080\nMetricsPortPolicy accept 127.0.0.1\nControlPort 9051\n";

// Check if the VPN configuration file exists and is not empty
if (!file_exists($vpnConfigFile) || filesize($vpnConfigFile) === 0) {
    // Attempt to open the file for writing, exit with an error message if unsuccessful
    
    $fileHandle = fopen($vpnConfigFile, "w") or die("Unable to open file: $vpnConfigFile");
    
    // Write the default content to the file
    fwrite($fileHandle, $defaultContent);
    
    // Close the file handle
    fclose($fileHandle);
    
    // Set the file permissions, exit with an error message if unsuccessful
    chmod($vpnConfigFile, 0644) or die("Unable to set file permissions for $vpnConfigFile");
}

// Regardless of whether the file was just created or already existed, read it
$configLines = file($vpnConfigFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$TEMPfilePath = "./temp_vpn_config.cfg";

if (file_exists($TEMPfilePath)) {
    $configLines = file($TEMPfilePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}
// } else {
//     $contents = file_get_contents($vpnConfigFile);
//     if ($contents === false) {
//         die("Error reading from $vpnConfigFile");
//     }
    
//     // Write the contents to temp_vpn_config.cfg
//     $result = file_put_contents($TEMPfilePath, $contents);
//     if ($result === false) {
//         die("Error writing to $TEMPfilePath");
//     } else {
//         echo "Contents of $TEMPfilePath have been replaced successfully.";
//     }

//     $configLines = file($TEMPfilePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// }

// Check if the file was read successfully
if ($configLines !== false) {
    // Variables to store the config values
    $accountingMax = "";
    $accountingStart = "";
    $relayBandwidthRate = "";
    $nickname = "";
    $address = "";
    $contactInfo = "";
    $MyFamily = [];
    $accountingEnabled = "disable"; // Initialize as disabled
    $checkCountry = "";

    // Loop through each line of the file
    foreach ($configLines as $line) {
        // Split the line into key and value by the first space
        list($key, $value) = preg_split('/\s+/', $line, 2);

        // Process the line based on the key
        switch (strtolower($key)) {
            case "accountingmax":
                preg_match('/\d+/', $value, $matches);
                $accountingMax = $matches[0] ?? $value;
                $accountingEnabled = "enable"; // Enable accounting if this key is found
                break;
            case "accountingstart":
                if (preg_match('/AccountingStart\s+(month|day|week)/', $line, $matches)) {
                    $accountingStart = $matches[1];
                }
                break;
            case "relaybandwidthrate":
                preg_match('/\d+/', $value, $matches);
                $relayBandwidthRate = $matches[0] ?? $value;
                break;
            case "nickname":
                $nickname = $value;
                break;
            case "contactinfo":
                $contactInfo = $value;
                break;
            case "myfamily":
                $MyFamily = array_map('trim', explode(',', $value));
                break;
            case "entrynodes":
                // Extract country code from between curly braces
                if (preg_match('/\{(\w+)\}/', $value, $matches)) {
                    $checkCountry = $matches[1];
                }
                break;
        }
    }
} else {
    echo "Failed to read the file: $vpnConfigFile";
}

// Read DID information from JSON file
$didFilePath = "../peaq/device_did.json";
$didName = "";
$didId = "";

if (file_exists($didFilePath)) {
    try {
        $didJson = file_get_contents($didFilePath);
        $didData = json_decode($didJson, true);
        
        if ($didData !== null) {
            $didName = $didData['name'] ?? '';
            $didId = $didData['id'] ?? '';
            // Log successful read
            error_log("DID Document loaded: " . $didId);
            error_log("DID Name loaded: " . $didName);
        } else {
            error_log("Error decoding JSON from device_did.json");
        }
    } catch (Exception $e) {
        error_log("Error reading device_did.json: " . $e->getMessage());
    }
} else {
    error_log("device_did.json file not found at: " . $didFilePath);
}

?>