<?php
/*
 * BGMI bot.php
 *
 * Keep this file, users.json, poster.jpg, premium.jpg and qr.jpg in the
 * same directory. Set BOT_TOKEN on the hosting server; never paste it here.
 */

$botToken = '8443117448:AAHd0T2Yi648z5O5NQNoDhT4o_jYEMzjKHY';

if (!$botToken) {
    http_response_code(500);
    exit('BOT_TOKEN is not configured');
}

define('BOT_TOKEN', $botToken);
define('ADMIN_ID', 7764449739);
define('FEEDBACK_CHANNEL', 'https://t.me/botproofsss');
define('VIEW_PROOFS_CHANNEL', 'https://t.me/tiopgesa');
define('UPI_ID', 'bharatpe2e0q0u1r9m15480@unitype');
define('API_URL', 'https://api.telegram.org/bot' . BOT_TOKEN . '/');
define('POSTER_FILE', 'AgACAgUAAxkBAAIQa2qmKN_aEmfKcLv1_S8AAcYZIetX-gACVxRrGzwxMFXdO8C71BYpJgEAAwIAA3kAAz0E');
define('START_FILE', 'AgACAgUAAxkBAAMGaqYQZpgTSyjsrKANNcJWhYOPeWwAAhESaxt5dylVa-ydcgABSUV8AQADAgADeAADPQQ');
define('QR_FILE', 'AgACAgUAAxkBAAIQg2qmKRa4IyoazKce_iUH93QVPOpdAAJYFGsbPDEwVW8FYyVwdldAAQADAgADeQADPQQ');
define('SESSION_DIR', __DIR__ . '/sessions/');
define('HOW_TO_USE_VIDEO', 'BAACAgUAAxkBAAMPapG3iM4S10afpg1kQT1axsFb-gkAAuEoAAIdtolU24iHnKFbsPo9BA');

define('USERS_FILE', __DIR__ . '/users.json');
define('USER_LOG_FILE', __DIR__ . '/user_ids.log');
define('USER_MARKER_DIR', __DIR__ . '/user_markers/');
define('USERS_LOCK_FILE', __DIR__ . '/users.lock');
define('BROADCAST_QUEUE_FILE', __DIR__ . '/broadcast_queue.json');
define('BROADCAST_QUEUE_LOCK_FILE', __DIR__ . '/broadcast_queue.lock');
define('PREMIUM_VIDEOS_FILE', __DIR__ . '/premium_videos.json');

/*
 * Optional fixed video IDs. Premium video IDs can also be added manually
 * to PREMIUM_VIDEOS_FILE.
 */
define('PREMIUM_VIDEO_IDS', [
]);

error_reporting(E_ALL);
@ini_set('display_errors', '0');

$plans = [
    'plan_1day'  => ['label' => '1Day',   'price' => '249'],
    'plan_3day'  => ['label' => '3Day',   'price' => '399'],
    'plan_7day'  => ['label' => '7Days',  'price' => '499'],
    'plan_15day' => ['label' => '15Days', 'price' => '249'],
];

function api($method, $params)
{
    $ch = curl_init(API_URL . $method);
    if ($ch === false) {
        return ['ok' => false, 'description' => 'Unable to initialize cURL'];
    }

    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($params, JSON_UNESCAPED_UNICODE),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_TIMEOUT        => 15,
    ]);

    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        return ['ok' => false, 'description' => $error ?: 'Telegram API request failed'];
    }

    $result = json_decode($response, true);
    return is_array($result)
        ? $result
        : ['ok' => false, 'description' => 'Invalid Telegram API response'];
}

function sendPhoto($chatId, $photo, $caption, $keyboard = null)
{
    $params = [
        'chat_id'    => $chatId,
        'caption'    => $caption,
        'parse_mode' => 'HTML',
    ];

    if ($keyboard !== null) {
        $params['reply_markup'] = json_encode(
            ['inline_keyboard' => $keyboard],
            JSON_UNESCAPED_UNICODE
        );
    }

    // Support both a local image file and a Telegram photo file_id.
    if (is_string($photo) && file_exists($photo)) {
        $params['photo'] = new CURLFile($photo, 'image/jpeg', basename($photo));

        $ch = curl_init(API_URL . 'sendPhoto');
        if ($ch === false) {
            return ['ok' => false, 'description' => 'Unable to initialize cURL'];
        }

        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $params,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_TIMEOUT        => 30,
        ]);

        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            return ['ok' => false, 'description' => $error ?: 'Photo request failed'];
        }

        $result = json_decode($response, true);
        return is_array($result)
            ? $result
            : ['ok' => false, 'description' => 'Invalid Telegram API response'];
    }

    // If it is not a local file, send it directly as Telegram file_id/URL.
    $params['photo'] = $photo;
    return api('sendPhoto', $params);
}

