<?php
include(__DIR__ . '/../includes/functions.php');

// Fetch DNS entries from the database
$res = $db->select('dns', '*', '', '');

// Fetch the welcome message from the database
$mes = $db->select('welcome', '*', 'id = :id', '', [':id' => 1]);

// Initialize an array to hold the portals data
$rows = array();
foreach ($res as $index => $row) {
    $rows[] = array(
        "id" => $index + 1,
        "name" => $row['title'],
        "url" => $row['url']
    );
}

// Create the final JSON structure
$final = array(
    "portalsdns" => $rows,
    "intro_url" => "",
    "message_oneo" => $mes[0]['message_one'],
    "message_twoo" => $mes[0]['message_two'],
    "message_threeo" => $mes[0]['message_three']
);

function atbashCipher($input) {
    $output = '';
    for ($i = 0; $i < strlen($input); $i++) {
        $char = $input[$i];
        if (ctype_upper($char)) {
            // A = 65, Z = 90; Z - (char - A) = 155 - char
            $output .= chr(155 - ord($char));
        }
        // Check if the character is a lowercase letter
        else if (ctype_lower($char)) {
            // a = 97, z = 122; z - (char - a) = 219 - char
            $output .= chr(219 - ord($char));
        }
        // Check if the character is a digit
        else if (ctype_digit($char)) {
            // 0 = 48, 9 = 57; 9 - (char - 0) = 105 - char
            $output .= chr(105 - ord($char));
        } else {
            // Non-alphabet characters are added directly
            $output .= $char;
        }
    }

    return $output;
}

// Decrypt function is the same as the encryption function
function atbashDecipher($input) {
    return atbashCipher($input);
}

header('Content-type: application/json; charset=UTF-8');
$sulanga = json_encode($final, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

$one = (atbashCipher($sulanga));
$tow =base64_encode($one);
$three = (atbashCipher($tow));
echo $three;
?>
