<?php
define('API_KEY', "API_TOKEN");
$admin = "ADMIN_ID";

define("db_server","localhost"); 
define("db_username","NAME"); 
define("db_password","PASSWORD"); 
define("db_name","NAME");
$connect = mysqli_connect(db_server, db_username, db_password, db_name);
mysqli_set_charset($connect,"utf8mb4");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `users` (
    `id` int(20) auto_increment primary key,
    `user_id` varchar(256),
    `active` varchar(256),
    `status` varchar(256),
    `date` varchar(256),
    `step` varchar(256),
    `premium` varchar(256)
)");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `admins` (
    `id` int(20) auto_increment primary key,
    `user_id` varchar(256),
    `opportunities` varchar(256),
    `date` varchar(256)
)");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `downloads` (
    `id` int(20) auto_increment primary key,
    `file_id` varchar(256),
    `date` varchar(256)
)");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `send` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `message` text NOT NULL,
    `type` text NOT NULL,
    `finish` text NOT NULL,
    `limit` text NOT NULL,
    `succes` text NOT NULL,
    `time1` text NOT NULL,
    `time2` text NOT NULL,
    `time3` text NOT NULL,
    `time4` text NOT NULL,
    `time5` text NOT NULL,
    `button` text NOT NULL,
    `status` text NOT NULL,
     PRIMARY KEY (`id`)
)");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `channels` (
    `id` int(20) auto_increment primary key,
    `channel_id` varchar(256),
    `url` varchar(256),
    `name` varchar(256),
    `members` varchar(256),
    `channel_group_link` varchar(256),
    `type` varchar(256),
    `date` varchar(256),
    `status` varchar(256)
)");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `movies` (
    `id` int(20) auto_increment primary key,
    `code` int(20),
    `name` varchar(256),
    `description` varchar(1024),
    `file_id` varchar(256),
    `status` varchar(256) default 'all'
)");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `download` (
    `id` int(20) auto_increment primary key,
    `file_id` varchar(256),
    `file_name` varchar(256),
    `name` varchar(256),
    `description` varchar(1024)
)");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `zayavka` (
    `id` int(20) auto_increment primary key,
    `chat_id` varchar(256),
    `user_id` varchar(256)
)");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `settings` (
    `id` int(20) auto_increment primary key,
    `share_save` varchar(256),
    `premium` varchar(256),
    `premium_price` varchar(256)
)");

mysqli_query($connect, "INSERT INTO `settings`(`id`, `share_save`, `premium`, `premium_price`) VALUES ('1', 'off', 'off', '30000');");

mysqli_query($connect, "CREATE TABLE IF NOT EXISTS `pay_methods`(
    `id` int(20) auto_increment primary key,
    `name` varchar(256),
    `owner` varchar(256),
    `code` varchar(256)
)");

function bot($method,$datas=[]){
    $url = "https://api.telegram.org/bot".API_KEY."/".$method;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$datas);
    $res = curl_exec($ch);
    if(curl_error($ch)){
        var_dump(curl_error($ch));
    }else{
        return json_decode($res);
    }
}

function joinchat($id, $file) {
    global $connect, $setting, $admin;
    if ($id == $admin || user($id)['isAdmin']) {
        return true;
    }
    if (isPremium($id) && $setting['premium'] == "on") {
        return true;
    }
    $query = mysqli_query($connect, "SELECT * FROM `channels`");
    if (mysqli_num_rows($query) > 0) {
        $noSub = 0;
        while ($channel = mysqli_fetch_assoc($query)) {
            $type = $channel['type'];
            $channel_id = $channel['channel_id'];
            $channel_url = $channel['url'];
            if ($type == "default" || $type == "personal") {
                $status = bot('getChatMember', ['chat_id' => $channel_id, 'user_id' => $id])->result->status;
                if ($status != "member" && $status != "administrator" && $status != "creator") {
                    $noSub++;
                    $keyboards[] = ["text" => "➕ Obuna bo'lish", "url" => $channel_url];
                }
            } else if ($type == "request") {
                $status = bot('getChatMember', ['chat_id' => $channel_id, 'user_id' => $id])->result->status;
                if ($status != "member" && $status != "administrator" && $status != "creator") {
                    $check = mysqli_num_rows(mysqli_query($connect, "SELECT * FROM `zayavka` WHERE `chat_id` = '{$channel_id}' AND `user_id` = '{$id}'"));
                    if ($check < 1) {
                        $noSub++;
                        $keyboards[] = ["text" => "➕ Obuna bo'lish", "url" => $channel_url];
                    }
                }
            } else if ($type == "url") {
                $keyboards[] = ["text" => "➕ Obuna bo'lish", "url" => $channel_url];
            }
        }
        if ($noSub > 0) {
            $keyboard = array_chunk($keyboards, 1);
            $keyboard[] = [["text" => "✅ Tekshirish", "callback_data" => "check-$file"]];
            ($setting['premium'] == "on") ? $keyboard[] = [["text" => "💎 Premium", "callback_data" => "premium"]] : null;
            $button  = json_encode(['inline_keyboard' => $keyboard]);
            bot('sendMessage', [
                'chat_id' => $id,
                'text' => "<b>❌ Kechirasiz, botimizdan foydalanish uchun ushbu kanallarga obuna bo'lishingiz kerak.</b>" .
                          (($setting['premium'] == "on") ? "\n\n<blockquote>💎 Premium obuna sotib olib, kanallarga obuna bo‘lmasdan foydalanishingiz mumkin.</blockquote>" : ""),
                'parse_mode' => "html",
                'reply_markup' => $button
            ]);
        } else {
            return true;
        }
    } else {
        return true;
    }
    exit();
}

function getAdmin($chat_id){
    $result = file_get_contents("https://api.telegram.org/bot".API_KEY."/getChatAdministrators?chat_id=$chat_id");
    $result = json_decode($result)->ok;
    return ($result == "1") ? true : false;
}

function isURL($url) {
    return preg_match("/^(https?):\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(\/[^\s]*)?$/", $url);
}

function user($id) {
    global $connect, $admin;
    $query = mysqli_query($connect, "SELECT * FROM `admins` WHERE `user_id` = '{$id}'");
    if (mysqli_num_rows($query) == 0) {
        return false; 
    }
    $admin = mysqli_fetch_assoc($query);
    $opportunities = json_decode($admin['opportunities'], true);
    return [
        'isAdmin' => true,
        'statistics' => $opportunities['statistics'] ?? false,
        'send' => $opportunities['send'] ?? false,
        'channels' => $opportunities['channels'] ?? false,
        'movies' => $opportunities['movies'] ?? false,
        'settings' => $opportunities['settings'] ?? false
    ];
}

function isPremium($user_id) {
    global $connect;
    $user = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `users` WHERE `user_id` = '{$user_id}'"));
    $currentTime = strtotime(date("Y-m-d H:i"));
    $botTime = strtotime(date("Y-m-d H:i", strtotime($user['premium'])));
    $timeDifference = $botTime - $currentTime;
    $day = floor($timeDifference / (60 * 60 * 24));
    $hour = floor(($timeDifference % (60 * 60 * 24)) / (60 * 60));
    $minute = floor(($timeDifference % (60 * 60)) / 60);
    if ($day <= 0 && $hour <= 0 && $minute <= 0) {
        return false;
    } else {
        return true;
    }
}

function step($step){
    global $connect, $chat_id, $from_id;
    mysqli_query($connect, "UPDATE `users` SET `step` = '{$step}' WHERE `user_id` IN ('{$chat_id}', '{$from_id}')");
}

function download($file){
    global $connect, $date;
    mysqli_query($connect,"INSERT INTO `downloads`(`file_id`, `date`) VALUES ('{$file}', '{$date}');");
}

function getMe() {
    return bot('getMe')->result;
}

$update = json_decode(file_get_contents('php://input'));

$message = $update->message ?? null;
$callback = $update->callback_query ?? null;
$remove_keyboard = json_encode(['remove_keyboard' => true]);
$message_button = isset($update->message->reply_markup) ? json_encode($update->message->reply_markup) : null;
$new_chat_member = $update->my_chat_member->new_chat_member ?? null;
$my_chat_member_id = $update->my_chat_member->from->id ?? null;
$userstatus = $new_chat_member->status ?? null;

$photo = $message->photo ?? null;
$photo_id = $message->photo[count($message->photo) - 1]->file_id ?? null;

$video = $message->video ?? null;
$video_id = $video->file_id ?? null;
$video_name = $video->file_name ?? null;
$video_size = $video->file_size ?? null;
$video_size2 = $video_size/1000;
$video_type = $video->mime_type ?? null;

if (isset($message)) {
    $from_id = $message->from->id ?? null;
    $message_id = $message->message_id ?? null;
    $chat_id = $message->chat->id ?? null;
    $text = $message->text ?? null;
    $first_name = $message->from->first_name ?? null;
    $type = $message->chat->type ?? null;
    $reply_markup = $message->reply_markup ?? null;
    $forward_id = $message->forward_from_chat->id ?? null;
}

if (isset($callback)) {
    $from_id = $callback->message->from->id ?? null;
    $first_name = $callback->from->first_name ?? null;
    $type = $callback->message->chat->type ?? null;
    $chat_id = $callback->message->chat->id ?? null;
    $message_id = $callback->message->message_id ?? null;
    $qid = $callback->id ?? null;
    $data = $callback->data ?? null;
}

date_default_timezone_set("Asia/Tashkent");
$date = date("Y.m.d");
$hour = date('H:i');
$time = date("Y-m-d H:i:s");

$user = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `users` WHERE `user_id` IN ('{$chat_id}', '{$from_id}')"));
$setting = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `settings` WHERE `id` = '1'"));

$join_chatid = $update->chat_join_request->chat->id ?? null;
$join_userid = $update->chat_join_request->from->id ?? null;
$join_userstatus = $update->chat_join_request->chat->type ?? null;

if ($join_userstatus == "channel" || $join_userstatus == "supergroup"){
    $channel = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `channels` WHERE `channel_id` = '{$join_chatid}'"));
    if ($channel['id']) {
        mysqli_query($connect,"INSERT INTO `zayavka`(`chat_id`,`user_id`) VALUES ('{$join_chatid}', '{$join_userid}');");
    }
}

if ($new_chat_member){
    if ($userstatus == "kicked"){
        mysqli_query($connect, "UPDATE `users` SET `status` = 'deactive' WHERE `user_id` = '{$my_chat_member_id}'");
    }
}

if (isset($chat_id)) {
    if (!$user['id']) {
        mysqli_query($connect, "INSERT INTO users(`user_id`, `status`, `date`, `step`) VALUES ('{$chat_id}', 'active', '{$date}', '')");
    } elseif ($user['status'] == "deactive") {
        mysqli_query($connect, "UPDATE `users` SET `status` = 'active' WHERE `user_id` = '{$chat_id}'");
    }

    if ($user['active'] != $date) {
        mysqli_query($connect, "UPDATE `users` SET `active` = '{$date}' WHERE `user_id` = '{$chat_id}'");
    }
}

$panel = json_encode([
            'resize_keyboard' => true,
            'keyboard' => [
                [['text' => "📊 Statistika"], ['text'=>"📨 Xabar yuborish"]],
                [['text' => "🎬 Kinolar"], ['text' => "🔐 Kanallar"]],
                [['text' => "👮‍♀️ Adminlar"], ['text'=>"⚙️ Sozlamalar"]],
                [['text' => "⏪ Orqaga"]],
            ]]);

$Bpanel = json_encode([
            'resize_keyboard' => true,
            'keyboard' => [
                [['text' => "🗄️ Boshqaruv"]],
            ]]);


$keyboards = [
    [['text' => "💎 Premium"]]
];

if (isset($chat_id) && ($chat_id == $admin || user($chat_id)['isAdmin'])) {
    $keyboards[] = [['text' => "🗄️ Boshqaruv"]];
}

$menu = json_encode([
    'resize_keyboard' => true,
    'keyboard' => $keyboards,
]);

if (isset($text) && explode(" ", $text)[0] == "/start" && explode(" ", $text)[1] > 0){
    $code = preg_replace('/\D/', '', $text);
    $bot = getMe()->username;
    $count = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `movies` WHERE `code` = '{$code}'"))['Total'];
    if (joinchat($chat_id, $code)) {
        if ($count > 0) {
            $query = mysqli_query($connect, "SELECT * FROM `movies` WHERE `code` = '{$code}' LIMIT 10");
            if ($count > 1) {
                $i = 0;
                $txt = "";
                $keyboard = [];
                $limit = 10;
                $total_pages = ceil($count / $limit);
                $page = 1;
                $offset = ($page - 1) * $limit;
                while ($movie = mysqli_fetch_assoc($query)) {
                    $i++;
                    $name = $movie['name'] ?: "{$i}-qism";
                    $txt .= "<b>$i.</b> $name " . ($movie['status'] == "premium" ? "💎" : "") ."\n";
                    $keyboard[] = ['text' => "$i", 'callback_data' => "movie_{$movie['id']}"];
                }
                $inline_keyboard = array_chunk($keyboard, 5);
                $inline_keyboard[] = [['text' => ($page > 1) ? "⏪" : "", 'callback_data' => "page_" . ($page - 1) . "_{$code}"], ['text' => "$page/$total_pages", 'callback_data' => "ignore"], ['text' => ($page < $total_pages) ? "⏩" : "", 'callback_data' => "page_" . ($page + 1) . "_$code"]];
                $inline_keyboard[] = ($setting['premium'] == "on") ? [["text" => "💎 Premium", "callback_data" => "premium"]] : [];
                bot('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "<b>🎬 Kino qismlari roʻyxati:</b>\n\n$txt",
                    'parse_mode' => 'html',
                    'reply_markup' => json_encode([
                        'inline_keyboard' => $inline_keyboard
                    ])
                ]);
            } else {
                $movie = mysqli_fetch_assoc($query);
                if ($movie['status'] == "premium") {
                    if (isPremium($chat_id)) {
                        $downloads = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `downloads` WHERE `file_id` = '{$movie['id']}'"));  
                        $name = ($movie['name']) ? "<b>🎬 Nomi:</b> {$movie['name']}\n\n" : "";
                        $description = ($movie['description']) ? "{$movie['description']}\n\n" : "";
                        bot('sendVideo',[
                            'chat_id' => $chat_id,
                            'video' => $movie['file_id'],
                                'caption' => "🔎 <b>Kino kodi:</b> <code>{$movie['code']}</code>\n\n$name$description<b>🤖 Botimiz:</b> @$bot \n\n<b>👁 Ko'rishlar:</b> {$downloads['Total']} ta",
                                'parse_mode' => 'html',
                                'protect_content' => ($setting['share_save'] == "on") ? true : false,
                                'reply_markup' => json_encode([
                                    'inline_keyboard' => [
                                        [['text' => "↗️ Ulashish",'url'=>"https://t.me/share/url/?url=https://t.me/$bot?start={$movie['code']}"]],
                                ]])
                            ]);
                        download($movie['id']);
                    } else {
                        bot('sendMessage', [
                            'chat_id' => $chat_id,
                            'text' => "<b>🔒 Ushbu kino faqat «Premium» foydalanuvchilar uchun</b> \n\n<blockquote>❗️ Kinoni ko'rish uchun Premium obuna sotib oling.</blockquote>",
                            'parse_mode' => 'html',
                            'reply_markup' => json_encode([
                                'inline_keyboard' => [
                                    ($setting['premium'] == "on") ? [["text" => "💎 Premium", "callback_data" => "premium"]] : [],
                            ]])
                        ]); 
                    }
                } else {
                    $downloads = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `downloads` WHERE `file_id` = '{$movie['id']}'"));  
                    $name = ($movie['name']) ? "<b>🎬 Nomi:</b> {$movie['name']}\n\n" : "";
                    $description = ($movie['description']) ? "{$movie['description']}\n\n" : "";
                    bot('sendVideo',[
                        'chat_id' => $chat_id,
                        'video' => $movie['file_id'],
                            'caption' => "🔎 <b>Kino kodi:</b> <code>{$movie['code']}</code>\n\n$name$description<b>🤖 Botimiz:</b> @$bot \n\n<b>👁 Ko'rishlar:</b> {$downloads['Total']} ta",
                            'parse_mode' => 'html',
                            'protect_content' => ($setting['share_save'] == "on") ? true : false,
                            'reply_markup' => json_encode([
                                'inline_keyboard' => [
                                    [['text' => "↗️ Ulashish",'url'=>"https://t.me/share/url/?url=https://t.me/$bot?start={$movie['code']}"]],
                            ]])
                        ]);
                    download($movie['id']);
                }
                exit();
            }
        } else {
            bot('sendMessage', [
                'chat_id' => $chat_id,
                'text' => "<b>👋 Assalomu alaykum <a href='tg://user?id=$chat_id'>$first_name</a> botimizga xush kelibsiz.</b> \n\n✍🏻 Kino kodini yuboring...",
                'parse_mode' => 'html',
                'reply_markup' => ($setting['premium'] == "off") ? (($chat_id == $admin || user($chat_id)['isAdmin']) ? $Bpanel : $remove_keyboard) : $menu,
            ]);
        }
    }
    step("");
    exit();
}

