<?php
// --------------------------------------------------------
// Telegram APK Signer Bot - Main Webhook File
// Webhook URL: https://mifrestamet.co.uk/sig/index.php
// --------------------------------------------------------

// Load configuration
require_once 'config.php';

// Load the main bot logic and signing class
require_once 'apk-signer.php';

// Retrieve the input data from Telegram
$update = json_decode(file_get_contents("php://input"), true);

// Check if this is a callback query (user pressed a button)
if (isset($update['callback_query'])) {
    $callback = $update['callback_query'];
    $data = $callback['data'];
    $chatId = $callback['message']['chat']['id'];
    $messageId = $callback['message']['message_id'];

    $signer = new APKSigner($BOT_TOKEN);
    
    // Answer callback first to remove loading indicator
    $answerUrl = "https://api.telegram.org/bot" . $BOT_TOKEN . "/answerCallbackQuery";
    $answerData = ['callback_query_id' => $callback['id']];
    $ch = curl_init($answerUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $answerData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
    
    // Then process the signing
    $signer->handleSigningCallback($chatId, $data);
    exit;
}

// Make sure we have a valid update
if (!isset($update)) {
    exit;
}

// Extract basic information from the update
$message = isset($update['message']) ? $update['message'] : "";
$chatId = isset($message['chat']['id']) ? $message['chat']['id'] : "";
$text = isset($message['text']) ? $message['text'] : "";
$firstName = isset($message['chat']['first_name']) ? $message['chat']['first_name'] : "User";

// Check if the update contains a document (file upload)
if (isset($message['document'])) {
    $fileId = $message['document']['file_id'];
    $fileName = $message['document']['file_name'];
    $mimeType = $message['document']['mime_type'];

    // Check if the uploaded file is an APK
    if ($mimeType == 'application/vnd.android.package-archive' || pathinfo($fileName, PATHINFO_EXTENSION) == 'apk') {
        // Instantiate the signer class
        $signer = new APKSigner($BOT_TOKEN);

        // Process the uploaded APK
        $signer->handleUploadedAPK($fileId, $chatId, $fileName);
    } else {
        // Not an APK file
        sendMessage($chatId, "❌ لطفاً یک فایل APK معتبر ارسال کنید.");
    }
    exit;
}

// Handle text commands
switch ($text) {
    case '/start':
        $welcomeMessage = "👋 سلام $firstName! به ربات امضاکننده APK خوش آمدید.\n\n";
        $welcomeMessage .= "🤖 من میتونم فایل APK تو رو با 4 روش مختلف امضا کنم:\n\n";
        
        global $SIGNING_METHODS;
        foreach ($SIGNING_METHODS as $method) {
            $welcomeMessage .= $method['name'] . " - " . $method['description'] . "\n\n";
        }
        
        $welcomeMessage .= "📤 فقط کافیه فایل APK رو اینجا بفرستی!\n\n";
        $welcomeMessage .= "🤖 توسعه دهنده: " . CREATOR_ID;
        
        sendMessage($chatId, $welcomeMessage);
        break;

    case '/help':
        $helpMessage = "📖 راهنما:\n";
        $helpMessage .= "1. فایل APK خودت رو برای من بفرست.\n";
        $helpMessage .= "2. من بهت 4 روش امضای مختلف پیشنهاد میدم.\n";
        $helpMessage .= "3. انتخاب کن کدوم روش رو میخوای.\n";
        $helpMessage .= "4. صبر کن تا فایل processed بشه و دانلودش کن!\n\n";
        $helpMessage .= "📜 روش‌های available:\n";
        
        global $SIGNING_METHODS;
        foreach ($SIGNING_METHODS as $method) {
            $helpMessage .= $method['name'] . " - " . $method['description'] . "\n\n";
        }
        
        $helpMessage .= "⚠️ توجه: این ربات برای اهداف آموزشی هست و مسئولیت استفاده از اون به عهده خودتونه.\n\n";
        $helpMessage .= "🤖 توسعه دهنده: " . CREATOR_ID;
        
        sendMessage($chatId, $helpMessage);
        break;

    default:
        if (!empty($text)) {
            sendMessage($chatId, "🤔 متوجه نشدم. از /help کمک بگیر یا یک APK برام بفرست.\n\n🤖 توسعه دهنده: " . CREATOR_ID);
        }
        break;
}

// Function to send a simple text message
function sendMessage($chatId, $text) {
    global $BOT_TOKEN;
    $url = "https://api.telegram.org/bot" . $BOT_TOKEN . "/sendMessage";
    $data = [
        'chat_id' => $chatId,
        'text' => $text,
        'parse_mode' => 'HTML'
    ];
    // Use cURL to send the message
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, count($data));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
}

?>