<?php
ini_set('display_errors', 1);
require_once(__DIR__ . '/../includes/functions.php');

// Define the table names
$tableNames = ['app_dns', 'app_image', 'api_key', 'app_announce', 'themes'];
$configurations = [];

// Fetch data from each table
foreach ($tableNames as $tableName) {
    $rows = $db->select($tableName);
    foreach ($rows as $row) {
        if (!isset($configurations[$tableName])) {
            $configurations[$tableName] = [];
        }
        $configurations[$tableName][] = $row; 
    }
}

$jsonFilePath = __DIR__ . '/config.json'; 

if (file_exists($jsonFilePath)) {
    $jsonString = file_get_contents($jsonFilePath);
    $configArray = json_decode($jsonString, true);
} else {
    $configArray = []; 
}

// Merge the fetched configurations into the config array
foreach ($configurations as $key => $value) {
    if (!empty($value)) {
        $configArray[$key] = $value;
    }
}

// Function to replace null values with empty strings
function replaceNullWithEmptyString($array) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $array[$key] = replaceNullWithEmptyString($value);
        } else {
            if (is_null($value)) {
                $array[$key] = '';
            }
        }
    }
    return $array;
}

// Apply the function to your configuration array
$configArray = replaceNullWithEmptyString($configArray);

// Step 1: Rename 'id' to 'dns_id' and place it at the top in 'app_dns' section
if (isset($configArray['app_dns'])) {
    foreach ($configArray['app_dns'] as &$dnsEntry) {
        if (isset($dnsEntry['id'])) {
            $dns_id = $dnsEntry['id'];
            unset($dnsEntry['id']);
            // Rebuild the array with 'dns_id' at the top
            $dnsEntry = array_merge(['dns_id' => $dns_id], $dnsEntry);
        }
    }
}

// Step 2: Remove 'id' field from 'themes' section and set 'theme_change' to 'true'
if (isset($configArray['themes'])) {
    // Since you want 'themes' to be an object, not an array, we'll extract the first element
    $themeEntry = $configArray['themes'][0]; // Get the first element

    // Remove 'id' field if it exists
    if (isset($themeEntry['id'])) {
        unset($themeEntry['id']);
    }

    // Set 'theme_change' to 'true'
    $themeEntry['theme_change'] = 'true';

    // Assign back to 'themes' as an associative array (object in JSON)
    $configArray['themes'] = $themeEntry;
}

// Encode the array to JSON
$jsonString = json_encode($configArray, JSON_PRETTY_PRINT);

// Base64 encode the JSON string four times
for ($i = 0; $i < 4; $i++) {
    $jsonString = base64_encode($jsonString);
}

echo $jsonString;
?>