if (isset($text) && ($text == "/start" || $text == "⏪ Orqaga") && joinchat($chat_id, $code)) {
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "<b>👋 Assalomu alaykum <a href='tg://user?id=$chat_id'>$first_name</a> botimizga xush kelibsiz.</b>

✍🏻 Kino kodini yuboring...",
        'parse_mode' => 'html',
        'reply_markup' => ($setting['premium'] == "off") ? (($chat_id == $admin || user($chat_id)['isAdmin']) ? $Bpanel : $remove_keyboard) : $menu,
    ]);
    step("");
    exit();
}

if ((isset($text) || isset($data)) && ($text == "💎 Premium" || $data == "premium") && $setting['premium'] == "on") {
    $currentTime = strtotime(date("Y-m-d H:i"));
    $botTime = strtotime(date("Y-m-d H:i", strtotime($user['premium'])));
    $timeDifference = $botTime - $currentTime;
    $day = floor($timeDifference / (60 * 60 * 24));
    $hour = floor(($timeDifference % (60 * 60 * 24)) / (60 * 60));
    $minute = floor(($timeDifference % (60 * 60)) / 60);
    if ($day <= 0 && $hour <= 0 && $minute <= 0) {
        bot($data ? 'editMessageText' : 'SendMessage',[
            'chat_id' => $chat_id,
            'message_id' => $message_id,
            'text' => "<b>💎 Siz Premium bo‘limidasiz</b>
        
❓ <b>Premium nima va uni sotib olganda nima bo‘ladi?</b>
    
<b>✅ Premium foydalanuvchilarga quyidagi qulayliklar taqdim etiladi:</b>
• Kanallarga obuna bo‘lmasdan kino yuklab olish
• Reklamalarsiz, tez va qulay foydalanish

💰 <b>Narx va Muddati:</b>
• 30 kun — " .(number_format($setting['premium_price'], 0, '.', ' ')). " so‘m

<i>Pastdagi tugmani bosib Premiumni sotib olishingiz mumkin.</i>",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => "💳 Sotib olish", 'callback_data' => "Payments"]],
                ]
            ]),
        ]);
    } else {
        bot($data ? 'editMessageText' : 'SendMessage',[
            'chat_id' => $chat_id,
            'message_id' => $message_id,
            'text' => "<b>💎 Siz Premium bo‘limidasiz</b>
        
❓ <b>Premium nima va uni sotib olganda nima bo‘ladi?</b>
    
<b>✅ Premium foydalanuvchilarga quyidagi qulayliklar taqdim etiladi:</b>
• Kanallarga obuna bo‘lmasdan kino yuklab olish
• Reklamalarsiz, tez va qulay foydalanish

📅 <b>Premium muddati:</b> $day kun, $hour soat, $minute daqiqa
📌 <b>Holatingiz:</b> Premium foydalanuvchi",
            'parse_mode' => 'html',
        ]);
    }
    step("");
    exit();
}

if (isset($data) && $data == "Payments" && $setting['premium'] == "on") {
    $get = mysqli_query($connect, "SELECT * FROM `pay_methods`");
    $count = 0;
    $key = [];
    while ($payment = mysqli_fetch_assoc($get)) {
        $count++;
        $key[] = ['text' => $payment['name'], 'callback_data' => "pay-{$payment['id']}"];
    }
    $keyboard = array_chunk($key, 1);
    $keyboard[] = [['text' => "⏪ Orqaga", 'callback_data' => "premium"]];
    $button = json_encode(['inline_keyboard' => $keyboard]);
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => ($count > 0) 
            ? "<b>💳 Quyidagi to‘lov tizimlaridan birini tanlang:</b>" 
            : "<b>⚠️ To‘lov tizimlar qo'shilmagan.</b>",
        'parse_mode' => 'html',
        'reply_markup' => $button,
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "pay" && $setting['premium'] == "on") {
    $payment_id = explode("-", $data)[1];
    $tariff_id = explode("-", $data)[2];
    $payment = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `pay_methods` WHERE `id` = '{$payment_id}'"));
    $tariff = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `tariffs` WHERE `id` = '{$tariff_id}'"));
    $owner = (!empty($payment['owner'])) 
        ? "\n👤 <b>Hisob raqam egasi:</b> {$payment['owner']}" 
        : "";
    $sum = number_format($tariff['price'], 0, '.', ' ');
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "💎 <b>PREMIUM — Sotib olish uchun to‘lov ma'lumotlari</b>

💰 <b>Narx:</b> <code>" . number_format($setting['premium_price'], 0, '.', ' ') . "</code> so‘m
📆 <b>Muddati:</b> 30 kun
💳 <b>To‘lov tizimi:</b> {$payment['name']}
🔢 <b>Karta raqami:</b> <code>{$payment['code']}</code> $owner

❗ <i>To‘lovni amalga oshirgach, iltimos, chekning skrinshotini yoki fotosuratini shu yerga yuboring.</i>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "⏪ Orqaga", 'callback_data' => "Payments"]],
            ]
        ])
    ]);
    step("pay-$payment_id");
    exit();
}

if (isset($user['step']) && explode("-", $user['step'])[0] == "pay" && $setting['premium'] == "on") {
    $payment_id = explode("-", $user['step'])[1];
    $payment = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `pay_methods` WHERE `id` = '{$payment_id}'"));
    $tariff = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `tariffs` WHERE `id` = '{$tariff_id}'"));
    if ($photo) {
        bot('SendPhoto',[
            'chat_id' => $admin,
            'photo' => $photo_id,
            'caption' => "<b>⏳ Yangi to‘lov tekshiruvda!</b> #Tekshiruvda \n\n "
                    . "💳 <b>To‘lov tizimi:</b> {$payment['name']}\n"
                    . "👤 <b>Foydalanuvchi:</b> <a href='tg://user?id=$chat_id'>$chat_id</a>\n"
                    . "💰 <b>To‘lov summasi:</b> <code>" . number_format($setting['premium_price'], 0, '.', ' ') . "</code> so‘m\n"
                    . "⏰ <b>Sana:</b> $time",
            'parse_mode' => 'html',
            'reply_markup'=>json_encode([
                'inline_keyboard'=>[
                    [['text'=>"✅",'callback_data'=>"confirmation-$chat_id-{$payment['id']}"], ['text'=>"❌",'callback_data'=>"cancel-{$chat_id}-{$payment['id']}"]],
                ]])
        ]);
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>✅ Chekingiz qabul qilindi!</b>\n\n"
                    . "Adminlar tomonidan tez orada ko‘rib chiqiladi. Agar to‘lov muvaffaqiyatli amalga oshirilgan bo‘lsa, sizga premium obunasi beriladi.",
            'parse_mode' => 'html',
        ]);
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>👋 Assalomu alaykum <a href='tg://user?id=$chat_id'>$first_name</a> botimizga xush kelibsiz.</b>

✍🏻 Kino kodini yuboring...",
            'parse_mode' => 'html',
            'reply_markup' => ($setting['premium'] == "off") ? (($chat_id == $admin || user($chat_id)['isAdmin']) ? $Bpanel : $remove_keyboard) : $menu,
        ]);
        step("");
    } else {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "⚠️ <b>Chekni faqat rasm holatida yuboring.</b>",
            'parse_mode' => 'html',
        ]);
    }
    exit();
}

if (isset($data) && explode("-", $data)[0] == "confirmation") {
    $user_id = explode("-", $data)[1];
    $payment_id = explode("-", $data)[2];
    $payment = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `pay_methods` WHERE `id` = '{$payment_id}'"));
    bot('editMessageCaption', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'caption' => "<b>✅ To'lov tasdiqlandi!</b> #Tasdiqlandi\n\n"
                . "💳 <b>To‘lov tizimi:</b> {$payment['name']}\n"
                . "👤 <b>Foydalanuvchi:</b> <a href='tg://user?id=$user_id'>$user_id</a>\n"
                . "💰 <b>To‘lov summasi:</b> <code>" . number_format($setting['premium_price'], 0, '.', ' ') . "</code> so‘m\n"
                . "⏰ <b>Sana:</b> $time",
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true,
    ]);
    $day = date("Y-m-d H:i", strtotime("+30 days"));
    mysqli_query($connect, "UPDATE `users` SET `premium` = '{$day}' WHERE `user_id` = '{$user_id}'");
    bot('sendMessage', [
        'chat_id' => $user_id,
        'text' => "✅ <b>To‘lov muvaffaqiyatli tasdiqlandi!</b>\n\n🎉 <b>Sizga 30 kunlik Premium obuna berildi.</b>",
        'parse_mode' => 'html'
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "cancel") {
    $user_id = explode("-", $data)[1];
    $payment_id = explode("-", $data)[2];
    $payment = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `pay_methods` WHERE `id` = '{$payment_id}'"));
    $tariff = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `tariffs` WHERE `id` = '{$tariff_id}'"));
    bot('editMessageCaption', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'caption' => "<b>⛔️ To'lov bekor qilindi!</b> #Bekor_qilindi\n\n"
                . "💳 <b>To‘lov tizimi:</b> {$payment['name']}\n"
                . "👤 <b>Foydalanuvchi:</b> <a href='tg://user?id=$user_id'>$user_id</a>\n"
                . "💰 <b>To‘lov summasi:</b> <code>" . number_format($setting['premium_price'], 0, '.', ' ') . "</code> so‘m\n"
                . "⏰ <b>Sana:</b> $time",
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true,
    ]);
    bot('sendMessage', [
        'chat_id' => $user_id,
        'text' => "<b>❌ To‘lovingiz bekor qilindi!</b>",
        'parse_mode' => 'html',
    ]);
    step("");
    exit();
}

if (isset($text) && ($text == "/panel" || $text == "🗄️ Boshqaruv") && ($chat_id == $admin || user($chat_id)['isAdmin'])) {
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "<b>Admin paneliga xush kelibsiz!</b>",
        'parse_mode' => 'html',
        'reply_markup' => $panel,
    ]);
    step("");
    exit();
}

if (isset($text) && $text == "📊 Statistika" && ($chat_id == $admin || user($chat_id)['isAdmin'])) {
    if ($chat_id == $admin || user($chat_id)['statistics']) {
        $bot = getMe()->username;
        $Users = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total,
                   SUM(status = 'active') AS Active,
                   SUM(status = 'deactive') AS Deactive
            FROM `users`
        "));
        
        $TodayAdd = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total 
            FROM `users` WHERE `date` = '{$date}'
        "));
        $SevenDayAdd = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total 
            FROM `users` 
            WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        "));
        $ThirtyDayAdd = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total 
            FROM `users` 
            WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        "));
        
        $TodayActive = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total 
            FROM `users` WHERE `active` = '{$date}'
        "));
        $SevenDayActive = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total 
            FROM `users` 
            WHERE `active` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        "));
        $ThirtyDayActive = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total 
            FROM `users` 
            WHERE `active` >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        "));
        
        $TodayDownloads = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total 
            FROM `downloads` WHERE `date` = '{$date}'
        "));
        $SevenDayDownloads = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total 
            FROM `downloads` 
            WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        "));
        $ThirtyDayDownloads = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total 
            FROM `downloads` 
            WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        "));
        
        $Movies = mysqli_fetch_assoc(mysqli_query($connect, "
            SELECT COUNT(*) AS Total
            FROM `movies`
        "));
    
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>📊 Statistika</b> \n<b>• Obunachilar soni:</b> " .number_format($Users['Total'], 0, '.', ' '). " ta \n<b>• Faol obunachilar:</b> " .number_format($Users['Active'], 0, '.', ' '). " ta \n<b>• Tark etganlar:</b> " .number_format($Users['Deactive'], 0, '.', ' '). " ta \n\n<b>📈 Obunachilar qo'shilishi</b> \n<b>• Oxirgi 24 soat:</b> +" .number_format($TodayAdd['Total'], 0, '.', ' '). " obunachi \n<b>• Oxirgi 7 kun:</b> +" .number_format($SevenDayAdd['Total'], 0, '.', ' '). " obunachi \n<b>• Oxirgi 30 kun:</b> +" .number_format($ThirtyDayAdd['Total'], 0, '.', ' '). " obunachi \n\n<b>📊 Faollik</b> \n<b>• Oxirgi 24 soatda faol:</b> " .number_format($TodayActive['Total'], 0, '.', ' '). " ta \n<b>• Oxirgi 7 kun faol:</b> " .number_format($SevenDayActive['Total'], 0, '.', ' '). " ta \n<b>• Oxirgi 30 kun faol:</b> " .number_format($ThirtyDayActive['Total'], 0, '.', ' '). " ta \n\n<b>📥 Yuklanishlar</b> \n<b>• Oxirgi 24 soat:</b> " .number_format($TodayDownloads['Total'], 0, '.', ' '). " ta \n<b>• Oxirgi 7 kun:</b> " .number_format($SevenDayDownloads['Total'], 0, '.', ' '). " ta \n<b>• Oxirgi 30 kun:</b> " .number_format($ThirtyDayDownloads['Total'], 0, '.', ' '). " ta \n\n🎬 <b>Kinolar soni:</b> " .number_format($Movies['Total'], 0, '.', ' '). " ta\n\n🤖 <b>@$bot</b>",
            'parse_mode' => 'html',
        ]);
    } else {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>🚫 Sizda ushbu bo'limga kirish uchun ruxsat yo‘q!</b>",
            'parse_mode' => "html",
        ]);
    }
    step("");
    exit();
}

