<?php
// bot.php — Telegram Webhook / Polling Entry Point
// Receives updates and dispatches to background worker

require_once __DIR__ . '/config.php';
$website = 'https://api.telegram.org/bot' . $botToken;

$update = json_decode(file_get_contents('php://input'), true);
if (!$update) exit; // No valid update, stop

// ── Handle Document (APK Upload) ─────────────────────────
if (isset($update['message']['document'])) {
    $chatId   = $update['message']['chat']['id'];
    $document = $update['message']['document'];
    $caption  = isset($update['message']['caption']) ? trim($update['message']['caption']) : '';

    if (!isAuthorized($chatId)) {
        sendMessage($chatId, "🚫 You are not authorized to use this bot.");
        exit;
    }

    if (strpos(strtolower($document['file_name']), '.apk') === false) {
        sendMessage($chatId, "❌ Please send a valid .apk file.");
        exit;
    }

    // Get download URL from Telegram
    $file_id  = $document['file_id'];
    $response = file_get_contents($website . "/getFile?file_id=" . $file_id);
    $result   = json_decode($response, true);

    if (!isset($result['ok']) || !$result['ok']) {
        sendMessage($chatId, "❌ Failed to get file info from Telegram.");
        exit;
    }

    $file_path    = $result['result']['file_path'];
    $download_url = "https://api.telegram.org/file/bot" . $botToken . "/" . $file_path;

    $orig_name = $document['file_name']; // Keep original filename e.g. "myapp.apk"

    if (!empty($caption)) {
        // Caption sent with APK — start immediately
        $local_apk = __DIR__ . '/temp_' . $chatId . '_' . time() . '.apk';
        file_put_contents($local_apk, file_get_contents($download_url));
        sendMessage($chatId, "✅ APK & filters received! Starting protection in background...");
        startWorker($chatId, $local_apk, $caption, $orig_name);
    } else {
        // No caption yet — save APK and ask for filters
        $waiting_apk  = __DIR__ . '/waiting_' . $chatId . '.apk';
        $waiting_name = __DIR__ . '/waiting_name_' . $chatId . '.txt';
        file_put_contents($waiting_apk,  file_get_contents($download_url));
        file_put_contents($waiting_name, $orig_name); // Remember original filename
        sendMessage($chatId, "📥 APK received!\n\nNow please send the filter text (e.g. package names or keywords) as a reply, and protection will begin automatically.");
    }
}

// ── Handle Text Message (filters / commands) ─────────────
elseif (isset($update['message']['text'])) {
    $chatId = $update['message']['chat']['id'];
    $text   = trim($update['message']['text']);

    if (!isAuthorized($chatId)) {
        sendMessage($chatId, "🚫 You are not authorized to use this bot.");
        exit;
    }

    $waiting_apk = __DIR__ . '/waiting_' . $chatId . '.apk';

    if (file_exists($waiting_apk)) {
        $local_apk    = __DIR__ . '/temp_' . $chatId . '_' . time() . '.apk';
        $waiting_name = __DIR__ . '/waiting_name_' . $chatId . '.txt';
        $orig_name    = file_exists($waiting_name) ? trim(file_get_contents($waiting_name)) : 'protected.apk';
        if (file_exists($waiting_name)) unlink($waiting_name);
        rename($waiting_apk, $local_apk);
        sendMessage($chatId, "✅ Filters received! Starting protection in background...\n⏳ Please wait 2–4 minutes.");
        startWorker($chatId, $local_apk, $text, $orig_name);
    } else {
        if ($text === '/start') {
            sendMessage($chatId, "👋 Welcome to DexProtectX Bot!\n\n📤 Send me an APK file (with or without a caption).\n\n• If you add a caption = filters applied automatically.\n• If no caption = I'll ask you for filters after upload.");
        } elseif ($text === '/help') {
            sendMessage($chatId, "ℹ️ Help\n\n1. Send your APK file.\n2. If prompted, send the filter text (e.g. package name).\n3. Wait 2–4 minutes.\n4. Receive your protected APK! 🛡️");
        } else {
            sendMessage($chatId, "⚠️ No APK is waiting for filters. Please send an APK file first.");
        }
    }
}

// ─────────────────────────────────────────────────────────
// HELPER FUNCTIONS
// ─────────────────────────────────────────────────────────

function isAuthorized($chatId) {
    global $allowed_users;
    return in_array($chatId, $allowed_users);
}

function startWorker($chatId, $local_apk, $caption, $orig_name = 'protected.apk') {
    $caption_b64  = base64_encode($caption);
    $name_b64     = base64_encode($orig_name);
    $worker_script = escapeshellarg(__DIR__ . '/worker.php');
    $arg_chat      = escapeshellarg($chatId);
    $arg_apk       = escapeshellarg($local_apk);
    $arg_caption   = escapeshellarg($caption_b64);
    $arg_name      = escapeshellarg($name_b64);

    $php = escapeshellarg(PHP_BINARY);
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        pclose(popen("start /B $php $worker_script $arg_chat $arg_apk $arg_caption $arg_name", "r"));
    } else {
        exec("$php $worker_script $arg_chat $arg_apk $arg_caption $arg_name > /dev/null 2>&1 &");
    }
}

function sendMessage($chatId, $message) {
    global $website;
    $url = $website . "/sendMessage?chat_id=" . $chatId . "&text=" . urlencode($message);
    @file_get_contents($url);
}
?>
