<?php
session_start();
header('Content-Type: application/json; charset=UTF-8');
error_reporting(0);

$db = new SQLite3(__DIR__ . '/.db.db');

/* 🔹 DEFAULT BASE URL (VERY IMPORTANT) */
$base_url = 'https://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);

/* 🔹 CLEAN BASE URL */
$base_url = rtrim($base_url, '/');

/* ---------------- DNS LIST ---------------- */

$json_response = [];

/* ✅ FIRST ITEM MUST HAVE VALID URL */
$json_response[] = [
    "namex" => "Direct Login",
    "urlx"  => $base_url
];

/* REAL DNS ENTRIES */
$res = $db->query('SELECT name, url FROM dns');
while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
    if (!empty($row['url'])) {
        $json_response[] = [
            "namex" => $row['name'],
            "urlx"  => rtrim($row['url'], '/')
        ];
    }
}

/* ---------------- PREMIUMIZE ---------------- */

$premiumize = [];
$res2 = $db->query('SELECT name, "key" FROM premium');
if ($res2) {
    while ($row2 = $res2->fetchArray(SQLITE3_ASSOC)) {
        $premiumize[] = [
            "name" => $row2['name'],
            "key"  => $row2['key']
        ];
    }
}

/* ---------------- ENCRYPT ---------------- */

function encr($data, $keyo, $keyt) {
    $key = $keyo . $keyt;
    $encrypted = openssl_encrypt(
        $data,
        'aes-256-cbc',
        $key,
        OPENSSL_RAW_DATA,
        'eS>f-A$Mtu21?>Hq'
    );
    return bin2hex($encrypted) . strrev($keyo);
}

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

$key = $_SESSION['random_key'];

$final = json_encode([
    "dns" => $json_response,
    "premiumize" => $premiumize
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

$encrypted = encr($final, $key, $key);

echo json_encode([
    "amdi7minus" => strrev($encrypted)
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

session_destroy();