if (isset($text) && $text == "📨 Xabar yuborish" && ($chat_id == $admin || user($chat_id)['isAdmin'])) {
    if ($chat_id == $admin || user($chat_id)['send']) {
        $send = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `send` WHERE `status` = 'on'"));
        (!$send['id']) ? $arr[]=[['text'=>"Oddiy",'callback_data'=>"send-CopyMessage"],['text'=>"Forward",'callback_data'=>"send-ForwardMessage"]] : null;
        ($send['id']) ? $arr[]=[['text'=>"⏳ Xabar holati",'callback_data'=>"send-status"]] : null;
        ($send['id']) ? $arr[]=[['text'=>"🗑 Xabar o'chirish",'callback_data'=>"send-del"]] : null;
        $inline = json_encode([
        'inline_keyboard' => $arr,
        ]);
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>📨 Xabar yuborish bo'limidasiz:</b> \n\n" . ((!$send['id']) ? "<i>Foydalanuvchilarga yuboradigan xabar turini tanglang.</i>" : ""),
            'parse_mode' => "html",
            'reply_markup' => $inline
        ]);
    } else {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>🚫 Sizda ushbu bo'limga kirish uchun ruxsat yo‘q!</b>",
            'parse_mode' => "html",
        ]);
    }
    step("");
    exit();
}

if (isset($data) && stripos($data, "send-") !== false) {
    $action = explode("-", $data)[1];
    if ($action == "CopyMessage" or $action == "ForwardMessage") {
        bot('deleteMessage',[
    	    'chat_id' => $chat_id,
    	    'message_id' => $message_id,
        ]);
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>✍️ Foydalanuvchilarga yuboradigan xabarni kiriting:</b>",
            'parse_mode' => "html",
            'reply_markup' => $Bpanel
        ]);
        step("send-$action");
        mysqli_query($connect, "DELETE FROM `send`"); 
    }
    
    if ($action == "status") {
        $send = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `send`"));
        $type = ($send['type'] == "CopyMessage") ? "Oddiy" : "Forward";
        bot('answerCallbackQuery',[
        	'callback_query_id'=>$qid,
        	'text'=>"✅ Xabar yuborilmoqda! \n\n⚙️ Xabar turi: $type\n📤 Yuborildi: $send[succes] ta",
        	'show_alert'=>true,
        ]);
        step("");
    }
    
    if ($action == "del") {
        bot('deleteMessage',[
    	    'chat_id' => $chat_id,
    	    'message_id' => $message_id,
        ]);
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>⚠️ Xabar o'chirilsinmi!</b>",
            'parse_mode' => "html",
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => "✅ Ha", 'callback_data' => "senddel-yes"],['text' => "⛔️ Yo'q", 'callback_data' => "senddel-no"]],
            ]]),
        ]);
        step("send-$action");
    }
    exit();
}

if (isset($data) && stripos($data, "senddel-") !== false) {
    $action = explode("-", $data)[1];
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    if ($action == "yes") {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>✅ Xabar o'chirildi!</b>",
            'parse_mode' => "html",
            'reply_markup' => $panel,
        ]);
        mysqli_query($connect,"DELETE FROM `send`");
    } else if ($action == "no") {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>Admin paneliga hush kelibsiz!</b>",
            'parse_mode' => "html",
            'reply_markup' => $panel
        ]);
    }
    step("");
    exit();
}

if (isset($user['step']) && stripos($user['step'], "send-") !== false) {
    $type = explode("-", $user['step'])[1];
    bot($type, [
        'chat_id' => $chat_id,
        'from_chat_id' => $chat_id,
        'message_id' => $message_id,
        'reply_markup' => $message_button,
    ]);
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "<b>❓ Xabar yuborilsinmi.</b>",
        'parse_mode' => "html",
        'reply_markup' =>json_encode([
            'inline_keyboard' => [
                [['text' => "✅ Yuborish", 'callback_data' => "sendsms"]],
        ]]),
    ]);
    step("");
    $button = base64_encode($message_button);
    mysqli_query($connect,"INSERT INTO `send`(`message`, `type`, `finish`, `limit`,`succes`, `time1`, `time2`, `time3`, `time4`, `time5`, `button`, `status`) VALUES ('{$message_id}', '{$type}', '', '100', '0', '', '','', '', '', '{$button}', 'off');");
    exit();
}


if (isset($data) && $data == "sendsms"){
    $time1 = date('H:i', strtotime('+1 minutes')); 
    bot('deleteMessage',[
        'chat_id' => $chat_id,
        'message_id' => $message_id,
    ]);
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "<b>⏳ Xabar qabul qilindi!</b> \n\nXabar yuborish $time1 da boshlanadi.",
        'parse_mode' => "html",
        'reply_markup' => $panel,
    ]);
    $users = mysqli_num_rows(mysqli_query($connect,"SELECT * FROM users"));
    $limit = $users - 1;
    $finish = mysqli_fetch_assoc(mysqli_query($connect,"SELECT * FROM users LIMIT $limit,$users"))['user_id'];
    $time2 = date('H:i', strtotime('+2 minutes')); 
    $time3 = date('H:i', strtotime('+3 minutes')); 
    $time4 = date('H:i', strtotime('+4 minutes')); 
    $time5 = date('H:i', strtotime('+5 minutes')); 
    mysqli_query($connect, "UPDATE `send` SET `finish` = '{$finish}', `time1` = '{$time1}', `time2` = '{$time2}', `time3` = '{$time3}', `time4` = '{$time4}', `time5` = '{$time5}', `status` = 'on' ");
    $bot = getMe()->username;
    step("");
    exit();
}

if ((isset($text) || isset($data)) && ($text == "🔐 Kanallar" || $data == "channels") && ($chat_id == $admin || user($chat_id)['isAdmin'])) {
    $data ? bot('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id]) : null;
    if ($chat_id == $admin || user($chat_id)['channels']) {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>🔐 Majburiy obuna kanallar:</b>",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => "➕ Kanal qo‘shish", 'callback_data' => "add_channel"]],
                    [['text' => "📋 Ro‘yxatni ko‘rish", 'callback_data' => "list_channel"]],
                    [['text' => "🗑 Kanalni o‘chirish", 'callback_data' => "del_channel"]]
                ]
            ])
        ]); 
    } else {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>🚫 Sizda ushbu bo'limga kirish uchun ruxsat yo‘q!</b>",
            'parse_mode' => "html",
        ]);
    }
    step("");
    exit();
}

if (isset($data) && $data == "del_channel" && ($chat_id == $admin || user($chat_id)['channels'])) {
    $get = mysqli_query($connect, "SELECT * FROM `channels`");
    $count = 0;
    $buttons = [];
    while ($channel = mysqli_fetch_assoc($get)) {
        $count++;
        $channel_name = ($channel['type'] == "url") ? $channel['url'] : base64_decode($channel['name']);
        $buttons[] = ['text' => "🗑 " . $channel_name, 'callback_data' => "delChannel-" . $channel['id']];
    }
    $keyboard = array_chunk($buttons, 1);
    $keyboard[] = [['text' => "⏪ Orqaga", 'callback_data' => "channels"]];
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => ($count > 0) ? "<b>📋 Majburiy obuna kanallar ro‘yxati:</b>\n\n🔢 <b>Jami:</b> <b>$count ta</b>\n\n🗑 O‘chirish uchun kerakli kanal nomini bosing." : "<b>⚠️ Majbur obuna kanallar qo‘shilmagan!</b>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
        'inline_keyboard' => $keyboard
    ])
    ]);
    step("");
    exit();
}

if (isset($data) && stripos($data, "delChannel-") !== false && ($chat_id == $admin || user($chat_id)['channels'])) {
    $id = explode("-", $data)[1];
    $channel = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `channels` WHERE `id` = '{$id}'"));
    bot('deleteMessage', [
        'chat_id' => $chat_id,
        'message_id' => $message_id
    ]);
    $type = ($channel['channel_group_link'] == 'channel') ? 'Kanal' : (($channel['channel_group_link'] == 'group') ? 'Guruh' : 'Havola');
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "<b>✅ {$type} o'chirildi!</b>",
        'parse_mode' => 'html',
        'reply_markup' => $panel
    ]);
    mysqli_query($connect, "DELETE FROM `channels` WHERE `id` = '{$id}'");
    if ($channel['type'] == "request") {
        mysqli_query($connect, "DELETE FROM `zayavka` WHERE `chat_id` = '{$channel['channel_id']}'");
    }
    step("");
    exit();
}

if (isset($data) && $data == "list_channel" && ($chat_id == $admin || user($chat_id)['channels'])) {
    $get = mysqli_query($connect, "SELECT * FROM `channels`");
    $count = 0;
    $buttons = [];
    while ($channel = mysqli_fetch_assoc($get)) {
        $count++;
        $channel_name = ($channel['type'] == "url") ? $channel['url'] : base64_decode($channel['name']);
        $buttons[] = ['text' => "⚙️ " . $channel_name, 'callback_data' => "channel-" . $channel['id']];
    }
    $keyboard = array_chunk($buttons, 1);
    $keyboard[] = [['text' => "⏪ Orqaga", 'callback_data' => "channels"]];
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => ($count > 0) ? "<b>📋 Majburiy obuna kanallari ro‘yxati:</b>\n\n🔢 <b>Jami:</b> <b>$count ta</b>\n\n👇 Kerakli kanal ustiga bosib ma'lumotlarni ko‘rishingiz mumkin." : "<b>⚠️ Majbur obuna kanallar qo‘shilmagan!</b>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => $keyboard
        ])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "channel") {
    $id = explode("-", $data)[1];
    $channel = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `channels` WHERE `id` = '{$id}'"));
    $name = base64_decode($channel['name']);
    $channel_group_link = $channel['channel_group_link'];
    $type = $channel['type'];
    $mamber = number_format($channel['members'], 0, '.', ' ');
    $date = $channel['date'];
    $url = str_replace("https://t.me/", "", $channel['url']);
    $full_url = $channel['url'];
    $buttons = [[['text' => "⏪ Orqaga", 'callback_data' => "list_channel"]]];
    $title = "ℹ️ Tafsilotlar";
    $body = "";
    $link_button_text = "🔗 Havola";
    if ($channel_group_link == "channel" || $channel_group_link == "group") {
        $current_members = number_format(bot('getChatMembersCount', ['chat_id' => $channel['channel_id']])->result, 0, '.', ' ');
        $group_type = ($channel_group_link == "channel") ? "Kanal" : "Guruh";
        $link_button_text = ($channel_group_link == "channel") ? "↗️ Kanalga o'tish" : "↗️ Guruhga o'tish";
        if ($type == "default" || $type == "personal") {
            $title = "📢 <b>{$group_type} tafsilotlari</b>";
            $body = "
📌 <b>Nomi:</b> <i>{$name}</i>
👥 <b>Obunachilar:</b> avval: {$mamber} ta, hozir: {$current_members} ta
🗓 <b>Qo‘shilgan:</b> <i>{$date}</i>";
        } else if ($type == "request") {
            $requests = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `zayavka` WHERE `chat_id` = '{$channel['channel_id']}'"));
            $title = "📢 <b>{$group_type} tafsilotlari</b>";
            $body = "
📌 <b>Nomi:</b> <i>{$name}</i>
📨 <b>Qo‘shilish so‘rovlari:</b> <b>{$requests['Total']} ta</b>
🗓 <b>Qo‘shilgan:</b> <i>{$date}</i>";
        }
        array_unshift($buttons, [['text' => $link_button_text, 'url' => "https://t.me/{$url}"]]);
    } elseif ($channel_group_link == "url") {
        $title = "🔗 <b>Havola haqida</b>";
        $body = "
🌐 <b>Havola:</b> {$full_url}
🗓 <b>Qo‘shilgan:</b> <i>{$date}</i>";
        array_unshift($buttons, [['text' => "↗️ Havolaga kirish", 'url' => $full_url]]);
    }
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "{$title}\n{$body}\n\n⚙️ Quyidagilardan birini tanlang:",
        'parse_mode' => 'html',
        'disable_web_page_preview' => true,
        'reply_markup' => json_encode(['inline_keyboard' => $buttons])
    ]);
    step("");
    exit();
}

if (isset($data) && $data == "add_channel") {
    bot('deleteMessage',[
        'chat_id' => $chat_id,
        'message_id' => $message_id,
    ]);
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' => "<b>⚙️ Majburiy obuna turini tanlang:</b>\n\nQuyidagi variantlardan birini tanlang:",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "📢 Kanal", 'callback_data' => "add_type-channel"], ['text' => "👥 Guruh", 'callback_data' => "add_type-group"]],
                [['text' => "🌐 Havola", 'callback_data' => "add_type-url"]],
                [['text' => "⏪ Orqaga", 'callback_data' => "channels"]],
            ]
        ])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "add_type") {
    $type = explode("-", $data)[1];
    bot('deleteMessage', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
    ]);
    if ($type == "channel") {
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "📢 <b>Kanal turini tanlang:</b>\n\n" .
                     "🔹 <b>Omaviy</b>\n<i>Telegram qidiruvida chiqadigan, foydalanuvchi nomi bo‘lgan kanallar.</i>\n\n" .
                     "🔸 <b>Shaxsiy</b>\n<i>Faqat shaxsiy havola orqali kirib bo‘ladigan kanallar.</i>\n\n" .
                     "🔐 <b>So'rovli</b>\n<i>Faqatgina qo‘shilish so‘rovi yuboriladigan kanallarni qo‘shishingiz mumkin.</i>",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => "💬 Omaviy", 'callback_data' => "add_channel-default_channel"], ['text' => "👤 Shaxsiy", 'callback_data' => "add_channel-personal_channel"]],
                    [['text' => "🔐 So'rovli", 'callback_data' => "add_channel-request_channel"]],
                    [['text' => "⏪ Orqaga", 'callback_data' => "add_channel"]],
                ],
            ]),
        ]);   
        step("");
    } else if ($type == "group") {
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "👥 <b>Guruh turini tanlang:</b>\n\n" .
                     "🔹 <b>Omaviy</b>\n<i>Telegram qidiruvida chiqadigan, foydalanuvchi nomi bo‘lgan guruhlar.</i>\n\n" .
                     "🔸 <b>Shaxsiy</b>\n<i>Faqat shaxsiy havola orqali kirib bo‘ladigan guruhlar.</i>\n\n" .
                     "🔐 <b>So'rovli</b>\n<i>Faqatgina qo‘shilish so‘rovi yuboriladigan guruhlarni qo‘shishingiz mumkin.</i>",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => "💬 Omaviy", 'callback_data' => "add_channel-default_group"], ['text' => "👤 Shaxsiy", 'callback_data' => "add_channel-personal_group"]],
                    [['text' => "🔐 So'rovli", 'callback_data' => "add_channel-request_group"]],
                    [['text' => "⏪ Orqaga", 'callback_data' => "add_channel"]],
                ],
            ]),
        ]);   
        step("");
    } else if ($type == "url"){
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "<b>🔗 <u>Havola kiriting:</u></b>\n\n" .
                      "<i>Masalan:</i> <code>https://site.com</code> yoki <code>https://t.me/kanal</code>\n\n" .
                      "Iltimos, yuqoridagi kabi to'g'ri formatda havolani kiriting.",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel,
        ]);
        step("add_channel-url");
    }
    exit();
}

