<?php
// Force session cookie path = '/' to stay consistent with index.php
if (session_status() === PHP_SESSION_NONE) {
    $cp = session_get_cookie_params();
    session_set_cookie_params([
        'lifetime' => $cp['lifetime'] ?? 0,
        'path'     => '/',
        'domain'   => $cp['domain'] ?? '',
        'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
    session_name('PHPSESSID');
    session_start();
}

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 logActivity($action, $details) {
    $logs = loadData('url_logs.json');
    $logs[] = [
        'ts' => date('Y-m-d H:i:s'),
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN',
        'ua' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'action' => $action,
        'details' => $details
    ];
    if (count($logs) > 5000) $logs = array_slice($logs, -5000);
    saveData('url_logs.json', $logs);
}

function get_url_slug($name) {
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name), '-'));
    return empty($slug) ? 'app' : $slug;
}

// Support both ?token= for backward compatibility and /slug for clean URLs
$token = $_GET['token'] ?? '';
$path_info = $_SERVER['PATH_INFO'] ?? '';
$slug = trim($path_info, '/');

// Authenticate via token if session is empty
if (!empty($token)) {
    $_SESSION['texa_user_code'] = $token;
    // Set cookie untuk fallback
    setcookie('texa_user_code', $token, time() + 86400, '/');
}

// Fallback ambil dari cookie
if (empty($_SESSION['texa_user_code']) && !empty($_COOKIE['texa_user_code'])) {
    $_SESSION['texa_user_code'] = $_COOKIE['texa_user_code'];
}