function sendMsg($chatId, $text, $keyboard = null)
{
    $params = [
        'chat_id'    => $chatId,
        'text'       => $text,
        'parse_mode' => 'HTML',
    ];
    if ($keyboard !== null) {
        $params['reply_markup'] = json_encode(['inline_keyboard' => $keyboard], JSON_UNESCAPED_UNICODE);
    }
    return api('sendMessage', $params);
}

function sendVideo($chatId, $video, $caption = '', $keyboard = null)
{
    $params = [
        'chat_id'           => $chatId,
        'video'             => $video,
        'supports_streaming' => true,
    ];

    if ($caption !== '') {
        $params['caption'] = $caption;
        $params['parse_mode'] = 'HTML';
    }

    if ($keyboard !== null) {
        $params['reply_markup'] = json_encode(
            ['inline_keyboard' => $keyboard],
            JSON_UNESCAPED_UNICODE
        );
    }

    return api('sendVideo', $params);
}

function sendPremiumVideoGroup($chatId, $videos)
{
    $videos = array_values(array_filter(array_map(
        static function ($video) {
            return trim((string)$video);
        },
        $videos
    )));

    if (count($videos) === 0) {
        return [];
    }

    $results = [];
    foreach (array_chunk($videos, 10) as $videoChunk) {
        if (count($videoChunk) === 1) {
            $results[] = sendVideo($chatId, $videoChunk[0]);
            continue;
        }

        $media = [];
        foreach ($videoChunk as $video) {
            $media[] = [
                'type'             => 'video',
                'media'            => $video,
                'supports_streaming' => true,
            ];
        }

        $results[] = api('sendMediaGroup', [
            'chat_id' => $chatId,
            'media'   => $media,
        ]);
    }

    return $results;
}

function answerCB($id)
{
    return api('answerCallbackQuery', ['callback_query_id' => $id]);
}

function forwardMsg($to, $from, $messageId)
{
    return api('forwardMessage', [
        'chat_id'      => $to,
        'from_chat_id' => $from,
        'message_id'   => $messageId,
    ]);
}

function ensureDirectory($directory)
{
    if (!is_dir($directory)) {
        @mkdir($directory, 0777, true);
    }
}

function getSession($uid)
{
    ensureDirectory(SESSION_DIR);
    $file = SESSION_DIR . rawurlencode((string)$uid) . '.json';
    if (!file_exists($file)) {
        return [];
    }
    $data = json_decode((string)file_get_contents($file), true);
    return is_array($data) ? $data : [];
}

function saveSession($uid, $data)
{
    ensureDirectory(SESSION_DIR);
    $file = SESSION_DIR . rawurlencode((string)$uid) . '.json';
    $temp = tempnam(SESSION_DIR, 'session_');
    if ($temp === false) {
        return false;
    }
    $json = json_encode($data, JSON_UNESCAPED_UNICODE);
    if ($json === false || file_put_contents($temp, $json, LOCK_EX) === false) {
        @unlink($temp);
        return false;
    }
    return @rename($temp, $file);
}

function atomicJsonWrite($file, $data)
{
    $temp = tempnam(dirname($file), 'json_');
    if ($temp === false) {
        return false;
    }
    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    if ($json === false || file_put_contents($temp, $json, LOCK_EX) === false) {
        @unlink($temp);
        return false;
    }
    if (!@rename($temp, $file)) {
        @unlink($temp);
        return false;
    }
    return true;
}