if (isset($data) && explode("-", $data)[0] == "add_channel") {
    $type = explode("-", $data)[1];
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    if ($type == "default_channel" || $type == "personal_channel" || $type == "request_channel") { 
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "<b>📩 Botga qo‘shmoqchi bo‘lgan kanaldan xohlagan postingizni yuboring!</b>\n\nKanaldagi istalgan postni tanlab, shu botga yuboring.",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel,
        ]);
        step("add_channel-$type");
    } else if ($type == "default_group" || $type == "personal_group" || $type == "request_group"){
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "👥 <b>Qo‘shmoqchi bo‘lgan guruhga botni admin qiling va <code>/add</code> buyrug‘ini yuboring!</b>",
            'parse_mode' => 'HTML',
            'reply_markup' => $Bpanel,
        ]);
        step("add_group-$type");  
        exit();
    }
    exit();
}

if (explode("-", $user['step'])[0] == "add_group" && $type !== "private" && ($text == "/add@" . getMe()->username || $text == "/add")) {
    $type = explode("-", $user['step'])[1];
    if ($type == "default_group" || $type == "personal_group") {
        $status = bot('getChatMember', [
            'chat_id' => $chat_id,
            'user_id' => getMe()->id
        ]) -> result -> status;  
        bot('deleteMessage',[
            'chat_id' => $chat_id,
            'message_id' => $message_id,
        ]);
        if ($status == "administrator") {
            $channel = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `channels` WHERE `channel_id` = '{$chat_id}'"));
            if (empty($channel['id'])) {
                bot('sendMessage', [
                    'chat_id' => $from_id,
                    'text' => "<b>✅ Guruh muvaffaqiyatli qo‘shildi!</b>",
                    'parse_mode' => 'HTML',
                    'reply_markup' => $panel,
                ]);
                $mambers = bot('getChatMembersCount',['chat_id' => $chat_id])->result;
                $name = base64_encode(bot('getChat',['chat_id' => $chat_id])->result->title);
                $username = bot('getChat',['chat_id' => $chat_id])->result->username;
                $invite_link = bot('getChat',['chat_id' => $chat_id])->result->invite_link;
                $url = ($username) ? "https://t.me/$username" : $invite_link;
                $type = explode("_", $type)[0];
                mysqli_query($connect,"INSERT INTO `channels`(`channel_id`, `url`, `name`, `members`, `channel_group_link`, `type`, `date`, `status`) VALUES ('$chat_id', '$url', '$name', '$mambers', 'group', '$type', '{$time}', 'on');");
                step("");
            } else {
                bot('sendMessage', [
                    'chat_id' => $from_id,
                    'text' => "<b>⚠️ Ushbu guruh allaqachon qo'shilgan!</b>",
                    'parse_mode' => 'HTML',
                ]);
            }
        } else {
            bot('sendMessage', [
                'chat_id' => $from_id,
                'text' => "<b>⚠️ Bot guruhda admin emas!</b>",
                'parse_mode' => 'HTML',
            ]);
        }
    } else if ($type == "request_group") {
        $status = bot('getChatMember', [
            'chat_id' => $chat_id,
            'user_id' => getMe()->id
        ]) -> result -> status;  
        bot('deleteMessage',[
            'chat_id' => $chat_id,
            'message_id' => $message_id,
        ]);
        if ($status == "administrator") {
            $channel = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `channels` WHERE `channel_id` = '{$chat_id}'"));
            if (empty($channel['id'])) {
                bot('SendMessage',[
                    'chat_id' => $from_id,
                    'text' =>  "<b>⚠️ Qabul qilindi!</b> \n\n<b>🔗 Zayavka havolasini kiriting:</b>\n\nNamuna: https://t.me/+5CFhgWa_4viYyrNGVi",
                    'parse_mode' => 'html',
                    'reply_markup' => $Bpanel,
                ]);
                mysqli_query($connect, "UPDATE `users` SET `step` = 'request_url=request_group=$chat_id' WHERE `user_id` = '{$from_id}'");
            } else {
                bot('sendMessage', [
                    'chat_id' => $from_id,
                    'text' => "<b>⚠️ Ushbu guruh allaqachon qo'shilgan!</b>",
                    'parse_mode' => 'HTML',
                ]);
            }
        } else {
            bot('sendMessage', [
                'chat_id' => $from_id,
                'text' => "<b>⚠️ Bot guruhda admin emas!</b>",
                'parse_mode' => 'HTML',
            ]);
        }
    }
    step("");  
    exit();
}

if (isset($user['step']) && explode("-", $user['step'])[0] == "add_channel") {
    $type = explode("-", $user['step'])[1];
    if ($type == "default_channel" || $type == "personal_channel") { 
        if (getAdmin($forward_id)) {
            $channel = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `channels` WHERE `channel_id` = '$forward_id'"));
            if (!$channel['id']) {
                bot('SendMessage',[
                    'chat_id' => $chat_id,
                    'text' => "<b>✅ Kanal muvaffaqiyatli qo‘shildi!</b>",
                    'parse_mode' => 'html',
                    'reply_markup' => $panel,
                ]);
                $mambers = bot('getChatMembersCount',['chat_id' => $forward_id])->result;
                $name = base64_encode(bot('getChat',['chat_id' => $forward_id])->result->title);
                $username = bot('getChat',['chat_id' => $forward_id])->result->username;
                $invite_link = bot('getChat',['chat_id' => $forward_id])->result->invite_link;
                $url = ($username) ? "https://t.me/$username" : $invite_link;
                $type = explode("_", $type)[0];
                mysqli_query($connect,"INSERT INTO `channels`(`channel_id`, `url`, `name`, `members`, `channel_group_link`, `type`, `date`, `status`) VALUES ('$forward_id', '$url', '$name', '$mambers', 'channel', '$type', '{$time}', 'on');");
                step("");
            } else {
                bot('SendMessage',[
                    'chat_id' => $chat_id,
                    'text' =>  "<b>⚠️ Ushbu kanal oldin botga qo'shilgan!</b> \n\n<i>Boshqa kanal kiriting.</i>",
                    'parse_mode' => 'html',
                    'reply_markup' => $Bpanel,
                ]);
            }
        } else {
            bot('SendMessage',[
                'chat_id' => $chat_id,
                'text' =>  "<b>⚠️ Bot ushbu kanalda admin emas!</b> \n\n<i>Admin qilib qayta urinib ko'ring</i>",
                'parse_mode' => 'html',
                'reply_markup' => $Bpanel,
            ]);
        }
    } else if ($type == "request_channel") { 
        if (getAdmin($forward_id)) {
            $channel = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `channels` WHERE `channel_id` = '$forward_id'"));
            if (!$channel['id']) {
                bot('SendMessage',[
                    'chat_id' => $chat_id,
                    'text' =>  "<b>⚠️ Qabul qilindi!</b> \n\n<b>🔗 Zayavka havolasini kiriting:</b>\n\nNamuna: https://t.me/+5CFhgWa_4viYyrNGVi",
                    'parse_mode' => 'html',
                    'reply_markup' => $Bpanel,
                ]);
                step("request_url=request_channel=$forward_id");
            } else {
                bot('SendMessage',[
                    'chat_id' => $chat_id,
                    'text' =>  "<b>⚠️ Ushbu kanal oldin botga qo'shilgan!</b> \n\n<i>Boshqa kanal kiriting.</i>",
                    'parse_mode' => 'html',
                    'reply_markup' => $Bpanel,
                ]);
            }
        } else {
            bot('SendMessage',[
                'chat_id' => $chat_id,
                'text' =>  "<b>⚠️ Bot ushbu kanalda admin emas!</b> \n\n<i>Admin qilib qayta urinib ko'ring</i>",
                'parse_mode' => 'html',
                'reply_markup' => $Bpanel,
            ]);
        } 
    } else if ($type == "url") {
        if (isURL($text)) {
            bot('SendMessage',[
                'chat_id' => $chat_id,
                'text' =>  "<b>✅ Havola qo'shildi!</b>",
                'parse_mode' => 'html',
                'reply_markup' => $panel,
            ]);
            mysqli_query($connect,"INSERT INTO `channels`(`channel_id`, `url`, `name`, `members`, `channel_group_link`, `type`, `date`, `status`) VALUES ('', '$text', '', '', 'url', 'url', '$time', 'on');");
            step("");   
        } else {
            bot('SendMessage',[
                'chat_id' => $chat_id,
                'text' => "<b>🔗 <u>Havola kiriting:</u></b>\n\n" .
                          "<i>Masalan:</i> <code>https://site.com</code> yoki <code>https://t.me/kanal</code>\n\n" .
                          "Iltimos, yuqoridagi kabi to'g'ri formatda havolani kiriting.",
                'parse_mode' => 'html',
                'reply_markup' => $Bpanel,
            ]);
        }
    }
    exit();
}

if (isset($user['step']) && explode("=", $user['step'])[0] == "request_url") {
    $type = explode("=", $user['step'])[1];
    $id = explode("=", $user['step'])[2];
    if ($type == "request_channel") {
        if (isURL($text)) {
            bot('SendMessage',[
                'chat_id' => $chat_id,
                'text' =>  "<b>✅ Kanal qo'shildi!</b>",
                'parse_mode' => 'html',
                'reply_markup' => $panel,
            ]);
            $mambers = bot('getChatMembersCount', ['chat_id'=>$id])->result;
            $name = base64_encode(bot('getChat', ['chat_id'=>$id])->result->title);
            mysqli_query($connect,"INSERT INTO `channels`(`channel_id`, `url`, `name`, `members`, `channel_group_link`, `type`, `date`, `status`) VALUES ('$id', '$text', '$name', '$mambers', 'channel', 'request', '{$time}', 'on');");
            mysqli_query($connect,"DELETE FROM `zayavka` WHERE `chat_id` = '{$id}'");
        step("");
        } else {
            bot('SendMessage',[
                'chat_id' => $chat_id,
                'text' =>  "<b>⚠️ Havola noto'g'ri kiritilgan!</b>",
                'parse_mode' => 'html',
                'reply_markup' => $Bpanel,
            ]);
        }
    } else if ($type == "request_group") {
        if (isURL($text)) {
            bot('SendMessage',[
                'chat_id' => $chat_id,
                'text' =>  "<b>✅ Guruh qo'shildi!</b>",
                'parse_mode' => 'html',
                'reply_markup' => $panel,
            ]);
            $mambers = bot('getChatMembersCount', ['chat_id'=>$id])->result;
            $name = base64_encode(bot('getChat', ['chat_id'=>$id])->result->title);
            mysqli_query($connect,"INSERT INTO `channels`(`channel_id`, `url`, `name`, `members`, `channel_group_link`, `type`, `date`, `status`) VALUES ('$id', '$text', '$name', '$mambers', 'group', 'request', '{$time}', 'on');");
            mysqli_query($connect,"DELETE FROM `zayavka` WHERE `chat_id` = '{$id}'");
            step("");
        } else {
            bot('SendMessage',[
                'chat_id' => $chat_id,
                'text' =>  "<b>⚠️ Havola noto'g'ri kiritilgan!</b>",
                'parse_mode' => 'html',
                'reply_markup' => $Bpanel,
            ]);
        }
    }
    exit();
}

if (isset($text) && $text == "🎬 Kinolar" && ($chat_id == $admin || user($chat_id)['isAdmin'])) {
    if ($chat_id == $admin || user($chat_id)['movies']) {
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>🎬 Kinolar bo‘limidasiz:</b>\n\nQuyidagi amallardan birini tanlang:",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'resize_keyboard' => true,
                'keyboard' => [
                    [['text' => "📥 Kino yuklash"]],
                    [['text' => "📝 Kino tahrirlash"], ['text' => "🗑 Kino o‘chirish"]],
                    [['text' => "🗄️ Boshqaruv"]],
                ]
            ])
        ]);
    } else {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>🚫 Sizda ushbu bo'limga kirish uchun ruxsat yo‘q!</b>",
            'parse_mode' => "html",
        ]);
    }
    step("");
    exit();
}

if (isset($text) && $text == "📥 Kino yuklash" && ($chat_id == $admin || user($chat_id)['movies'])) {
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' => "<b>🔢 Kino qaysi kodga yuklansin? \n\nKodni kiriting:</b>",
        'parse_mode' => 'html',
        'reply_markup' => $Bpanel
    ]);
    mysqli_query($connect, "DELETE FROM `download`");
    step("code");
    exit();
}

if (isset($user['step']) && $user['step'] == "code" && ($chat_id == $admin || user($chat_id)['movies'])) {
    if (is_numeric($text)) {
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "<b>🔢 “{$text}” kodi qabul qilindi.\n\n🎥 Endi yuklamoqchi bo‘lgan kinoni kiriting:</b>",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
        mysqli_query($connect, "DELETE FROM `download`");
        step("movie-$text");
    } else {
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "<b>⚠️ Kino kodi noto‘g‘ri formatda kiritildi.\n\nFaqat raqam kiriting.</b>",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
    }
    exit();
}

if (isset($user['step']) && explode("-", $user['step'])[0] == "movie" && ($chat_id == $admin || user($chat_id)['movies'])) {
    $code = explode("-", $user['step'])[1];
    if (isset($video)) {
        bot('sendVideo',[
            'chat_id' => $chat_id,
            'video' => $video_id,
            'caption' => "<b>🎞 Kino yuklash jarayoni</b>\n\n" .
                         "<b>🔎 Kino kodi:</b> <code>$code</code>\n\n" .
                         "<blockquote>🔓 <b>Hammaga yuklash</b> — Kinoni barcha foydalanuvchilar ko‘ra oladi.\n" .
                         "💎 <b>Faqat Premium</b> — Kinoni faqat premium obunasiga ega foydalanuvchilar ko‘ra oladi.</blockquote>",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => "➕ Nom kiritish", 'callback_data' => "movie_name-$code"]],
                    [['text' => "📥 Yuklash: 🔓 Hammaga", 'callback_data' => "movie_save-$code-all"]],
                    [['text' => "📥 Yuklash: 💎 Premium", 'callback_data' => "movie_save-$code-premium"]],
            ]])
        ]);
        mysqli_query($connect,"INSERT INTO `download`(`id`, `file_id`, `file_name`, `name`, `description`) VALUES ('1', '{$video_id}', '', '', '');");
        step("");
    } else {
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "🎥 <b>Yuklamoqchi bo‘lgan kinoni kiriting:</b>",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
    }
    exit();
}

if (isset($data) && explode("-", $data)[0] == "movie_name" && ($chat_id == $admin || user($chat_id)['movies'])) {
    $code = explode("-", $data)[1];
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' => "<b>📝 Kino nomini kiriting:</b>",
        'parse_mode' => 'html',
        'reply_markup' => $Bpanel
    ]);
    step("movie_name-$code");
    exit();
}

