<?php
session_start();
error_reporting(0);
$db = new SQLite3('./.db.db');
$res = $db->query('SELECT * FROM dns'); 
$rows = array();
$rowsn = array();
$json_response = array(); 

$current_protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$current_domain = $_SERVER['HTTP_HOST'];
$current_directory = dirname($_SERVER['REQUEST_URI']);
$current_url = $current_protocol . $current_domain . $current_directory;


$default_item = array(
    'name' => 'Default user',
    'url' => $current_url
);

array_push($json_response, $default_item);

while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
	$row_array['name'] = $row['title']; 
	$row_array['url'] = $row['url']; 
	array_push($json_response,$row_array);  
}



function encr($data,$keyo,$keyt) {
        $key = $keyo.$keyt;
        $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, 'R4tghjg^425(@#Gg');
        $encrypted_hex = bin2hex($encrypted);
		$reversed_text = strrev($keyo);
        return $encrypted_hex.$reversed_text;
}

function generateRandomKeyfirst() {
    if (!isset($_SESSION['random_key'])) {
        $_SESSION['random_key'] = substr(bin2hex(random_bytes(16)), 0, 16);
    }
    return substr($_SESSION['random_key'], 0, 16);
}

function getkey(){
	$db = new SQLite3('./.db.db');
	$result = $db->query('SELECT * FROM pkey');
	$rows = array();
	while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    	$rows[] = $row;
	}
	$randomIndex = rand(0, count($rows) - 1);
	$randomRow = $rows[$randomIndex];
	$randomKeyValue = $randomRow['key'];

	if ($randomKeyValue == null){
		return "null";
    }else{
		return $randomKeyValue;
    }

}

$mykeyone = generateRandomKeyfirst();

$final = json_encode($json_response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$output_json = '{"portals":' . $final . ',"pkey":"'.getkey().'"}';
$mainencrypt = encr($output_json,$mykeyone,$mykeyone);
$addkeys = $mainencrypt;

header('Content-type: application/json; charset=UTF-8');
echo $addkeys;
session_destroy();
?>