function loadPremiumVideoIds()
{
    $ids = [];

    foreach (PREMIUM_VIDEO_IDS as $id) {
        $id = trim((string)$id);
        if ($id !== '' && !in_array($id, $ids, true)) {
            $ids[] = $id;
        }
    }

    if (file_exists(PREMIUM_VIDEOS_FILE)) {
        $saved = json_decode((string)file_get_contents(PREMIUM_VIDEOS_FILE), true);
        if (is_array($saved)) {
            foreach ($saved as $id) {
                $id = trim((string)$id);
                if ($id !== '' && !in_array($id, $ids, true)) {
                    $ids[] = $id;
                }
            }
        }
    }

    return $ids;
}

function loadUsers()
{
    $ids = [];
    if (file_exists(USERS_FILE)) {
        $data = json_decode((string)file_get_contents(USERS_FILE), true);
        if (is_array($data)) {
            foreach ($data as $id) {
                $key = trim((string)$id);
                if ($key !== '') {
                    $ids[$key] = is_numeric($id) ? (int)$id : $id;
                }
            }
        }
    }
    if (file_exists(USER_LOG_FILE)) {
        $lines = @file(USER_LOG_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (is_array($lines)) {
            foreach ($lines as $id) {
                $key = trim((string)$id);
                if ($key !== '') {
                    $ids[$key] = is_numeric($key) ? (int)$key : $key;
                }
            }
        }
    }
    return array_values($ids);
}

/*
 * Registration never rewrites users.json. A marker means the same user is
 * appended only once; cleanup_users.php later merges the log into users.json.
 */
function registerUser($uid)
{
    ensureDirectory(USER_MARKER_DIR);
    $id = (string)$uid;
    $marker = USER_MARKER_DIR . rawurlencode($id) . '.seen';
    if (file_exists($marker)) {
        return;
    }

    $lock = @fopen(USERS_LOCK_FILE, 'c');
    if ($lock === false || !flock($lock, LOCK_EX)) {
        if ($lock) fclose($lock);
        return;
    }

    $markerHandle = @fopen($marker, 'x');
    if ($markerHandle !== false) {
        fclose($markerHandle);
        $log = @fopen(USER_LOG_FILE, 'a');
        if ($log !== false) {
            $written = fwrite($log, $id . PHP_EOL);
            fflush($log);
            fclose($log);
            if ($written === false) {
                @unlink($marker);
            }
        } else {
            @unlink($marker);
        }
    }

    flock($lock, LOCK_UN);
    fclose($lock);
}

function queueBroadcast($type, $caption, $fileId = '')
{
    $lock = @fopen(BROADCAST_QUEUE_LOCK_FILE, 'c');
    if ($lock === false || !flock($lock, LOCK_EX)) {
        if ($lock) fclose($lock);
        return false;
    }

    try {
        $users = loadUsers();
        if ($users === []) {
            return false;
        }

        $queue = [
            'type'         => $type,
            'caption'      => $caption,
            'file_id'      => $fileId,
            'pending'      => array_values(array_unique(array_map('strval', $users))),
            'total'        => count($users),
            'sent_count'   => 0,
            'failed_count' => 0,
            'sent_ids'     => [],
            'created_at'   => date('Y-m-d H:i:s'),
        ];
        return atomicJsonWrite(BROADCAST_QUEUE_FILE, $queue)
            ? count($queue['pending'])
            : false;
    } finally {
        flock($lock, LOCK_UN);
        fclose($lock);
    }
}

function getBroadcastStatus()
{
    if (!file_exists(BROADCAST_QUEUE_FILE)) {
        return null;
    }
    $queue = json_decode((string)file_get_contents(BROADCAST_QUEUE_FILE), true);
    return is_array($queue) ? $queue : null;
}

function acknowledgeWebhook()
{
    http_response_code(200);
    if (function_exists('fastcgi_finish_request')) {
        @fastcgi_finish_request();
    }
}

$input = file_get_contents('php://input');
$update = json_decode($input ?: '', true);
if (!is_array($update)) {
    acknowledgeWebhook();
    exit;
}

/*
 * Telegram receives HTTP 200 before photo/video/payment work starts. This
 * prevents webhook retries while keeping the original handlers intact.
 */
acknowledgeWebhook();

if (isset($update['callback_query'])) {
    $callback = $update['callback_query'];
    $chatId = $callback['message']['chat']['id'];
    $data = (string)$callback['data'];
    answerCB((string)$callback['id']);

    if ($data === 'get_premium') {
        // Send all premium videos listed in the configured video IDs together.
        sendPremiumVideoGroup($chatId, loadPremiumVideoIds());

        // Keep the existing premium poster, text and plan buttons.
        $text = "💎 <b>   𝐎𝐧𝐥𝐲 𝐑𝐬 𝟏𝟒𝟗 𝐟𝐨𝐫 𝐋𝐢𝐦𝐢𝐭𝐞𝐝 𝐓𝐢𝐦𝐞   </b> 💎\n\n"
              . "━━━━━━━━━━━━━━━━━━\n"
              . "💋 <b> MEMBERSHIP CATEGORY </b> 💋\n\n"
              . "𝐃ē𝐬𝐢, ¢𝐡#!𝐥𝐝, 𝐌0𝐦 & s0𝐧, 𝐑@𝐩€, 𝐕𝐢𝐫𝐚𝐥, 𝐂𝐫𝐞𝐚𝐭𝐨𝐫𝐬 𝐌𝐦$, Comics, 𝐒𝐚𝐯𝐢𝐭𝐚 𝐂𝐨𝐦𝐢𝐜𝐬, 𝐚𝐧𝐝 𝐀𝐋𝐋 𝐓𝐘𝐏𝐄 𝐏𝟎𝐑𝐍 𝐕𝐈𝐃𝐄𝐎𝐒 𝐀𝐕𝐀𝐈𝐋𝐀𝐁𝐋𝐄\n\n"
              . "• <i>𝐋𝐚𝐬𝐭 𝐟𝐞𝐰 𝐬𝐥𝐨𝐭𝐬 𝐚𝐭 𝟒𝟗𝟗→ 𝐃𝐨𝐧’𝐭 𝐦𝐢𝐬𝐬 𝐢𝐭!</i> \n\n"
              . "👇 <b>𝐂𝐥𝐢𝐜𝐤 𝐁𝐮𝐲 𝐍𝐨𝐰 </b> 👇";
        sendPhoto($chatId, POSTER_FILE, $text, [
            [['text' => '🫦 𝟏 𝐌𝐨𝐧𝐭𝐡 🫦 ₹ 𝟐𝟒𝟗
', 'callback_data' => 'plan_1day']],
            [['text' => '🥵 𝟐 𝐌𝐨𝐧𝐭𝐡 🥵 ₹ 𝟑𝟗𝟗','callback_data' => 'plan_3day']],
            [['text' => '🍑 𝟑 𝐌𝐨𝐧𝐭𝐡 🍑 ₹ 𝟒𝟗𝟗','callback_data' => 'plan_7day']],
        ]);
    } elseif ($data === 'see_feedback') {
        sendMsg($chatId, '👇 Hamare premium users ka feedback dekhne ke liye click karein:', [
            [['text' => '👁️ Open Feedback Channel', 'url' => FEEDBACK_CHANNEL]],
        ]);
    } elseif (strpos($data, 'plan_') === 0 && isset($GLOBALS['plans'][$data])) {
        $plan = $GLOBALS['plans'][$data];
        $price = $plan['price'];
        $session = getSession($chatId);
        $session['selected_plan'] = $plan;
        $session['waiting_screenshot'] = false;
        saveSession($chatId, $session);

        $text = "⭐ <b>PREMIUM SUBSCRIPTION</b>\n"
              . "━━━━━━━━━━━━━━━━━━\n"
              . "📢 <b>LIMITED OFFER:</b> Only 4 <i>available slots</i>!\n"
              . "💵 <b>FIXED COST:</b> ₹{$price} <b>FULL ACCESS</b>\n"
              . "🛡️ <b>PERMANENT ACTIVATION IN APP</b>\n"
              . "━━━━━━━━━━━━━━━━━━\n"
              . "STEP 1: <b>Transfer ₹{$price} via QR Code</b>\n"
              . "STEP 2: Press 'I HAVE PAID' to verify\n\n"
              . "📌 <b>OFFICIAL UPI ID:</b> <code>" . UPI_ID . "</code>";
        sendPhoto($chatId, QR_FILE, $text, [
            [['text' => '✅ I HAVE PAID (Submit Screenshot)', 'callback_data' => 'i_have_paid']],
            [['text' => '📋 VIEW PROOFS', 'url' => VIEW_PROOFS_CHANNEL]],
            [['text' => '❌ CANCEL', 'callback_data' => 'cancel']],
        ]);
    } elseif ($data === 'i_have_paid') {
        $session = getSession($chatId);
        $session['waiting_screenshot'] = true;
        saveSession($chatId, $session);
        sendMsg($chatId, '📸 ᴋɪɴᴅʟʏ ꜱᴇɴᴅ ᴘᴀʏᴍᴇɴᴛ UTR FROM APP  ᴛᴏ ᴠᴇʀɪꜰʏ and Joi this Channel https://t.me/+NJQkVJ6aid00MTE1');
    } elseif ($data === 'cancel') {
        $session = getSession($chatId);
        $session['waiting_screenshot'] = false;
        saveSession($chatId, $session);
        sendMsg($chatId, '❌ Cancelled. /start karein dobara.');
    } elseif ($data === 'how_to_use') {
        $caption = "📖 <b>HOW TO USE</b>\n\n"
                 . "Yeh video dekh kar aap samajh jaayenge ki\n"
                 . "is bot ko kaise use karna hai.\n\n"
                 . "neeche button se premium lo! 👇";
        sendVideo($chatId, HOW_TO_USE_VIDEO, $caption, [
            [['text' => '💎 GET PREMIUM ENTRY 💎', 'callback_data' => 'get_premium']],
        ]);
    }
    exit;
}

if (!isset($update['message'])) {
    exit;
}

$msg = $update['message'];
$chatId = $msg['chat']['id'];
$uid = $msg['from']['id'];
$text = (string)($msg['text'] ?? '');
$caption = (string)($msg['caption'] ?? '');
registerUser($uid);

$effectiveText = $text !== '' ? $text : $caption;
$command = strtolower(explode(' ', explode('@', $effectiveText)[0])[0]);

if ($command === '/totalusers') {
    if ($uid != ADMIN_ID) {
        sendMsg($chatId, '❌ Sirf admin yeh command use kar sakta hai.');
    } else {
        sendMsg($chatId, '👥 <b>Total Users:</b> <b>' . count(loadUsers()) . '</b>');
    }
} elseif ($command === '/broadcaststatus') {
    if ($uid != ADMIN_ID) {
        sendMsg($chatId, '❌ Sirf admin yeh command use kar sakta hai.');
    } else {
        $queue = getBroadcastStatus();
        if (!$queue) {
            sendMsg($chatId, '✅ Koi broadcast chal nahi raha abhi.');
        } else {
            sendMsg($chatId,
                "📊 <b>Broadcast Status</b>\n\n"
                . "📤 Total: <b>" . ($queue['total'] ?? 0) . "</b>\n"
                . "✅ Bheja: <b>" . ($queue['sent_count'] ?? 0) . "</b>\n"
                . "❌ Failed: <b>" . ($queue['failed_count'] ?? 0) . "</b>\n"
                . "⏳ Baki: <b>" . count($queue['pending'] ?? []) . "</b>\n"
                . "📅 Started: <b>" . ($queue['created_at'] ?? '-') . "</b>"
            );
        }
    }
} elseif ($command === '/broadcastcancel') {
    if ($uid != ADMIN_ID) {
        sendMsg($chatId, '❌ Sirf admin yeh command use kar sakta hai.');
    } else {
        $lock = @fopen(BROADCAST_QUEUE_LOCK_FILE, 'c');
        if ($lock !== false && flock($lock, LOCK_EX)) {
            $cancelled = file_exists(BROADCAST_QUEUE_FILE);
            if ($cancelled) @unlink(BROADCAST_QUEUE_FILE);
            flock($lock, LOCK_UN);
            fclose($lock);
            sendMsg($chatId, $cancelled ? '🚫 Broadcast cancel kar diya gaya!' : 'ℹ️ Koi active broadcast nahi hai.');
        } else {
            if ($lock) fclose($lock);
            sendMsg($chatId, '⚠️ Broadcast lock busy hai, thodi der baad try karein.');
        }
    }
} elseif ($command === '/broadcast') {
    if ($uid != ADMIN_ID) {
        sendMsg($chatId, '❌ Sirf admin yeh command use kar sakta hai.');
    } else {
        $queue = getBroadcastStatus();
        if ($queue && count($queue['pending'] ?? []) > 0) {
            sendMsg($chatId,
                "⚠️ Ek broadcast pehle se chal raha hai!\n"
                . "Baki users: <b>" . count($queue['pending']) . "</b>\n\n"
                . "Pehle /broadcastcancel karo."
            );
        } else {
            $type = 'text';
            $fileId = '';
            if (!empty($msg['photo'])) {
                $type = 'photo';
                $photos = $msg['photo'];
                $lastPhoto = end($photos);
                $fileId = (string)($lastPhoto['file_id'] ?? '');
            } elseif (!empty($msg['video'])) {
                $type = 'video';
                $fileId = (string)($msg['video']['file_id'] ?? '');
            }

            $broadcastText = trim(substr($effectiveText, strlen('/broadcast')));
            if ($broadcastText !== '' && $broadcastText[0] === '@') {
                $space = strpos($broadcastText, ' ');
                $broadcastText = trim($space === false ? '' : substr($broadcastText, $space));
            }

            if ($broadcastText === '' && $type === 'text') {
                sendMsg($chatId,
                    "📢 <b>Broadcast Usage:</b>\n\n"
                    . "• Sirf text: <code>/broadcast Aapka message</code>\n"
                    . "• Photo: caption mein <code>/broadcast Aapka message</code>\n"
                    . "• Video: caption mein <code>/broadcast Aapka message</code>"
                );
            } else {
                $total = queueBroadcast($type, $broadcastText, $fileId);
                if ($total === false) {
                    sendMsg($chatId, '⚠️ Abhi koi user nahi hai broadcast karne ke liye!');
                } else {
                    sendMsg($chatId,
                        "✅ <b>Broadcast Queue Mein Add Ho Gaya!</b>\n\n"
                        . "👥 Total users: <b>{$total}</b>\n"
                        . "📨 Type: <b>{$type}</b>\n\n"
                        . "Cron job automatically bhejta rahega.\n/broadcaststatus se track karo."
                    );
                }
            }
        }
    }
} elseif ($text === '/start') {
    $telegramName = trim(
        (string)($msg['from']['first_name'] ?? '') . ' '
        . (string)($msg['from']['last_name'] ?? '')
    );
    if ($telegramName === '') {
        $telegramName = (string)($msg['from']['username'] ?? 'User');
    }
    $telegramName = htmlspecialchars($telegramName, ENT_QUOTES, 'UTF-8');
    $startCaption = "👋 <b>{$telegramName}</b> Welcome to StarDeals!🎉\n\n"
        . "🍑 <b> 𝐇𝐃 𝐐𝐮𝐚𝐥𝐢𝐭𝐲 • 𝐃𝐚𝐢𝐥𝐲 𝐔𝐩𝐝𝐚𝐭𝐞𝐬 • 𝐔𝐧𝐥𝐢𝐦𝐢𝐭𝐞𝐝 𝐀𝐜𝐜𝐞𝐬𝐬 💦 </b>\n\n"
        . "💰 𝐀𝐟𝐟𝐨𝐫𝐝𝐚𝐛𝐥𝐞 𝐩𝐥𝐚𝐧𝐬 𝐬𝐭𝐚𝐫𝐭𝐢𝐧𝐠 𝐚𝐭 𝐣𝐮𝐬𝐭 ₹𝟏𝟗𝟗 \n\n"
        . "🥵𝐀𝐋𝐋 𝐓𝐘𝐏𝐄 𝐏𝟎𝐑𝐍 𝐕𝐈𝐃𝐄𝐎𝐒 𝐀𝐕𝐀𝐈𝐋𝐀𝐁𝐋𝐄 🥵 \n\n"
        . "𝐃ē𝐬𝐢, ¢𝐡#!𝐥𝐝, 𝐌0_𝐦 & 𝐒_0𝐧, 𝐑@𝐩€, 𝐕𝐢𝐫𝐚𝐥, 𝐂𝐫𝐞𝐚𝐭𝐨𝐫𝐬 𝐌𝐦$, Comics, 𝐒𝐚𝐯𝐢𝐭𝐚 𝐂𝐨𝐦𝐢𝐜𝐬, 𝐚𝐧𝐝 𝐀𝐋𝐋 𝐓𝐘𝐏𝐄 𝐏𝟎𝐑𝐍 𝐕𝐈𝐃𝐄𝐎𝐒 𝐀𝐕𝐀𝐈𝐋𝐀𝐁𝐋𝐄\n\n"
        . "💎 𝐎𝐧𝐥𝐲 𝐑𝐬 𝟏𝟗𝟗 𝐟𝐨𝐫 𝐋𝐢𝐦𝐢𝐭𝐞𝐝 𝐓𝐢𝐦𝐞 💎 \n\n"
        . "✅ 𝗟𝗮𝘁𝗲𝘀𝘁 𝗥𝗲𝗹𝗲𝗮𝘀𝗲𝘀 | ✅ 4𝗞 𝗨𝗹𝘁𝗿𝗮 𝗛𝗗 | ✅ 𝗡𝗼 𝗔𝗱𝘀 • 𝗙𝗮𝘀𝘁 𝗦𝘁𝗿𝗲𝗮𝗺𝗶𝗻𝗴 \n\n"
        . "🫦 𝐂𝐥𝐢𝐜𝐤 𝐖𝐚𝐭𝐜𝐡 √!𝐝ē𝟎𝐬 💦 𝐏𝐫𝐢𝐦𝐢𝐮𝐦 𝐌𝐞𝐦𝐛𝐞𝐫𝐬👇 \n\n";
    $keyboard = [
        [['text' => '𝐖𝐚𝐭𝐜𝐡 √!𝐝ē𝟎𝐬 💦', 'url' => 'http://t.me/Stardeals_Zhub_bot/Stardeals_Z_hub']],
        [['text' => '📢 𝐉𝐨𝐢𝐧 𝐂𝐡𝐚𝐧𝐧𝐞𝐥', 'url' => 'https://t.me/+NJQkVJ6aid00MTE1']],
    ];
    // Small text is sent first so /start has an immediate visible response.
    sendPhoto($chatId, START_FILE, $startCaption, $keyboard);
 } elseif (isset($msg['photo']) && $uid == ADMIN_ID) {
    $photos = $msg['photo'];
    $lastPhoto = end($photos);
    $fileId = (string)($lastPhoto['file_id'] ?? '');

    if ($fileId !== '') {
        sendMsg(
            $chatId,
            "🖼️ <b>Photo File ID:</b>\n<code>{$fileId}</code>\n\n"
            . "Is File ID ko copy karke START_FILE ki jagah use kar sakte ho."
        );
    } else {
        sendMsg($chatId, '❌ Photo File ID nahi mila.');
    }
 } elseif (isset($msg['video']) && $uid == ADMIN_ID) {
    $fileId = (string)($msg['video']['file_id'] ?? '');

    if ($fileId !== '') {
        sendMsg(
            $chatId,
            "🎬 <b>Video File ID:</b>\n<code>{$fileId}</code>\n\n"
            . "Is File ID ko <code>premium_videos.json</code> mein add kar do.\n"
            . "Auto-save band hai."
        );
    } else {
        sendMsg($chatId, '❌ Video File ID nahi mila.');
    }
} elseif (isset($msg['photo'])) {
    $session = getSession($chatId);
    if (!empty($session['waiting_screenshot'])) {
        $session['waiting_screenshot'] = false;
        saveSession($chatId, $session);
        $plan = $session['selected_plan'] ?? [];
        $user = $msg['from'];
        $username = isset($user['username']) ? '@' . $user['username'] : 'no username';
        forwardMsg(ADMIN_ID, $chatId, (int)$msg['message_id']);
        sendMsg(ADMIN_ID,
            "🔔 <b>New Payment!</b>\n"
            . "👤 " . ($user['first_name'] ?? 'User') . " ({$username})\n"
            . "🆔 <code>" . ($user['id'] ?? '') . "</code>\n"
            . "😍 Primium Link send Success ✅ — ₹" . ($plan['price'] ?? '0')
        );
        sendMsg($chatId, 'PLEASE WAIT PEYMENT VERIFY ⌛ https://t.me/+NJQkVJ6aid00MTE1');
    }
}
?>