if (isset($user['step']) && explode("-", $user['step'])[0] == "movie_name") {
    $code = explode("-", $user['step'])[1];
    $download = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `download` WHERE `id` = '1'"));
    $file_id = $download['file_id'];
    bot('sendVideo',[
        'chat_id' => $chat_id,
        'video' => $file_id,
        'caption' => "<b>🎞 Kino yuklash jarayoni</b>\n\n" . 
                     "<b>🔎 Kino kodi:</b> <code>$code</code>\n\n" .
                     "<b>🎬 Nomi:</b> {$text}\n\n" .
                     "<blockquote>🔓 <b>Hammaga yuklash</b> — Kinoni barcha foydalanuvchilar ko‘ra oladi.\n" .
                     "💎 <b>Faqat Premium</b> — Kinoni faqat premium obunasiga ega foydalanuvchilar ko‘ra oladi.</blockquote>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "➕ Ma'lumot kiritish", 'callback_data' => "movie_description-$code"]],
                [['text' => "📥 Yuklash: 🔓 Hammaga", 'callback_data' => "movie_save-$code-all"]],
                [['text' => "📥 Yuklash: 💎 Premium", 'callback_data' => "movie_save-$code-premium"]],
        ]])
    ]);
    $text = mysqli_real_escape_string($connect, $text);
    mysqli_query($connect, "UPDATE `download` SET `name` = '{$text}' WHERE `id` = '1'");
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "movie_description" && ($chat_id == $admin || user($chat_id)['movies'])) {
    $code = explode("-", $data)[1];
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' => "<b>📝 Kino ma'lumotini kiriting:</b>",
        'parse_mode' => 'html',
        'reply_markup' => $Bpanel
    ]);
    step("movie_description-$code");
    exit();
}

if (isset($user['step']) && explode("-", $user['step'])[0] == "movie_description") {
    $code = explode("-",  $user['step'])[1];
    $download = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `download` WHERE `id` = '1'"));
    $file_id = $download['file_id'];
    bot('sendVideo',[
        'chat_id' => $chat_id,
        'video' => $file_id,
        'caption' => "<b>🎞 Kino yuklash jarayoni</b>\n\n" . 
                     "<b>🔎 Kino kodi:</b> <code>$code</code>\n\n" .
                     "<b>🎬 Nomi:</b> {$download['name']}\n\n" .
                     "📝 <b>Ma'lumoti:</b>\n" .
                     "<blockquote>$text</blockquote>\n\n" .
                     "<blockquote>🔓 <b>Hammaga yuklash</b> — Kinoni barcha foydalanuvchilar ko‘ra oladi.\n" .
                     "💎 <b>Faqat Premium</b> — Kinoni faqat premium obunasiga ega foydalanuvchilar ko‘ra oladi.</blockquote>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "📥 Yuklash: 🔓 Hammaga", 'callback_data' => "movie_save-$code-all"]],
                [['text' => "📥 Yuklash: 💎 Premium", 'callback_data' => "movie_save-$code-premium"]],
        ]])
    ]);
    $text = mysqli_real_escape_string($connect, $text);
    mysqli_query($connect, "UPDATE `download` SET `description` = '{$text}' WHERE `id` = '1'");
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "movie_save") {
    $code = explode("-", $data)[1];
    $status = explode("-", $data)[2];
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' =>  ⏳,
        'parse_mode' => 'html',
    ]);
    $download = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `download` WHERE `id` = '1'"));
    $file_id = $download['file_id'];
    $movie_name = $download['file_name'];
    $name = ($download['name']) ? $download['name'] : null;
    $description = ($download['description']) ? $download['description'] : null;
    $escape_name = mysqli_real_escape_string($connect, $name);
    $escape_description = mysqli_real_escape_string($connect, $description);
    mysqli_query($connect,"INSERT INTO `movies`(`code`, `name`, `description`, `file_id`, `status`) VALUES ('{$code}', '{$escape_name}', '{$escape_description}', '{$file_id}', '{$status}');");
    $movie_name = ($download['name']) ? "<b>🎬 Nomi:</b> " . $download['name'] : "";
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id + 1,
    ]);
    bot('sendVideo',[
        'chat_id' => $chat_id,
        'video' => $file_id,
        'caption' => "<b>✅ Kino muvaffaqiyatli yuklandi!</b>\n\n<b>🔎 Kino kodi:</b> <code>$code</code> \n\n$movie_name\n\n$description",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "📥 Yana Kino Yuklash", 'callback_data' => "movie_downlod-$code"]],
        ]])
    ]);
    mysqli_query($connect,"DELETE FROM `download`");
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "movie_downlod" && ($chat_id == $admin || user($chat_id)['movies'])) {
    $code = explode("-", $data)[1];
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' => "<b>🎥 Yuklamoqchi bo‘lgan kinoni kiriting:</b>",
        'parse_mode' => 'html',
        'reply_markup' => $Bpanel
    ]);
    mysqli_query($connect, "DELETE FROM `download`");
    step("movie-$code");
    exit();
}

if (isset($text) && $text == "📝 Kino tahrirlash" && ($chat_id == $admin || user($chat_id)['movies'])) {
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' =>  "<b>📝 Tahrirlamoqchi bo'lgan kino kodini kiriting:</b>",
        'parse_mode' => 'html',
        'reply_markup' => $Bpanel
    ]);
    step("movie_edit");
    exit();
}

if (isset($user['step']) && $user['step'] == "movie_edit") {
    $query = mysqli_query($connect, "SELECT * FROM `movies` WHERE `code` = '{$text}'"); 
    if (mysqli_num_rows($query) > 0) {
        while ($movie = mysqli_fetch_assoc($query)) {
            $name = ($movie['name']) ? "\n\n<b>🎬 Nomi:</b> {$movie['name']}" : "";
            $description = ($movie['description']) ? "\n\n{$movie['description']}" : "";
            bot('sendVideo',[
                'chat_id' => $chat_id,
                'video' => $movie['file_id'],
                'caption' => "<b>🔎 Kino kodi:</b> <code>{$movie['code']}</code>$name$description\n\nQaysi qismini tahrirlamoqchisiz?",
                'parse_mode' => 'html',
                'reply_markup' => json_encode([
                    'inline_keyboard' => [
                        [['text' => "✏️ Kodini", 'callback_data' => "fileEdit-code-{$movie['id']}"]],
                        [['text' => "✏️ Nomini", 'callback_data' => "fileEdit-name-{$movie['id']}"], ['text' => "✏️ Ma'lumotini", 'callback_data' => "fileEdit-description-{$movie['id']}"]],
                        [['text' => ($movie['status'] == "premium" ? "💎 Premium ko‘rinish" : "🔓 Ochiq ko‘rinish"), 'callback_data' => "EditStatus-{$movie['id']}"]],
                    ]
                ])
            ]);
        }
        step("");
    } else {
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' =>  "<b>⚠️ Ushbu kodga bog'liq kino topilmadi.</b> \n\nQayta urinib ko'ring:",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
    }
    exit();
}

if (isset($data) && explode("-", $data)[0] == "EditStatus") {
    $id = explode("-", $data)[1];
    $movie = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `movies` WHERE `id` = '{$id}'")); 
    $status = ($movie['status'] == "premium") ? "all" : "premium";
    mysqli_query($connect, "UPDATE `movies` SET `status` = '{$status}' WHERE `id` = '{$id}'");
    bot('answerCallbackQuery',[
        'callback_query_id' => $qid,
        'text' => ($status == "premium") 
            ? "🎬 Holat o‘zgartirildi!\n\n💎 Kino endi faqat Premium foydalanuvchilar ko‘ra oladi."
            : "🎬 Holat o‘zgartirildi!\n\n🔓 Kino endi barcha foydalanuvchilar ko‘ra oladi.",
        'show_alert' => true,
    ]);
    bot('editMessageReplyMarkup', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "✏️ Kodini", 'callback_data' => "fileEdit-code-{$movie['id']}"]],
                [['text' => "✏️ Nomini", 'callback_data' => "fileEdit-name-{$movie['id']}"], ['text' => "✏️ Ma'lumotini", 'callback_data' => "fileEdit-description-{$movie['id']}"]],
                [['text' => ($status == "premium" ? "💎 Premium ko‘rinish" : "🔓 Ochiq ko‘rinish"), 'callback_data' => "EditStatus-{$movie['id']}"]],
            ]
        ])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "fileEdit") {
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    $action = explode("-", $data)[1];
    $id = explode("-", $data)[2];
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' =>  "<b>📝 Yangi qiymat kiriting:</b>",
        'parse_mode' => 'html',
        'reply_markup' => $Bpanel
    ]);
    step("fileEdit-$action-$id");
}

if (isset($user['step']) && explode("-", $user['step'])[0] == "fileEdit") {
    $action = explode("-", $user['step'])[1];
    $id = explode("-", $user['step'])[2];
    if ($action == "code" && !is_numeric($text)) {
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "<b>⚠️ Raqam kiritish kerak!</b>\n\nKino kodi faqat raqamlardan iborat bo‘lishi kerak.",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
        exit();
    }
    $text = mysqli_real_escape_string($connect, $text);
    mysqli_query($connect, "UPDATE `movies` SET `$action` = '{$text}' WHERE `id` = '{$id}'");
    $movie = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `movies` WHERE `id` = '{$id}'"));
    $name = ($movie['name']) ? "\n\n<b>🎬 Nomi:</b> {$movie['name']}" : "";
    $description = ($movie['description']) ? "\n\n{$movie['description']}" : "";
    bot('sendVideo',[
        'chat_id' => $chat_id,
        'video' => $movie['file_id'],
        'caption' => "<b>🔎 Kino kodi:</b> <code>{$movie['code']}</code> $name $description \n\nQuyidagilardan qaysisini tahrirlamoqchisiz?",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "✏️ Kodini", 'callback_data' => "fileEdit-code-{$movie['id']}"]],
                [['text' => "✏️ Nomini", 'callback_data' => "fileEdit-name-{$movie['id']}"], ['text' => "✏️ Ma'lumotini", 'callback_data' => "fileEdit-description-{$movie['id']}"]],
        ]])
    ]);
    step("");
    exit();
}

if (isset($text) && $text == "🗑 Kino o‘chirish" && ($chat_id == $admin || user($chat_id)['movies'])) {
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' =>  "<b>🗑 O'chirmoqchi bo'lgan kino kodini kiriting:</b>",
        'parse_mode' => 'html',
        'reply_markup' => $Bpanel
    ]);
    step("movie_delete");
    exit();
}

if (isset($user['step']) && $user['step'] == "movie_delete") {
    $query = mysqli_query($connect, "SELECT * FROM `movies` WHERE `code` = '{$text}'"); 
    if (mysqli_num_rows($query) > 0) {
        while ($movie = mysqli_fetch_assoc($query)) {
            $name = ($movie['name']) ? "\n\n<b>🎬 Nomi:</b> {$movie['name']}" : "";
            $description = ($movie['description']) ? "\n\n{$movie['description']}" : "";
            bot('sendVideo',[
                'chat_id' => $chat_id,
                'video' => $movie['file_id'],
                'caption' => "<b>🔎 Kino kodi:</b> <code>{$movie['code']}</code>$name$description\n\nQuyidagi tugma orqali kinoni o‘chirishingiz mumkin.",
                'parse_mode' => 'html',
                   'reply_markup' => json_encode([
                        'inline_keyboard' => [
                            [['text' => "🗑 O'chirish", 'callback_data' => "file_del-{$movie['id']}"]],
                    ]])
            ]);
        }
        step("");
    } else {
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' =>  "<b>⚠️ Ushbu kodga bog'liq kino topilmadi.</b> \n\nQayta urinib ko'ring:",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
    }
    exit();
}

if (isset($data) && explode("-", $data)[0] == "file_del") {
    $id = explode("-", $data)[1];
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' =>  "<b>✅ O'chirish yakunlandi!</b>",
        'parse_mode' => 'html',
        'reply_markup' => $panel
    ]);
    mysqli_query($connect, "DELETE FROM `movies` WHERE `id` = '{$id}'");
    mysqli_query($connect, "DELETE FROM `downloads` WHERE `file_id` = '{$id}'");
    step("");
    exit();
}

