<?php
define('DATA_DIR', __DIR__ . '/data');

function loadData($file) {
    $path = DATA_DIR . '/' . $file;
    if (!file_exists($path)) return [];
    $raw = file_get_contents($path);
    return json_decode($raw, true) ?: [];
}

function saveData($file, $data) {
    if (!is_dir(DATA_DIR)) mkdir(DATA_DIR, 0777, true);
    file_put_contents(DATA_DIR . '/' . $file, json_encode($data, JSON_PRETTY_PRINT));
}

function get_url_token($app_id, $real_url) {
    $settings = loadData('settings.json');
    $key = $settings['url_secret_key'] ?? '';
    if (empty($key)) {
        $key = bin2hex(random_bytes(32));
        $settings['url_secret_key'] = $key;
        saveData('settings.json', $settings);
    }
    $payload = json_encode(['id' => $app_id, 'url' => $real_url, 'ts' => time()]);
    $iv = random_bytes(16);
    $encrypted = openssl_encrypt($payload, 'aes-256-cbc', base64_decode($key), 0, $iv);
    return rtrim(strtr(base64_encode($iv . '::' . $encrypted), '+/', '-_'), '=');
}

echo "Menjalankan Unit Test Keamanan Penyamaran URL (URL Hiding)...\n\n";

$app_id = 'test-app-google';
$real_url = 'https://gemini.google.com/share/953a078caac9';
$token = get_url_token($app_id, $real_url);

echo "Target Asli: $real_url\n";
echo "Token Enkripsi (Fake URL payload): $token\n\n";

if (!empty($token)) {
    echo "[PASS] Enkripsi berhasil dilakukan.\n";
} else {
    echo "[FAIL] Enkripsi gagal.\n";
}

if (strpos($token, 'gemini.google.com') === false) {
    echo "[PASS] URL asli tidak bocor di dalam token (sepenuhnya tersamar).\n";
} else {
    echo "[FAIL] URL asli terlihat di dalam token.\n";
}

$settings = loadData('settings.json');
$key = $settings['url_secret_key'] ?? '';
$decoded = base64_decode(strtr($token, '-_', '+/'));
list($iv, $encrypted) = explode('::', $decoded, 2);
$decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', base64_decode($key), 0, $iv);
$payload = json_decode($decrypted, true);

if ($payload['url'] === $real_url && $payload['id'] === $app_id) {
    echo "[PASS] Proses dekripsi (simulasi go.php) berhasil divalidasi dengan aman.\n";
} else {
    echo "[FAIL] Dekripsi tidak sesuai.\n";
}

echo "\nSemua test selesai.\n";