// Check if accessed from extension/remote app via session
if (empty($_SESSION['texa_user_code'])) {
    logActivity('BLOCK_DIRECT_ACCESS', 'Direct access without extension session');
    die('
    <!DOCTYPE html>
    <html lang="id">
    <head><title>Akses Ditolak</title><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
    <body style="margin:0;padding:0;overflow:hidden;background-color:#010814;color:white;font-family:\'Inter\',system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;width:100vw;">
        <div style="background:rgba(255,107,107,0.1);border:1px solid rgba(255,107,107,0.3);padding:30px 40px;border-radius:20px;text-align:center;box-shadow:0 20px 50px rgba(0,0,0,0.5);">
            <svg viewBox="0 0 24 24" fill="none" stroke="#ff4d4d" stroke-width="2" width="60" height="60" style="margin-bottom:20px;">
            <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
            </svg>
            <h2 style="color:#ff4d4d;margin:0 0 10px 0;font-size:24px;">Akses Ditolak</h2>
            <p style="margin:0 0 20px 0;color:#c0c0c0;line-height:1.5;">Aplikasi ini dilindungi dan hanya dapat dibuka<br>melalui <b style="color:#00d4ff;font-weight:900;text-shadow:0 0 10px rgba(0,212,255,0.5);">TEKNO APPS</b>.</p>
        </div>
    </body>
    </html>
    ');
}

$targetUrl = '';
$appId = 'unknown';
$appName = 'Aplikasi TEXA';

if (!empty($slug)) {
    // Look up by slug in applications.json
    $apps = loadData('applications.json');
    $found = false;
    
    foreach ($apps as $a) {
        if (!empty($a['hide_url'])) {
            if (get_url_slug($a['name']) === $slug) {
                $targetUrl = $a['default_url'];
                $appId = $a['id'];
                $appName = $a['name'];
                $found = true;
                break;
            }
            if (!empty($a['custom_servers'])) {
                foreach ($a['custom_servers'] as $cs) {
                    if (get_url_slug($cs['name']) === $slug) {
                        $targetUrl = $cs['url'];
                        $appId = $a['id'];
                        $appName = $cs['name'];
                        $found = true;
                        break 2;
                    }
                }
            }
        }
    }
    
    // Gunakan URL persis yang di-fetch dari sesi jika ada (mencakup override dari cookies.json)
    if ($found) {
        if (!empty($_SESSION['texa_target_url_' . $slug])) {
            $targetUrl = $_SESSION['texa_target_url_' . $slug];
        } elseif (!empty($_COOKIE['texa_target_url_' . $slug])) {
            $targetUrl = $_COOKIE['texa_target_url_' . $slug];
        }
    }
    
    if (!$found) {
        logActivity('BLOCK_SLUG_NOT_FOUND', "Slug not found: $slug");
        die('
        <!DOCTYPE html>
        <html lang="id">
        <head><title>Akses Ditolak</title><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
        <body style="margin:0;padding:0;overflow:hidden;background-color:#010814;color:white;font-family:\'Inter\',system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;width:100vw;">
            <div style="background:rgba(255,107,107,0.1);border:1px solid rgba(255,107,107,0.3);padding:30px 40px;border-radius:20px;text-align:center;box-shadow:0 20px 50px rgba(0,0,0,0.5);">
                <svg viewBox="0 0 24 24" fill="none" stroke="#ff4d4d" stroke-width="2" width="60" height="60" style="margin-bottom:20px;">
                <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
                </svg>
                <h2 style="color:#ff4d4d;margin:0 0 10px 0;font-size:24px;">Akses Ditolak</h2>
                <p style="margin:0 0 20px 0;color:#c0c0c0;line-height:1.5;">Aplikasi atau Server tidak ditemukan.</p>
            </div>
        </body>
        </html>
        ');
    }
} elseif (!empty($token)) {
    // Legacy token decryption
    $settings = loadData('settings.json');
    $key = $settings['url_secret_key'] ?? '';
    if (empty($key)) {
        logActivity('BLOCK_NO_KEY', 'Secret key not found in settings');
        die('<h1>Akses Ditolak</h1><p>Konfigurasi server tidak lengkap.</p>');
    }

    $decoded = base64_decode(strtr($token, '-_', '+/'));
    if (!$decoded || strpos($decoded, '::') === false) {
        logActivity('BLOCK_INVALID_BASE64', 'Failed to decode base64 token');
        die('<h1>Akses Ditolak</h1><p>Token tidak valid.</p>');
    }

    list($iv, $encrypted) = explode('::', $decoded, 2);
    if (strlen($iv) !== 16) {
        logActivity('BLOCK_INVALID_IV', 'IV length is not 16 bytes');
        die('<h1>Akses Ditolak</h1><p>Token tidak valid.</p>');
    }

    $decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', base64_decode($key), 0, $iv);
    if (!$decrypted) {
        logActivity('BLOCK_DECRYPT_FAIL', 'Failed to decrypt token payload');
        die('<h1>Akses Ditolak</h1><p>Token tidak valid atau rusak.</p>');
    }

    $payload = json_decode($decrypted, true);
    if (!$payload || empty($payload['url'])) {
        logActivity('BLOCK_INVALID_PAYLOAD', 'Payload JSON invalid or missing url');
        die('<h1>Akses Ditolak</h1><p>Token rusak.</p>');
    }

    if (time() - $payload['ts'] > 86400) {
        logActivity('BLOCK_EXPIRED', 'Token expired for App ID: ' . ($payload['id'] ?? 'unknown'));
        die('<h1>Akses Ditolak</h1><p>Sesi URL telah kedaluwarsa. Silakan muat ulang ekstensi.</p>');
    }

    $targetUrl = $payload['url'];
    $appId = $payload['id'] ?? 'unknown';

    $apps = loadData('applications.json');
    foreach ($apps as $a) {
        if ($a['id'] === $appId) {
            $appName = $a['name'];
            break;
        }
    }
} else {
    logActivity('BLOCK_NO_SLUG_OR_TOKEN', 'No slug or token provided');
    die('
    <!DOCTYPE html>
    <html lang="id">
    <head><title>Akses Ditolak</title><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
    <body style="margin:0;padding:0;overflow:hidden;background-color:#010814;color:white;font-family:\'Inter\',system-ui,sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;width:100vw;">
        <div style="background:rgba(255,107,107,0.1);border:1px solid rgba(255,107,107,0.3);padding:30px 40px;border-radius:20px;text-align:center;box-shadow:0 20px 50px rgba(0,0,0,0.5);">
            <svg viewBox="0 0 24 24" fill="none" stroke="#ff4d4d" stroke-width="2" width="60" height="60" style="margin-bottom:20px;">
            <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
            </svg>
            <h2 style="color:#ff4d4d;margin:0 0 10px 0;font-size:24px;">Akses Ditolak</h2>
            <p style="margin:0 0 20px 0;color:#c0c0c0;line-height:1.5;">URL tidak valid atau kosong.</p>
        </div>
    </body>
    </html>
    ');
}

// --- Penanganan Khusus untuk Website Super-Restriktif (seperti Grok) ---
    // Karena Next.js / React Turbopack sangat bergantung pada struktur document origin
    // kita akan menggunakan opsi Server-Side Redirect untuk menghindari Iframe Cross-Origin
    if (strpos($targetUrl, 'grok.com') !== false || strpos($targetUrl, 'chatgpt.com') !== false || strpos($targetUrl, 'claude.ai') !== false) {
        logActivity('SERVER_REDIRECT', "Redirecting directly to: $targetUrl (App: $appName)");
        header("Location: " . $targetUrl);
        exit();
    }
    // -----------------------------------------------------------------------

    logActivity('IFRAME_RENDER', "Rendering iframe for App ID: $appId (Name: $appName)");
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($appName); ?></title>
    <style>
        body, html { margin: 0; padding: 0; height: 100%; overflow: hidden; background: #0F2234; }
        iframe { border: none; width: 100%; height: 100%; display: block; }
        .loading { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #fff; font-family: sans-serif; z-index: -1; }
    </style>
</head>
<body>
    <div class="loading">Memuat <?php echo htmlspecialchars($appName); ?>...</div>
    <iframe id="targetFrame" src="<?php echo htmlspecialchars($targetUrl); ?>" allow="camera; microphone; fullscreen; display-capture; picture-in-picture; clipboard-read; clipboard-write; geolocation" sandbox="allow-same-origin allow-scripts allow-popups allow-forms" allowfullscreen></iframe>
</body>
</html>