if ((isset($text) || isset($data)) && ($text == "⚙️ Sozlamalar" || $data == "settings") && ($chat_id == $admin || user($chat_id)['isAdmin'])) {
    if ($chat_id == $admin || user($chat_id)['settings']) {
        $share_save_status = ($setting['share_save'] == "on") ? "✅" : "⛔️";
        bot($data ? 'editMessageText' : 'SendMessage',[
            'chat_id' => $chat_id,
            'message_id' => $message_id,
            'text' => "<b>⚙️ Sozlamalardan birini tanlang:</b>

<b>💬 Ulashishni cheklash</b>
• Foydalanuvchilarga kinoni boshqalarga yuborish yoki qurilmaga yuklab olishni taqiqlaydi.",
            'parse_mode' => 'html',
                'reply_markup' => json_encode([
                    'inline_keyboard' => [
                        [['text' => "💬 Ulashish - $share_save_status", 'callback_data' => "setting-share_save"]],
                        [['text' => "💎 Premium", 'callback_data' => "premium_settings"]],
                        [['text' => "💳 To'lov tizimlar", 'callback_data' => "payment_methods"]]
                ]])
        ]);
    } else {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>🚫 Sizda ushbu bo'limga kirish uchun ruxsat yo‘q!</b>",
            'parse_mode' => "html",
        ]);
    }
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "setting" && ($chat_id == $admin || user($chat_id)['settings'])) {
    $action = explode("-", $data)[1];
    $status = ($setting[$action] == "on") ? "off" : "on";
    mysqli_query($connect, "UPDATE `settings` SET `$action` = '$status' WHERE `id` = '1'");
    $setting = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `settings` WHERE `id` = '1'"));
    $share_save_status = ($setting['share_save'] == "on") ? "✅" : "⛔️";
    $premium_status = ($setting['premium'] == "on") ? "✅" : "⛔️";
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "<b>⚙️ Sozlamalardan birini tanlang:</b>

<b>💬 Ulashishni cheklash</b>
• Foydalanuvchilarga kinoni boshqalarga yuborish yoki qurilmaga yuklab olishni taqiqlaydi.",
            'parse_mode' => 'html',
                'reply_markup' => json_encode([
                    'inline_keyboard' => [
                        [['text' => "💬 Ulashish - $share_save_status", 'callback_data' => "setting-share_save"]],
                        [['text' => "💎 Premium", 'callback_data' => "premium_settings"]],
                        [['text' => "💳 To'lov tizimlar", 'callback_data' => "payment_methods"]]
                ]])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "premium_settings" && ($chat_id == $admin || user($chat_id)['settings'])) {
    $action = explode("-", $data)[1] ?? null;
    $premium_status = ($setting['premium'] == "on") ? "✅ Faol" : "⛔️ O‘chiq";
    $now = date("Y-m-d H:i:s");
    $total_premium = mysqli_num_rows(mysqli_query($connect, "SELECT id FROM `users` WHERE `premium` > '$now'"));
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "<b>⚙️ Premium sozlamalar bo‘limidasiz:</b>\n\n" .
                  "<b>🔹 Premium holati:</b> {$premium_status}\n" .
                  "<b>💰 Premium narxi (1 oy):</b> " . number_format($setting['premium_price'], 0, '.', ' ') . " so‘m\n" .
                  "<b>👥 Jami Premium foydalanuvchilar:</b> {$total_premium} ta\n\n" .
                  "<b>📌 Quyidagi tugmalardan foydalanib Premium sozlamalarini boshqaring.</b>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode(['inline_keyboard' => [
            [['text' => "💡 Holat o‘zgartirish", 'callback_data' => "toggle_premium"], ['text' => "✏️ Narx o‘zgartirish", 'callback_data' => "premium_price"]],
            [['text' => "👥 Premium foydalanuvchilar ro‘yxati", 'callback_data' => "premium_users"]],
            [['text' => "➕ Premium berish / Muddatni boshqarish", 'callback_data' => "give_premium"]],
            [['text' => "⏪ Orqaga", 'callback_data' => "settings"]],
        ]])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "toggle_premium" && ($chat_id == $admin || user($chat_id)['settings'])) {
    $status = ($setting['premium'] == "on") ? "off" : "on";
    mysqli_query($connect, "UPDATE `settings` SET `premium` = '$status' WHERE `id` = '1'");
    $premium_status = ($setting['premium'] == "off") ? "✅ Faol" : "⛔️ O‘chiq";
    $now = date("Y-m-d H:i:s");
    $total_premium = mysqli_num_rows(mysqli_query($connect, "SELECT id FROM `users` WHERE `premium` > '$now'"));
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "<b>⚙️ Premium sozlamalar bo‘limidasiz:</b>\n\n" .
                  "<b>🔹 Premium holati:</b> {$premium_status}\n" .
                  "<b>💰 Premium narxi (1 oy):</b> " . number_format($setting['premium_price'], 0, '.', ' ') . " so‘m\n" .
                  "<b>👥 Jami Premium foydalanuvchilar:</b> {$total_premium} ta\n\n" .
                  "<b>📌 Quyidagi tugmalardan foydalanib Premium sozlamalarini boshqaring.</b>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode(['inline_keyboard' => [
            [['text' => "💡 Holat o‘zgartirish", 'callback_data' => "toggle_premium"], ['text' => "✏️ Narx o‘zgartirish", 'callback_data' => "premium_price"]],
            [['text' => "👥 Premium foydalanuvchilar ro‘yxati", 'callback_data' => "premium_users"]],
            [['text' => "➕ Premium berish / Muddatni boshqarish", 'callback_data' => "give_premium"]],
            [['text' => "⏪ Orqaga", 'callback_data' => "settings"]],
        ]])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "premium_users") {
    $page = isset(explode("-", $data)[1]) ? (int)explode("-", $data)[1] : 1;
    $limit = 5;
    $offset = ($page - 1) * $limit;
    $now = date("Y-m-d H:i:s");
    $count_all = mysqli_num_rows(mysqli_query($connect, "SELECT id FROM `users` WHERE `premium` > '$now'"));
    $total_pages = ceil($count_all / $limit);
    $users = mysqli_query($connect, "SELECT * FROM `users` WHERE `premium` > '$now' ORDER BY id DESC LIMIT $limit OFFSET $offset");
    $i = $page - 1;
    
    if (mysqli_num_rows($users) > 0) {
        $txt = "<b>👥 Premium foydalanuvchilar ro‘yxati</b>\n\n";
        while ($user = mysqli_fetch_assoc($users)) {
            $i++;
            $currentTime = strtotime(date("Y-m-d H:i"));
            $botTime = strtotime(date("Y-m-d H:i", strtotime($user['premium'])));
            $timeDifference = $botTime - $currentTime;
            $day = floor($timeDifference / (60 * 60 * 24));
            $hour = floor(($timeDifference % (60 * 60 * 24)) / (60 * 60));
            $minute = floor(($timeDifference % (60 * 60)) / 60);
            $getChat = bot('getChat', ['chat_id' => $user['user_id']])->result;
            $first_name = isset($getChat->first_name) ? $getChat->first_name : "Noma’lum";
            $username   = isset($getChat->username) ? "@".$getChat->username : "—";
            $txt .= "👤 <b>{$i}-foydalanuvchi</b>\n";
            $txt .= "🟢 <a href='tg://user?id={$user['user_id']}'>{$first_name}</a> ";
            $txt .= "({$username})\n";
            $txt .= "🆔 <b>ID:</b> <code>{$user['user_id']}</code>\n";
            $txt .= "⏳ <b>Premium muddati:</b> {$day} kun, {$hour} soat, {$minute} daqiqa\n\n";
        }
    } else {
        $txt = "⚠️ <b>Hozircha Premium foydalanuvchilar mavjud emas.</b>";
    }
    $keyboard = [];
    $nav_buttons = [];
    if ($page > 1) {
        $nav_buttons[] = ['text' => "⏪", 'callback_data' => "premium_users-" . ($page - 1)];
    }
    if ($total_pages > 1) {
        $nav_buttons[] = ['text' => "$page / $total_pages", 'callback_data' => "noop"];
    }
    if ($page < $total_pages) {
        $nav_buttons[] = ['text' => "⏩", 'callback_data' => "premium_users-" . ($page + 1)];
    }
    if (!empty($nav_buttons)) {
        $keyboard[] = $nav_buttons;
    }
    $keyboard[] = [['text' => "⏪ Orqaga", 'callback_data' => "premium_settings"]];
    bot($text ? 'sendMessage' : 'editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => $txt,
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => $keyboard
        ]),
    ]);
    step("");
    exit();
}

if ($data == "give_premium") {
    bot($text ? 'sendMessage' : 'editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "<b>🔎 Premium boshqarish uchun foydalanuvchi ID raqamini kiriting:</b>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode(['inline_keyboard' => [
            [['text' => "⏪ Orqaga", 'callback_data' => "premium_settings"]],
        ]])
    ]);
    step("premium_user_search");
    exit();
}

if ($user['step'] == "premium_user_search") {
    $userid = trim($text);
    $user = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `users` WHERE `user_id` = '{$userid}'"));
    if (!$user) {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "❌ Bunday foydalanuvchi topilmadi. Qayta urinib ko'ring."
        ]);
        exit();
    }
    $premium = $user['premium'];
    $status = ($premium > date("Y-m-d H:i:s")) ? "♻️ Faol" : "⛔️ Yo'q";
    $currentTime = strtotime(date("Y-m-d H:i"));
    $botTime = strtotime(date("Y-m-d H:i", strtotime($user['premium'])));
    $timeDifference = $botTime - $currentTime;
    $day = floor($timeDifference / (60 * 60 * 24));
    $hour = floor(($timeDifference % (60 * 60 * 24)) / (60 * 60));
    $minute = floor(($timeDifference % (60 * 60)) / 60);
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "👤 <b>Foydalanuvchi topildi:</b>\n\n"
                . "🆔 <b>ID:</b> $userid\n"
                . "🌟 <b>Premium:</b> $status\n"
                . (($premium > date("Y-m-d H:i:s")) ? "⏳ <b>Muddat:</b> {$day} kun, {$hour} soat, {$minute} daqiqa" : ""),
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "➕ Premium berish / uzaytirish", 'callback_data' => "premium_add:$userid"]],
                [['text' => "➖ Kamaytirish", 'callback_data' => "premium_reduce:$userid"]],
                [['text' => "❌ Premiumni o‘chirish", 'callback_data' => "premium_remove:$userid"]],
            ]
        ])
    ]);
    step("");
    exit();
}

if (explode("-", $data)[0] == "premium_user") {
    $userid = explode("-", $data)[1];
    $user = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `users` WHERE `user_id` = '{$userid}'"));
    if (!$user) {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "❌ Bunday foydalanuvchi topilmadi. Qayta urinib ko'ring."
        ]);
        exit();
    }
    $premium = $user['premium'];
    $status = ($premium > date("Y-m-d H:i:s")) ? "♻️ Faol" : "⛔️ Yo'q";
    $currentTime = strtotime(date("Y-m-d H:i"));
    $botTime = strtotime(date("Y-m-d H:i", strtotime($user['premium'])));
    $timeDifference = $botTime - $currentTime;
    $day = floor($timeDifference / (60 * 60 * 24));
    $hour = floor(($timeDifference % (60 * 60 * 24)) / (60 * 60));
    $minute = floor(($timeDifference % (60 * 60)) / 60);
    bot($text ? 'sendMessage' : 'editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "👤 <b>Foydalanuvchi topildi:</b>\n\n"
                . "🆔 <b>ID:</b> $userid\n"
                . "🌟 <b>Premium:</b> $status\n"
                . (($premium > date("Y-m-d H:i:s")) ? "⏳ <b>Muddat:</b> {$day} kun, {$hour} soat, {$minute} daqiqa" : ""),
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "➕ Premium berish / uzaytirish", 'callback_data' => "premium_add:$userid"]],
                [['text' => "➖ Kamaytirish", 'callback_data' => "premium_reduce:$userid"]],
                [['text' => "❌ Premiumni o‘chirish", 'callback_data' => "premium_remove:$userid"]],
            ]
        ])
    ]);
    step("");
    exit();
}

if (explode(":", $data)[0] == "premium_add") {
    $userid = explode(":", $data)[1];
    bot($text ? 'sendMessage' : 'editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "📅 <b>Necha kun qo‘shmoqchisiz?</b>\n\n<b>Masalan:</b> 30",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "⏪ Orqaga", 'callback_data' => "premium_user-$userid"]],
            ]
        ])
    ]);
    step("premium_add_days-$userid");
    exit();
}

if ($user['step'] && explode("-", $user['step'])[0] == "premium_add_days") {
    $userid = explode("-", $user['step'])[1];
    $days = trim($text);
    if (!is_numeric($days) || $days < 1) {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "⚠️ Iltimos, to‘g‘ri kun kiriting. Masalan: 30"
        ]);
        exit();
    }
    $user = mysqli_fetch_assoc(mysqli_query($connect, "SELECT `premium` FROM `users` WHERE `user_id` = '{$userid}'"));
    $premium = $user['premium'];
    $now = date("Y-m-d H:i");
    if ($premium > $now) {
        $new = date("Y-m-d H:i", strtotime("$premium +$days days"));
    } else {
        $new = date("Y-m-d H:i", strtotime("+$days days"));
    }
    mysqli_query($connect, "UPDATE `users` SET `premium` = '{$new}' WHERE `user_id` = '{$userid}'");
    $currentTime = strtotime(date("Y-m-d H:i"));
    $botTime = strtotime(date("Y-m-d H:i", strtotime($new)));
    $timeDifference = $botTime - $currentTime;
    $day = floor($timeDifference / (60 * 60 * 24));
    $hour = floor(($timeDifference % (60 * 60 * 24)) / (60 * 60));
    $minute = floor(($timeDifference % (60 * 60)) / 60);
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "✅ <b>$days kunlik Premium qo‘shildi!</b>\n\n⏳ <b>Yangi muddat:</b> {$day} kun, {$hour} soat, {$minute} daqiqa", 
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "⏪ Orqaga", 'callback_data' => "premium_user-$userid"]],
            ]
        ])
    ]);
    step("");
    exit();
}

if (explode(":", $data)[0] == "premium_reduce") {
    $userid = explode(":", $data)[1];
    bot($text ? 'sendMessage' : 'editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "📅 <b>Necha kun ayirmoqchisiz?</b>\n\n<b>Masalan:</b> 15",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "⏪ Orqaga", 'callback_data' => "premium_user-$userid"]],
            ]
        ])
    ]);
    step("premium_reduce_days-$userid");
    exit();
}

if ($user['step'] && explode("-", $user['step'])[0] == "premium_reduce_days") {
    $userid = explode("-", $user['step'])[1];
    $days = trim($text);
    if (!is_numeric($days) || $days < 1) {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "⚠️ Iltimos, to‘g‘ri kun kiriting. Masalan: 15"
        ]);
        exit();
    }
    $user = mysqli_fetch_assoc(mysqli_query($connect, "SELECT `premium` FROM `users` WHERE `user_id` = '{$userid}'"));
    $premium = $user['premium'];
    $new = date("Y-m-d H:i", strtotime("$premium -$days days"));
    mysqli_query($connect, "UPDATE `users` SET `premium` = '{$new}' WHERE `user_id` = '{$userid}'");
    $currentTime = strtotime(date("Y-m-d H:i"));
    $botTime = strtotime(date("Y-m-d H:i", strtotime($new)));
    $timeDifference = $botTime - $currentTime;
    $day = floor($timeDifference / (60 * 60 * 24));
    $hour = floor(($timeDifference % (60 * 60 * 24)) / (60 * 60));
    $minute = floor(($timeDifference % (60 * 60)) / 60);
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "➖ <b>Premium muddati $days kun kamaytirildi.</b>\n\n⏳ <b>Yangi muddat:</b> {$day} kun, {$hour} soat, {$minute} daqiqa", 
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "⏪ Orqaga", 'callback_data' => "premium_user-$userid"]],
            ]
        ])
    ]);
    step("");
    exit();
}

if ($data && explode(":", $data)[0] == "premium_remove") {
    $userid = explode(":", $data)[1];
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "❌ <b>Premiumni olib tashlashni tasdiqlaysizmi?</b>\n\n🆔 <b>Foydalanuvchi:</b> <code>$userid</code>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "❌ Ha, o‘chirish", 'callback_data' => "premium_remove_confirm:$userid"]],
                [['text' => "⏪ Orqaga", 'callback_data' => "premium_user-$userid"]],
            ]
        ])
    ]);
    step("");
    exit();
}

if ($data && explode(":", $data)[0] == "premium_remove_confirm") {
    $userid = explode(":", $data)[1];
    mysqli_query($connect, "UPDATE `users` SET `premium` = '' WHERE `user_id` = '{$userid}'");
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "❌ <b>Premium o‘chirildi!</b>\n\n🆔 <b>Foydalanuvchi:</b> <code>$userid</code>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [
                    ['text' => "⏪ Orqaga", 'callback_data' => "premium_user-$userid"],
                ]
            ]
        ])
    ]);
    step("");
    exit();
}

if (isset($data) && $data == "premium_price") {
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "<b>📝 Yangi qiymat kiriting:</b>",
        'parse_mode' => "html",
        'reply_markup' => json_encode(['inline_keyboard' => [
            [['text' => "⏪ Orqaga", 'callback_data' => "premium_settings"]],
        ]])
    ]);
    step("premium_price");
    exit();
}

if (isset($user['step']) && $user['step'] == "premium_price" && is_numeric($text)) {
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "<b>✅ Qabul qilindi!</b>",
        'parse_mode' => "html",
        'reply_markup' => json_encode(['inline_keyboard' => [
            [['text' => "⏪ Orqaga", 'callback_data' => "premium_settings"]],
        ]])
    ]);
    mysqli_query($connect,"UPDATE `settings` SET `premium_price` = '$text' WHERE `id` = '1'");
    step("");
    exit();
}

if (isset($data) && $data == "payment_methods" && ($chat_id == $admin || user($chat_id)['settings'])) {
    $get = mysqli_query($connect, "SELECT * FROM `pay_methods`");
    $count = 0;
    $key = [];
    while ($payment = mysqli_fetch_assoc($get)) {
        $count++;
        $key[] = ['text' => $payment['name'], 'callback_data' => "payment-" . $payment['id']];
    }
    $keyboard = array_chunk($key, 1);
    $keyboard[] = [['text' => "➕ To'lov tizimi qo'shish", 'callback_data' => "addpayment"]];
    $keyboard[] = [['text' => "⏪ Orqaga", 'callback_data' => "settings"]];
    $button = json_encode(['inline_keyboard' => $keyboard]);
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => ($count > 0) ? "<b>💳 To'lov tizimlari:</b> $count ta" : "<b>⚠️ To'lov tizimlari mavjud emas.</b>",
        'parse_mode' => 'html',
        'reply_markup' => $button,
    ]);
    step("");
    exit();
}

if (isset($data) && stripos($data, "payment-") !== false) {
    $id = explode("-", $data)[1];
    $paymentQuery = mysqli_query($connect, "SELECT * FROM `pay_methods` WHERE `id` = '$id'");
    $payment = mysqli_fetch_assoc($paymentQuery);
    if (!$payment) {
        bot('editMessageText', [
            'chat_id' => $chat_id,
            'message_id' => $message_id,
            'text' => "<b>⚠️ Xatolik yuz berdi! To'lov tizimi topilmadi.</b>",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => "⏪ Orqaga", 'callback_data' => "payment_methods"]],
                ]
            ])
        ]);
        exit();
    }
    $owner = ($payment['owner']) ? "\n\n👤 <b>Hisob egasi:</b> {$payment['owner']}" : "";
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => 
            "💳 <b>To‘lov tizimi:</b> {$payment['name']} $owner\n\n" .
            "🔢 <b>Raqam:</b> <code>{$payment['code']}</code>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "⏪ Orqaga", 'callback_data' => "payment_methods"],
                  ['text' => "🗑 O'chirish", 'callback_data' => "dlpymnt-{$payment['id']}"]],
            ]
        ])
    ]);
    step("");
    exit();
}

if (isset($data) && stripos($data, "dlpymnt-") !== false) {
    $id = explode("-", $data)[1];
    $paymentQuery = mysqli_query($connect, "SELECT * FROM `pay_methods` WHERE `id` = '$id'");
    $payment = mysqli_fetch_assoc($paymentQuery);
    bot('deleteMessage', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
    ]);
    if ($payment) {
        mysqli_query($connect, "DELETE FROM `pay_methods` WHERE `id` = '$id'");
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>✅ To'lov tizmi muvaffaqiyatli o'chirildi!</b>",
            'parse_mode' => 'html',
            'reply_markup' => $panel
        ]);
    } else {
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>⚠️ Xatolik: To'lov tizimi topilmadi.</b>",
            'parse_mode' => 'html',
            'reply_markup' => $panel
        ]);
    }
    step("");
    exit();
}

if (isset($data) && $data == "addpayment") {
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    bot('SendMessage',[
        'chat_id' => $chat_id,
        'text' => "📝 <b>Iltimos, to‘lov tizimi nomini kiriting:</b>\n\n<i>(Masalan: Click, Payme, Humo, Uzcard...)</i>",
        'parse_mode' => 'html',
        'reply_markup' => $Bpanel,
    ]);
    step("paymentname");
    exit();
}

if (isset($user['step']) && $user['step'] == "paymentname") {
    $count = strlen(trim($text));
    if ($count <= 30) {
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "🔢 <b>Iltimos, to‘lov tizimi raqamini kiriting:</b>\n\n<i>(Masalan: karta yoki hisob raqami)</i>",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel,
        ]);
        $name = base64_encode($text);
        step("paymencode=$name");
    } else {
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "⚠️ <b>Xatolik:</b> To‘lov tizimi nomi <u>30 belgidan oshmasligi</u> kerak. Iltimos, qisqaroq nom kiriting.",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
    }
    exit();
}

if (isset($user['step']) && explode("=", $user['step'])[0] == "paymencode") {
    $name = explode("=", $user['step'])[1];
    $count = strlen(trim($text));
    if ($count <= 50) {
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "👤 <b>Hisob raqami egasining to‘liq ismini kiriting:</b>\n\n<i>(Masalan: Ism Familiya)</i>",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'resize_keyboard' => true,
                    'keyboard' => [
                        [['text' => "❌ Kiritilmasin"]],
                        [['text' => "🗄️ Boshqaruv"]],
            ]]),
        ]);
        $code = base64_encode($text);
        step("paymentadded=$name=$code");
    } else {
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>⚠️ To'lov tizim raqamini 50 belgidan ko'p bo'lishi mumkin emas.</b>",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
    }
    exit();
}

if (isset($user['step']) && explode("=", $user['step'])[0] == "paymentadded") {
    $name = explode("=", $user['step'])[1];
    $code = explode("=", $user['step'])[2];
    if ($count <= 400) {
        bot('SendMessage',[
            'chat_id' => $chat_id,
            'text' => "<b>✅ To'lov tizimi qo'shildi!</b>",
            'parse_mode' => 'html',
            'reply_markup' => $panel,
        ]);
        $name = mysqli_real_escape_string($connect, base64_decode($name));
        $owner = ($text != "❌ Kiritilmasin") ? mysqli_real_escape_string($connect, $text) : "";
        $code = mysqli_real_escape_string($connect, base64_decode($code));
        mysqli_query($connect,"INSERT INTO `pay_methods`(`name`, `owner`, `code`) VALUES ('{$name}', '{$owner}', '{$code}');");
    } else {
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>⚠️ To'lov tizim malumoti 400 belgidan ko'p bo'lishi mumkin emas.</b>",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
    }
    step("");
    exit();
}

if ((isset($text) || isset($data)) && ($text == "👮‍♀️ Adminlar" || $data == "admins") && ($chat_id == $admin || user($chat_id)['isAdmin'])) {
    if ($chat_id == $admin) {
        $data ? bot('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id]) : null;
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>👮‍♀️ Adminlar bo'limidasiz:</b>\n\n🔹 Bu yerda yangi admin qo‘shishingiz yoki mavjudlarini boshqarishingiz mumkin.",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [['text' => "➕ Admin qo‘shish", 'callback_data' => "add_admin"], ['text' => "➖ Adminni o‘chirish", 'callback_data' => "delete_admin"]],
                    [['text' => "📋 Adminlar ro‘yxati", 'callback_data' => "list_admin"]],
                ]
            ])
        ]);
    } else {
        bot('sendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>🚫 Sizda ushbu bo'limga kirish uchun ruxsat yo‘q!</b>",
            'parse_mode' => "html",
        ]);
    }
    step("");
    exit();
}

if (isset($data) && $data == "add_admin") {
    if ($chat_id == $admin){
        bot('deleteMessage',[
        	'chat_id' => $chat_id,
        	'message_id' => $message_id,
        ]);
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>🆔 Yangi admin ID sini kiriting:</b>",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
        step("add_admin");
    } else {
        bot('answerCallbackQuery',[
        	'callback_query_id' => $qid,
            'text' => "<b>🚫 Sizda admin qo‘shish uchun ruxsat yo‘q!</b>",
        	'show_alert' => true,
        ]);
    }
    exit();
}

if (isset($user['step']) && $user['step'] == "add_admin") {
    if (is_numeric($text)) {
        $check = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `admins` WHERE `user_id` = '{$text}'"));
        if (empty($check['id']) && $text != $admin) {
            $user = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `users` WHERE `user_id` = '{$text}'"));
            if (isset($user['id'])) {
                bot('SendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "<b>✅ Admin muvaffaqiyatli qo‘shildi!</b>",
                    'parse_mode' => 'html',
                    'reply_markup' => $panel
                ]);
                step("");
                $discount['amount'] = $amount;
                $discount['time'] = $time;
                $opportunities = json_encode(['statistics' => true, 'send' => true, 'channels' => true, 'movies' => true, 'settings' => true]);
                mysqli_query($connect,"INSERT INTO admins(`user_id`, `opportunities`, `date`) VALUES ('{$text}', '{$opportunities}', '{$time}');");                
            } else {
                bot('SendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "<b>⚠️ Ushbu foydalanuvchi botdan foydalanmagan!</b>",
                    'parse_mode' => 'html',
                    'reply_markup' => $Bpanel
                ]);
            }
        } else {
            bot('SendMessage', [
                'chat_id' => $chat_id,
                'text' => "<b>⚠️ Ushbu foydalanuvchi allaqachon adminlar ro‘yxatida mavjud!</b>",
                'parse_mode' => 'html',
                'reply_markup' => $Bpanel
            ]);
        }
    } else {
        bot('SendMessage', [
            'chat_id' => $chat_id,
            'text' => "<b>⚠️ Faqat raqam kiritishingiz mumkin!</b>",
            'parse_mode' => 'html',
            'reply_markup' => $Bpanel
        ]);
    }
    exit();
}

if (isset($data) && $data == "delete_admin") {
    if ($chat_id == $admin){
        $get = mysqli_query($connect, "SELECT * FROM `admins`");
        $count = 0;
        $buttons = [];
        while ($admin = mysqli_fetch_assoc($get)) {
            $count++;
            $buttons[] = ['text' => "🗑 " . $admin['user_id'], 'callback_data' => "delAdmin-" . $admin['id']];
        }
        $keyboard = array_chunk($buttons, 1);
        $keyboard[] = [['text' => "⏪ Orqaga", 'callback_data' => "admins"]];
        bot('editMessageText', [
            'chat_id' => $chat_id,
            'message_id' => $message_id,
            'text' => ($count > 0) ? "<b>📋 Adminlar ro'yxati:</b>\n\n🔹 O'chirish kerak bo'lgan admin ID ustiga bosing 👇" : "<b>⚠️ Adminlar qo‘shilmagan!</b>",
            'parse_mode' => 'html',
            'reply_markup' => json_encode([
                'inline_keyboard' => $keyboard
            ])
        ]);
        step("");
    } else {
        bot('answerCallbackQuery',[
        	'callback_query_id' => $qid,
            'text' => "<b>🚫 Sizda admin qo‘shish uchun ruxsat yo‘q!</b>",
        	'show_alert' => true,
        ]);
    }
    exit();
}

if (isset($data) && explode("-", $data)[0] == "delAdmin") {
    $id = explode("-", $data)[1];
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    bot('sendMessage', [
        'chat_id' => $chat_id,
        'text' => "<b>🗑 Admin muvaffaqiyatli o'chirildi!</b>",
        'parse_mode' => 'html',
        'reply_markup' => $panel,
    ]);
    mysqli_query($connect, "DELETE FROM `admins` WHERE `id` = '{$id}'");
    step("");
    exit();
}

if (isset($data) && $data == "list_admin") {
    $get = mysqli_query($connect, "SELECT * FROM `admins`");
    $count = 0;
    $buttons = [];
    while ($admin = mysqli_fetch_assoc($get)) {
        $count++;
        $buttons[] = ['text' => "👮‍♀️ " . $admin['user_id'], 'callback_data' => "admin-" . $admin['id']];
    }
    $keyboard = array_chunk($buttons, 1);
    $keyboard[] = [['text' => "⏪ Orqaga", 'callback_data' => "admins"]];
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => ($count > 0) ? "<b>📋 Adminlar ro‘yxati:</b>\n\n🔹 Adminning imkoniyatlarini boshqarish uchun uning ustiga bosing 👇" : "<b>⚠️ Adminlar qo‘shilmagan!</b>",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => $keyboard
        ])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "admin") {
    $id = explode("-", $data)[1];
    $admin = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `admins` WHERE `id` = '{$id}'"));
    $opportunities = json_decode($admin['opportunities'], true);
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "<b>🆔 Admin ID:</b> <a href='tg://user?id={$admin['user_id']}'>{$admin['user_id']}</a>\n\n" .
                  "🔹 Quyidagi tugmalar orqali admin imkoniyatlarini boshqarishingiz mumkin:",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "📊 Statistika " . ($opportunities['statistics'] ? "✅" : "⛔️"),'callback_data' => "adminStatus-$id-statistics"]],
                [['text' => "📨 Xabar yuborish " . ($opportunities['send'] ? "✅" : "⛔️"), 'callback_data' => "adminStatus-$id-send"]],
                [['text' => "🔐 Kanallar " . ($opportunities['channels'] ? "✅" : "⛔️"), 'callback_data' => "adminStatus-$id-channels"]],
                [['text' => "🎬 Kinolar " . ($opportunities['movies'] ? "✅" : "⛔️"), 'callback_data' => "adminStatus-$id-movies"]],
                [['text' => "⚙️ Sozlamalar " . ($opportunities['settings'] ? "✅" : "⛔️"), 'callback_data' => "adminStatus-$id-settings"]],
                [['text' => "⏪ Orqaga", 'callback_data' => "list_admin"]],
        ]])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "adminStatus") {
    $id = explode("-", $data)[1];
    $type = explode("-", $data)[2];
    $admin = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `admins` WHERE `id` = '{$id}'"));
    $opportunities = json_decode($admin['opportunities'], true);
    $opportunities[$type] = $opportunities[$type] ? false : true;
    mysqli_query($connect, "UPDATE `admins` SET `opportunities` = '" . json_encode($opportunities) . "' WHERE `id` = '{$id}'");
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "<b>🆔 Admin ID:</b> <a href='tg://user?id={$admin['user_id']}'>{$admin['user_id']}</a>\n\n" .
                  "🔹 Quyidagi tugmalar orqali admin imkoniyatlarini boshqarishingiz mumkin:",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => [
                [['text' => "📊 Statistika " . ($opportunities['statistics'] ? "✅" : "⛔️"),'callback_data' => "adminStatus-$id-statistics"]],
                [['text' => "📨 Xabar yuborish " . ($opportunities['send'] ? "✅" : "⛔️"), 'callback_data' => "adminStatus-$id-send"]],
                [['text' => "🔐 Kanallar " . ($opportunities['channels'] ? "✅" : "⛔️"), 'callback_data' => "adminStatus-$id-channels"]],
                [['text' => "🎬 Kinolar " . ($opportunities['movies'] ? "✅" : "⛔️"), 'callback_data' => "adminStatus-$id-movies"]],
                [['text' => "⚙️ Sozlamalar " . ($opportunities['settings'] ? "✅" : "⛔️"), 'callback_data' => "adminStatus-$id-settings"]],
                [['text' => "⏪ Orqaga", 'callback_data' => "list_admin"]],
        ]])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("-", $data)[0] == "check") {
    $code = explode("-", $data)[1];
    bot('deleteMessage',[
    	'chat_id' => $chat_id,
    	'message_id' => $message_id,
    ]);
    $count = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `movies` WHERE `code` = '{$code}'"))['Total'];
    if (joinchat($chat_id, $code)) {
        $bot = getMe()->username;
        if ($count > 0) {
            $query = mysqli_query($connect, "SELECT * FROM `movies` WHERE `code` = '{$code}' LIMIT 10");
            if ($count > 1) {
                $i = 0;
                $txt = "";
                $keyboard = [];
                $limit = 10;
                $total_pages = ceil($count / $limit);
                $page = 1;
                $offset = ($page - 1) * $limit;
                while ($movie = mysqli_fetch_assoc($query)) {
                    $i++;
                    $name = $movie['name'] ?: "{$i}-qism";
                    $txt .= "<b>$i.</b> $name " . ($movie['status'] == "premium" ? "💎" : "") ."\n";
                    $keyboard[] = ['text' => "$i", 'callback_data' => "movie_{$movie['id']}"];
                }
                $inline_keyboard = array_chunk($keyboard, 5);
                $inline_keyboard[] = [['text' => ($page > 1) ? "⏪" : "", 'callback_data' => "page_" . ($page - 1) . "_{$code}"], ['text' => "$page/$total_pages", 'callback_data' => "ignore"], ['text' => ($page < $total_pages) ? "⏩" : "", 'callback_data' => "page_" . ($page + 1) . "_$code"]];
                $inline_keyboard[] = ($setting['premium'] == "on") ? [["text" => "💎 Premium", "callback_data" => "premium"]] : [];
                bot('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "<b>🎬 Kino qismlari roʻyxati:</b>\n\n$txt",
                    'parse_mode' => 'html',
                    'reply_markup' => json_encode([
                        'inline_keyboard' => $inline_keyboard
                    ])
                ]);
            } else {
                $movie = mysqli_fetch_assoc($query);
                if ($movie['status'] == "premium") {
                    if (isPremium($chat_id)) {
                        $downloads = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `downloads` WHERE `file_id` = '{$movie['id']}'"));  
                        $name = ($movie['name']) ? "<b>🎬 Nomi:</b> {$movie['name']}\n\n" : "";
                        $description = ($movie['description']) ? "{$movie['description']}\n\n" : "";
                        bot('sendVideo',[
                            'chat_id' => $chat_id,
                            'video' => $movie['file_id'],
                                'caption' => "🔎 <b>Kino kodi:</b> <code>{$movie['code']}</code>\n\n$name$description<b>🤖 Botimiz:</b> @$bot \n\n<b>👁 Ko'rishlar:</b> {$downloads['Total']} ta",
                                'parse_mode' => 'html',
                                'protect_content' => ($setting['share_save'] == "on") ? true : false,
                                'reply_markup' => json_encode([
                                    'inline_keyboard' => [
                                        [['text' => "↗️ Ulashish",'url'=>"https://t.me/share/url/?url=https://t.me/$bot?start={$movie['code']}"]],
                                ]])
                            ]);
                        download($movie['id']);
                    } else {
                        bot('sendMessage', [
                            'chat_id' => $chat_id,
                            'text' => "<b>🔒 Ushbu kino faqat «Premium» foydalanuvchilar uchun</b> \n\n<blockquote>❗️ Kinoni ko'rish uchun Premium obuna sotib oling.</blockquote>",
                            'parse_mode' => 'html',
                            'reply_markup' => json_encode([
                                'inline_keyboard' => [
                                    ($setting['premium'] == "on") ? [["text" => "💎 Premium", "callback_data" => "premium"]] : [],
                            ]])
                        ]); 
                    }
                } else {
                    $downloads = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `downloads` WHERE `file_id` = '{$movie['id']}'"));  
                    $name = ($movie['name']) ? "<b>🎬 Nomi:</b> {$movie['name']}\n\n" : "";
                    $description = ($movie['description']) ? "{$movie['description']}\n\n" : "";
                    bot('sendVideo',[
                        'chat_id' => $chat_id,
                        'video' => $movie['file_id'],
                            'caption' => "🔎 <b>Kino kodi:</b> <code>{$movie['code']}</code>\n\n$name$description<b>🤖 Botimiz:</b> @$bot \n\n<b>👁 Ko'rishlar:</b> {$downloads['Total']} ta",
                            'parse_mode' => 'html',
                            'protect_content' => ($setting['share_save'] == "on") ? true : false,
                            'reply_markup' => json_encode([
                                'inline_keyboard' => [
                                    [['text' => "↗️ Ulashish",'url'=>"https://t.me/share/url/?url=https://t.me/$bot?start={$movie['code']}"]],
                            ]])
                        ]);
                    download($movie['id']);
                }
                exit();
            }
        } else {
            bot('sendMessage', [
                'chat_id' => $chat_id,
                'text' => "<b>👋 Assalomu alaykum <a href='tg://user?id=$chat_id'>$first_name</a> botimizga xush kelibsiz.</b> \n\n✍🏻 Kino kodini yuboring...",
                'parse_mode' => 'html',
                'reply_markup' => ($setting['premium'] == "off") ? (($chat_id == $admin || user($chat_id)['isAdmin']) ? $Bpanel : $remove_keyboard) : $menu,
            ]);
        }
    }
    step("");
    exit();
}

if (isset($text) && $type == "private"){
    $code = preg_replace('/\D/', '', $text);
    $escaped_code = mysqli_real_escape_string($connect, $code);
    $count = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `movies` WHERE `code` = '{$escaped_code}'"))['Total'];
    if (joinchat($chat_id, $code)) {
        if ($count > 0) {
            $bot = getMe()->username;
            $query = mysqli_query($connect, "SELECT * FROM `movies` WHERE `code` = '{$escaped_code}' LIMIT 10");
            if ($count > 1) {
                $i = 0;
                $txt = "";
                $keyboard = [];
                $limit = 10;
                $total_pages = ceil($count / $limit);
                $page = 1;
                $offset = ($page - 1) * $limit;
                while ($movie = mysqli_fetch_assoc($query)) {
                    $i++;
                    $name = $movie['name'] ?: "{$i}-qism";
                    $txt .= "<b>$i.</b> $name " . ($movie['status'] == "premium" ? "💎" : "") ."\n";
                    $keyboard[] = ['text' => "$i", 'callback_data' => "movie_{$movie['id']}"];
                }
                $inline_keyboard = array_chunk($keyboard, 5);
                $inline_keyboard[] = [['text' => ($page > 1) ? "⏪" : "", 'callback_data' => "page_" . ($page - 1) . "_{$code}"], ['text' => "$page/$total_pages", 'callback_data' => "ignore"], ['text' => ($page < $total_pages) ? "⏩" : "", 'callback_data' => "page_" . ($page + 1) . "_$code"]];
                $inline_keyboard[] = ($setting['premium'] == "on") ? [["text" => "💎 Premium", "callback_data" => "premium"]] : [];
                bot('sendMessage', [
                    'chat_id' => $chat_id,
                    'text' => "<b>🎬 Kino qismlari roʻyxati:</b>\n\n$txt",
                    'parse_mode' => 'html',
                    'reply_markup' => json_encode([
                        'inline_keyboard' => $inline_keyboard
                    ])
                ]);
            } else {
                $movie = mysqli_fetch_assoc($query);
                if ($movie['status'] == "premium") {
                    if (isPremium($chat_id)) {
                        $downloads = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `downloads` WHERE `file_id` = '{$movie['id']}'"));  
                        $name = ($movie['name']) ? "<b>🎬 Nomi:</b> {$movie['name']}\n\n" : "";
                        $description = ($movie['description']) ? "{$movie['description']}\n\n" : "";
                        bot('sendVideo',[
                            'chat_id' => $chat_id,
                            'video' => $movie['file_id'],
                                'caption' => "🔎 <b>Kino kodi:</b> <code>{$movie['code']}</code>\n\n$name$description<b>🤖 Botimiz:</b> @$bot \n\n<b>👁 Ko'rishlar:</b> {$downloads['Total']} ta",
                                'parse_mode' => 'html',
                                'protect_content' => ($setting['share_save'] == "on") ? true : false,
                                'reply_markup' => json_encode([
                                    'inline_keyboard' => [
                                        [['text' => "↗️ Ulashish",'url'=>"https://t.me/share/url/?url=https://t.me/$bot?start={$movie['code']}"]],
                                ]])
                            ]);
                        download($movie['id']);
                    } else {
                        bot('sendMessage', [
                            'chat_id' => $chat_id,
                            'text' => "<b>🔒 Ushbu kino faqat «Premium» foydalanuvchilar uchun</b> \n\n<blockquote>❗️ Kinoni ko'rish uchun Premium obuna sotib oling.</blockquote>",
                            'parse_mode' => 'html',
                            'reply_markup' => json_encode([
                                'inline_keyboard' => [
                                    ($setting['premium'] == "on") ? [["text" => "💎 Premium", "callback_data" => "premium"]] : [],
                            ]])
                        ]); 
                    }
                } else {
                    $downloads = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `downloads` WHERE `file_id` = '{$movie['id']}'"));  
                    $name = ($movie['name']) ? "<b>🎬 Nomi:</b> {$movie['name']}\n\n" : "";
                    $description = ($movie['description']) ? "{$movie['description']}\n\n" : "";
                    bot('sendVideo',[
                        'chat_id' => $chat_id,
                        'video' => $movie['file_id'],
                            'caption' => "🔎 <b>Kino kodi:</b> <code>{$movie['code']}</code>\n\n$name$description<b>🤖 Botimiz:</b> @$bot \n\n<b>👁 Ko'rishlar:</b> {$downloads['Total']} ta",
                            'parse_mode' => 'html',
                            'protect_content' => ($setting['share_save'] == "on") ? true : false,
                            'reply_markup' => json_encode([
                                'inline_keyboard' => [
                                    [['text' => "↗️ Ulashish",'url'=>"https://t.me/share/url/?url=https://t.me/$bot?start={$movie['code']}"]],
                            ]])
                        ]);
                    download($movie['id']);
                }
                exit();
            }
        } else {
            bot('SendMessage',[
                'chat_id' => $chat_id,
                'text' => "<b>❌ Kino kodini xato yubordingiz!</b>",
                'parse_mode' => 'html',
                'reply_markup' => ($setting['premium'] == "off") ? (($chat_id == $admin || user($chat_id)['isAdmin']) ? $Bpanel : $remove_keyboard) : $menu,
            ]);
        }
    }
    step("");
    exit();
}

if (isset($data) && explode("_", $data)[0] == "page") {
    $page = explode("_", $data)[1];
    $code = explode("_", $data)[2];
    $page = isset($page) ? intval($page) : 1;
    $limit = 10;
    $offset = ($page - 1) * $limit;
    $count_data = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `movies` WHERE `code` = '{$code}'"));
    $total_movies = intval($count_data['Total']);
    $total_pages = ceil($total_movies / $limit);
    $query = mysqli_query($connect, "SELECT * FROM `movies` WHERE `code` = '{$code}' LIMIT $limit OFFSET $offset");
    $i = $offset;
    $txt = "";
    $keyboard = [];
    while ($movie = mysqli_fetch_assoc($query)) {
        $i++;
        $name = $movie['name'] ?: "{$i}-qism";
        $txt .= "<b>$i.</b> $name " . ($movie['status'] == "premium" ? "💎" : "") ."\n";
        $keyboard[] = ['text' => "$i", 'callback_data' => "movie_{$movie['id']}"];
    }
    $inline_keyboard = array_chunk($keyboard, 5);
    $inline_keyboard[] = [['text' => ($page > 1) ? "⏪" : "", 'callback_data' => "page_" . ($page - 1) . "_{$code}"], ['text' => "$page/$total_pages", 'callback_data' => "ignore"], ['text' => ($page < $total_pages) ? "⏩" : "", 'callback_data' => "page_" . ($page + 1) . "_$code"]];
    $inline_keyboard[] = ($setting['premium'] == "on") ? [["text" => "💎 Premium", "callback_data" => "premium"]] : [];
    bot('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => "<b>🎬 Kino qismlari roʻyxati:</b>\n\n$txt",
        'parse_mode' => 'html',
        'reply_markup' => json_encode([
            'inline_keyboard' => $inline_keyboard
        ])
    ]);
    step("");
    exit();
}

if (isset($data) && explode("_", $data)[0] == "movie" && joinchat($chat_id, explode("_", $data)[1])) {
    $code = explode("_", $data)[1];
    $movie = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM `movies` WHERE `id` = '{$code}'"));
    if ($movie['status'] == "premium") {
        if (isPremium($chat_id)) {
            $downloads = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `downloads` WHERE `file_id` = '{$movie['id']}'"));  
            $name = ($movie['name']) ? "<b>🎬 Nomi:</b> {$movie['name']}\n\n" : "";
            $description = ($movie['description']) ? "{$movie['description']}\n\n" : "";
            $bot = getMe()->username;
            bot('sendVideo',[
                'chat_id' => $chat_id,
                'video' => $movie['file_id'],
                'caption' => "🔎 <b>Kino kodi:</b> <code>{$movie['code']}</code>\n\n$name$description<b>🤖 Botimiz:</b> @$bot \n\n<b>👁 Ko'rishlar:</b> {$downloads['Total']} ta",
                'parse_mode' => 'html',
                'protect_content' => ($setting['share_save'] == "on") ? true : false,
                'reply_markup' => json_encode([
                    'inline_keyboard' => [
                        [['text' => "↗️ Ulashish", 'url'=>"https://t.me/share/url/?url=https://t.me/$bot?start={$movie['code']}"]],
                ]])
            ]);
            download($movie['id']);
        } else {
            bot('answerCallbackQuery',[
            	'callback_query_id' => $qid,
                'text' => "🔒 Ushbu kino faqat «Premium» foydalanuvchilar uchun\n\n❗️ Kinoni ko'rish uchun Premium obuna sotib oling.",
            	'show_alert' => true,
            ]);
        }
    } else {
            $downloads = mysqli_fetch_assoc(mysqli_query($connect, "SELECT COUNT(*) AS Total FROM `downloads` WHERE `file_id` = '{$movie['id']}'"));  
            $name = ($movie['name']) ? "<b>🎬 Nomi:</b> {$movie['name']}\n\n" : "";
            $description = ($movie['description']) ? "{$movie['description']}\n\n" : "";
            $bot = getMe()->username;
            bot('sendVideo',[
                'chat_id' => $chat_id,
                'video' => $movie['file_id'],
                'caption' => "🔎 <b>Kino kodi:</b> <code>{$movie['code']}</code>\n\n$name$description<b>🤖 Botimiz:</b> @$bot \n\n<b>👁 Ko'rishlar:</b> {$downloads['Total']} ta",
                'parse_mode' => 'html',
                'protect_content' => ($setting['share_save'] == "on") ? true : false,
                'reply_markup' => json_encode([
                    'inline_keyboard' => [
                        [['text' => "↗️ Ulashish", 'url'=>"https://t.me/share/url/?url=https://t.me/$bot?start={$movie['code']}"]],
                ]])
            ]);
            download($movie['id']);
    }
    exit();
}

if (isset($_REQUEST['send']) && $_REQUEST['send'] == "message") {
    $hour = date('H:i');
    $send = mysqli_fetch_assoc(mysqli_query($connect, "SELECT * FROM send"));
    $message = $send['message']; 
    $type = $send['type']; 
    $finish = $send['finish']; 
    $limit = $send['limit']; 
    $succes = $send['succes']; 
    $time1 = $send['time1']; 
    $time2 = $send['time2']; 
    $time3 = $send['time3']; 
    $time4 = $send['time4']; 
    $time5 = $send['time5'];
    $button = base64_decode($send['button']) ?? " "; 
    $status = $send['status']; 
    if($hour == $time1 or $hour == $time2 or $hour == $time3 or $hour == $time4 or $hour == $time5){
        $send = mysqli_query($connect,"SELECT * FROM users LIMIT $succes,$limit");
        while($sms = mysqli_fetch_assoc($send)){
            $user_id = $sms['user_id'];
            bot($type,[ 
                'from_chat_id' => $admin, 
                'chat_id' => $user_id, 
                'message_id' => $message, 
                'disable_web_page_preview' => true, 
                'reply_markup' => $button,
            ]);
            if ($user_id == $finish) {
                bot('sendMessage',[ 
                    'chat_id' => $admin, 
                    'text' => "<b>✅ Xabar yuborish yakunlandi!</b>", 
                    'parse_mode' => 'html', 
                ]); 
                mysqli_query($connect, "DELETE FROM `send`"); 
                exit(); 
            }
            $time1 = date('H:i', strtotime('+1 minutes')); 
            $time2 = date('H:i', strtotime('+2 minutes')); 
            $time3 = date('H:i', strtotime('+3 minutes')); 
            $time4 = date('H:i', strtotime('+4 minutes')); 
            $succes = $succes + 1;
            mysqli_query($connect, "UPDATE `send` SET `succes` = '$succes', `time1` = '$time1', `time2` = '$time2', `time3` = '$time3', `time4` = '$time4', `time5` = '$time5'"); 
        }
    }
}

?>