
<?php
/**
 * ربات تلگرام فیلم
 * فایل: bot.php
 * نسخه: 1.0
 */

// ==================== تنظیمات ====================
define('BOT_TOKEN', '8539054629:AAEkiHvtvhbEH-IlFCnZXTErH9Nfw36-Gjg'); // توکن ربات را اینجا قرار دهید
define('ADMIN_ID', 735533834); // آیدی عددی مدیر اصلی
define('DB_FILE', 'bot_database.sqlite');
define('MOVIE_DISPLAY_TIME', 30); // زمان نمایش فیلم به ثانیه

// ==================== دیتابیس ====================
class Database {
    private $db;
    
    public function __construct() {
        $this->db = new SQLite3(DB_FILE);
        $this->createTables();
    }
    
    private function createTables() {
        // جدول کاربران
        $this->db->exec("
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY,
                user_id INTEGER UNIQUE,
                username TEXT,
                first_name TEXT,
                join_date DATETIME DEFAULT CURRENT_TIMESTAMP,
                blocked INTEGER DEFAULT 0
            )
        ");
        
        // جدول فیلم‌ها
        $this->db->exec("
            CREATE TABLE IF NOT EXISTS movies (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                type TEXT CHECK(type IN ('iranian', 'foreign', 'popular')),
                title TEXT,
                description TEXT,
                file_id TEXT,
                file_type TEXT DEFAULT 'video',
                added_date DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ");
        
        // جدول ادمین‌ها
        $this->db->exec("
            CREATE TABLE IF NOT EXISTS admins (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER UNIQUE,
                added_by INTEGER,
                added_date DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ");
        
        // جدول کانال‌های اجباری
        $this->db->exec("
            CREATE TABLE IF NOT EXISTS channels (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                channel_id TEXT UNIQUE,
                channel_title TEXT,
                channel_link TEXT,
                added_date DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ");
        
        // جدول تبلیغات
        $this->db->exec("
            CREATE TABLE IF NOT EXISTS advertisements (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                content TEXT,
                status TEXT DEFAULT 'pending',
                added_date DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ");
        
        // جدول پیام‌های موقت
        $this->db->exec("
            CREATE TABLE IF NOT EXISTS temp_messages (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                message_id INTEGER,
                delete_time DATETIME
            )
        ");
        
        // اضافه کردن مدیر اصلی به ادمین‌ها
        $check = $this->db->querySingle("SELECT COUNT(*) FROM admins WHERE user_id = " . ADMIN_ID);
        if ($check == 0) {
            $this->db->exec("INSERT INTO admins (user_id, added_by) VALUES (" . ADMIN_ID . ", 0)");
        }
    }
    
    public function getConnection() {
        return $this->db;
    }
}

// ==================== توابع تلگرام ====================
class TelegramAPI {
    private $token;
    
    public function __construct($token) {
        $this->token = $token;
    }
    
    private function request($method, $params = []) {
        $url = "https://api.telegram.org/bot{$this->token}/{$method}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }
    
    public function sendMessage($chat_id, $text, $keyboard = null, $parse_mode = 'HTML') {
        $params = [
            'chat_id' => $chat_id,
            'text' => $text,
            'parse_mode' => $parse_mode
        ];
        if ($keyboard) {
            $params['reply_markup'] = json_encode($keyboard);
        }
        return $this->request('sendMessage', $params);
    }
    
    public function editMessageText($chat_id, $message_id, $text, $keyboard = null, $parse_mode = 'HTML') {
        $params = [
            'chat_id' => $chat_id,
            'message_id' => $message_id,
            'text' => $text,
            'parse_mode' => $parse_mode
        ];
        if ($keyboard) {
            $params['reply_markup'] = json_encode($keyboard);
        }
        return $this->request('editMessageText', $params);
    }
    
    public function deleteMessage($chat_id, $message_id) {
        return $this->request('deleteMessage', [
            'chat_id' => $chat_id,
            'message_id' => $message_id
        ]);
    }
    
    public function sendVideo($chat_id, $video, $caption = null, $keyboard = null) {
        $params = [
            'chat_id' => $chat_id,
            'video' => $video
        ];
        if ($caption) {
            $params['caption'] = $caption;
            $params['parse_mode'] = 'HTML';
        }
        if ($keyboard) {
            $params['reply_markup'] = json_encode($keyboard);
        }
        return $this->request('sendVideo', $params);
    }
    
    public function sendPhoto($chat_id, $photo, $caption = null, $keyboard = null) {
        $params = [
            'chat_id' => $chat_id,
            'photo' => $photo
        ];
        if ($caption) {
            $params['caption'] = $caption;
            $params['parse_mode'] = 'HTML';
        }
        if ($keyboard) {
            $params['reply_markup'] = json_encode($keyboard);
        }
        return $this->request('sendPhoto', $params);
    }
    
    public function getChatMember($chat_id, $user_id) {
        return $this->request('getChatMember', [
            'chat_id' => $chat_id,
            'user_id' => $user_id
        ]);
    }
    
    public function answerCallbackQuery($callback_query_id, $text = null, $show_alert = false) {
        $params = [
            'callback_query_id' => $callback_query_id
        ];
        if ($text) {
            $params['text'] = $text;
            $params['show_alert'] = $show_alert;
        }
        return $this->request('answerCallbackQuery', $params);
    }
    
    public function forwardMessage($chat_id, $from_chat_id, $message_id) {
        return $this->request('forwardMessage', [
            'chat_id' => $chat_id,
            'from_chat_id' => $from_chat_id,
            'message_id' => $message_id
        ]);
    }
    
    public function copyMessage($chat_id, $from_chat_id, $message_id, $caption = null) {
        $params = [
            'chat_id' => $chat_id,
            'from_chat_id' => $from_chat_id,
            'message_id' => $message_id
        ];
        if ($caption) {
            $params['caption'] = $caption;
        }
        return $this->request('copyMessage', $params);
    }
}

// ==================== کیبوردها ====================
class Keyboards {
    public static function mainMenu() {
        return [
            'keyboard' => [
                ['🎬 فیلم ایرانی'],
                ['🎬 فیلم خارجی'],
                ['⭐ فیلم های محبوب'],
                ['📢 ثبت تبلیغ']
            ],
            'resize_keyboard' => true,
            'one_time_keyboard' => false
        ];
    }

    
    public static function adminPanel() {
        return [
            'keyboard' => [
                ['👥 تعداد کاربران', '🎥 مدیریت فیلم ها'],
                ['👮 مدیریت ادمین ها', '📢 کانال های اجباری'],
                ['📨 ارسال همگانی', '🔙 بازگشت به منو']
            ],
            'resize_keyboard' => true
        ];
    }
    
    public static function movieManagement() {
        return [
            'keyboard' => [
                ['➕ افزودن فیلم ایرانی', '➕ افزودن فیلم خارجی'],
                ['➕ افزودن فیلم محبوب', '🗑 حذف فیلم'],
                ['📋 لیست فیلم ها', '🔙 بازگشت']
            ],
            'resize_keyboard' => true
        ];
    }
    
    public static function adminManagement() {
        return [
            'keyboard' => [
                ['➕ افزودن ادمین', '🗑 حذف ادمین'],
                ['📋 لیست ادمین ها', '🔙 بازگشت']
            ],
            'resize_keyboard' => true
        ];
    }
    
    public static function channelManagement() {
        return [
            'keyboard' => [
                ['➕ افزودن کانال', '🗑 حذف کانال'],
                ['📋 لیست کانال ها', '🔙 بازگشت']
            ],
            'resize_keyboard' => true
        ];
    }
    
    public static function inlineNext($type, $offset) {
        return [
            'inline_keyboard' => [
                [
                    ['text' => '⏭ بعدی', 'callback_data' => "next_{$type}_{$offset}"]
                ]
            ]
        ];
    }
    
    public static function inlineDelete($movie_id) {
        return [
            'inline_keyboard' => [
                [
                    ['text' => '🗑 حذف این فیلم', 'callback_data' => "delmovie_{$movie_id}"]
                ]
            ]
        ];
    }
    
    public static function inlineConfirm($action, $id) {
        return [
            'inline_keyboard' => [
                [
                    ['text' => '✅ تایید', 'callback_data' => "confirm_{$action}_{$id}"],
                    ['text' => '❌ لغو', 'callback_data' => "cancel_{$action}_{$id}"]
                ]
            ]
        ];
    }
    
    public static function backKeyboard() {
        return [
            'keyboard' => [
                ['🔙 بازگشت']
            ],
            'resize_keyboard' => true
        ];
    }
    
    public static function removeKeyboard() {
        return [
            'remove_keyboard' => true
        ];
    }
}

// ==================== کلاس اصلی ربات ====================
class MovieBot {
    private $telegram;
    private $db;
    private $update;
    private $message;
    private $callback;
    private $user_id;
    private $chat_id;
    private $text;
    private $user_state = [];
        // تابع استخراج اطلاعات فیلم از پیام
      private function extractMovieInfo() {
        $file_id = null;
        $file_type = null;
        $title = 'بدون عنوان';
        $description = '';
        
        // بررسی ویدیو
        if (isset($this->message['video'])) {
            $file_id = $this->message['video']['file_id'];
            $file_type = 'video';
        } 
        // بررسی عکس
        elseif (isset($this->message['photo'])) {
            $photo = end($this->message['photo']);
            $file_id = $photo['file_id'];
            $file_type = 'photo';
        } 
        // بررسی فایل (Document) - این بخش اضافه شد
        elseif (isset($this->message['document'])) {
            $file_id = $this->message['document']['file_id'];
            $file_type = 'document';
        }
        
        // استخراج کپشن اگر وجود داشته باشد
        if ($file_id && isset($this->message['caption'])) {
            $parts = explode("\n", $this->message['caption'], 2);
            $title = $parts[0];
            $description = isset($parts[1]) ? $parts[1] : '';
        }
        
        if ($file_id) {
            return [
                'file_id' => $file_id,
                'file_type' => $file_type,
                'title' => $title,
                'description' => $description
            ];
        }
        return null;
    }

    // تابع جمع‌آوری فیلم‌ها در حافظه موقت
    private function accumulateMovie($stateData) {
        $movieInfo = $this->extractMovieInfo();
        
        if ($movieInfo) {
            $stateData['movies'][] = $movieInfo;
            $this->setUserState(json_encode($stateData));
            
            $count = count($stateData['movies']);
            // پیام کوتاه برای اطلاع کاربر بدون ارسال کیبورد
            $this->telegram->sendMessage($this->chat_id, "📥 فیلم دریافت شد (تعداد فعلی: {$count}).");
        } else {
            $this->telegram->sendMessage($this->chat_id, "⚠️ لطفا فقط ویدیو یا عکس ارسال کنید.");
        }
    }
    
    // تابع نهایی کردن و ذخیره فیلم‌ها در دیتابیس
    private function finishAddingMovies() {
        $stateJson = $this->getUserState();
        $stateData = json_decode($stateJson, true);
        
        if (!isset($stateData['action'], $stateData['movies'])) {
            $this->telegram->sendMessage($this->chat_id, "⚠️ خطا در پردازش.", Keyboards::movieManagement());
            $this->clearUserState();
            return;
        }
        
        $typeMap = [
            'waiting_movie_iranian' => 'iranian',
            'waiting_movie_foreign' => 'foreign',
            'waiting_movie_popular' => 'popular'
        ];
        
        $type = $typeMap[$stateData['action']] ?? null;
        $movies = $stateData['movies'];
        $count = 0;
        
        if ($type && !empty($movies)) {
            foreach ($movies as $movie) {
                $stmt = $this->db->prepare("INSERT INTO movies (type, title, description, file_id, file_type) VALUES (:type, :title, :desc, :fid, :ftype)");
                $stmt->bindValue(':type', $type, SQLITE3_TEXT);
                $stmt->bindValue(':title', $movie['title'], SQLITE3_TEXT);
                $stmt->bindValue(':desc', $movie['description'], SQLITE3_TEXT);
                $stmt->bindValue(':fid', $movie['file_id'], SQLITE3_TEXT);
                $stmt->bindValue(':ftype', $movie['file_type'], SQLITE3_TEXT);
                $stmt->execute();
                $count++;
            }
            
            $typeNames = ['iranian' => 'ایرانی', 'foreign' => 'خارجی', 'popular' => 'محبوب'];
            $this->telegram->sendMessage($this->chat_id, 
                "✅ {$count} فیلم {$typeNames[$type]} با موفقیت اضافه شد.",
                Keyboards::movieManagement());
        } else {
            $this->telegram->sendMessage($this->chat_id, "⚠️ فیلمی برای افزودن دریافت نشده است.", Keyboards::movieManagement());
        }
        
        $this->clearUserState();
    }

    public function __construct() {
        $this->telegram = new TelegramAPI(BOT_TOKEN);
        $database = new Database();
        $this->db = $database->getConnection();
        
        // دریافت آپدیت
        $content = file_get_contents("php://input");
        $this->update = json_decode($content, true);
        
        if (!$this->update) {
            die('No update received');
        }
        
        // تشخیص نوع آپدیت
        if (isset($this->update['message'])) {
            $this->message = $this->update['message'];
            $this->chat_id = $this->message['chat']['id'];
            $this->user_id = $this->message['from']['id'];
            $this->text = isset($this->message['text']) ? $this->message['text'] : '';
        } elseif (isset($this->update['callback_query'])) {
            $this->callback = $this->update['callback_query'];
            $this->chat_id = $this->callback['message']['chat']['id'];
            $this->user_id = $this->callback['from']['id'];
            $this->text = $this->callback['data'];
        }
    }
    
    // بررسی عضویت در کانال‌ها
    private function checkChannelSubscription() {
        $channels = $this->db->query("SELECT channel_id, channel_title, channel_link FROM channels");
        $not_joined = [];
        
        while ($channel = $channels->fetchArray(SQLITE3_ASSOC)) {
            $member = $this->telegram->getChatMember($channel['channel_id'], $this->user_id);
            
            if (!isset($member['result']) || !in_array($member['result']['status'], ['member', 'administrator', 'creator'])) {
                $not_joined[] = $channel;
            }
        }
        
        return $not_joined;
    }
    
    // نمایش پیام عضویت در کانال
       private function showJoinMessage($not_joined) {
        $text = "⚠️ برای استفاده از ربات، لطفاً در کانال‌های زیر عضو شوید:";
        
        $keyboard = ['inline_keyboard' => []];
        
        // ایجاد دکمه شیشه‌ای برای هر کانال
        foreach ($not_joined as $channel) {
            $keyboard['inline_keyboard'][] = [
                ['text' => "📢 " . $channel['channel_title'], 'url' => $channel['channel_link']]
            ];
        }
        
        // دکمه "عضو شدم" در پایین لیست
        $keyboard['inline_keyboard'][] = [
            ['text' => "✅ عضو شدم", 'callback_data' => "check_subscription"]
        ];
        
        $this->telegram->sendMessage($this->chat_id, $text, $keyboard);
    }

    
    // بررسی ادمین بودن
    private function isAdmin($user_id = null) {
        $uid = $user_id ?: $this->user_id;
        $result = $this->db->querySingle("SELECT COUNT(*) FROM admins WHERE user_id = {$uid}");
        return $result > 0 || $uid == ADMIN_ID;
    }
    
    // ذخیره کاربر
    private function saveUser() {
        $user = $this->message['from'];
        $username = isset($user['username']) ? $user['username'] : '';
        $first_name = isset($user['first_name']) ? $user['first_name'] : '';
        
        $stmt = $this->db->prepare("INSERT OR IGNORE INTO users (user_id, username, first_name) VALUES (:uid, :uname, :fname)");
        $stmt->bindValue(':uid', $user['id'], SQLITE3_INTEGER);
        $stmt->bindValue(':uname', $username, SQLITE3_TEXT);
        $stmt->bindValue(':fname', $first_name, SQLITE3_TEXT);
        $stmt->execute();
    }
    
    // دریافت وضعیت کاربر
    private function getUserState() {
        $stmt = $this->db->prepare("SELECT state FROM user_states WHERE user_id = :uid");
        $stmt->bindValue(':uid', $this->user_id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        $row = $result->fetchArray();
        return $row ? $row['state'] : null;
    }
    
    // تنظیم وضعیت کاربر
    private function setUserState($state) {
        $stmt = $this->db->prepare("INSERT OR REPLACE INTO user_states (user_id, state) VALUES (:uid, :state)");
        $stmt->bindValue(':uid', $this->user_id, SQLITE3_INTEGER);
        $stmt->bindValue(':state', $state, SQLITE3_TEXT);
        $stmt->execute();
    }
    
    // پاک کردن وضعیت کاربر
    private function clearUserState() {
        $stmt = $this->db->prepare("DELETE FROM user_states WHERE user_id = :uid");
        $stmt->bindValue(':uid', $this->user_id, SQLITE3_INTEGER);
        $stmt->execute();
    }
    
    // نمایش فیلم‌ها
    private function showMovies($type, $offset = 0) {
        $limit = 3;
        $typeMap = [
            'iranian' => 'iranian',
            'foreign' => 'foreign',
            'popular' => 'popular'
        ];
        
        $movieType = $typeMap[$type] ?? $type;
        
        // شمارش کل فیلم‌ها
        $total = $this->db->querySingle("SELECT COUNT(*) FROM movies WHERE type = '{$movieType}'");
        
        if ($total == 0) {
            $typeNames = [
                'iranian' => 'ایرانی',
                'foreign' => 'خارجی',
                'popular' => 'محبوب'
            ];
            $this->telegram->sendMessage($this->chat_id, "⚠️ فیلم {$typeNames[$movieType]} ای یافت نشد.", Keyboards::mainMenu());
            return;
        }
        
        // دریافت فیلم‌ها
        $movies = $this->db->query("SELECT * FROM movies WHERE type = '{$movieType}' ORDER BY id DESC LIMIT {$limit} OFFSET {$offset}");
        
        $message_ids = [];
        
        while ($movie = $movies->fetchArray(SQLITE3_ASSOC)) {
            $caption = "🎬 <b>{$movie['title']}</b>\n\n";
            $caption .= "📝 {$movie['description']}\n\n";
            $caption .= "━━━━━━━━━━━━━━━━━━━━";
            
            if ($movie['file_type'] == 'video') {
                $result = $this->telegram->sendVideo($this->chat_id, $movie['file_id'], $caption);
            } else {
                $result = $this->telegram->sendPhoto($this->chat_id, $movie['file_id'], $caption);
            }
            
            if (isset($result['result']['message_id'])) {
                $message_ids[] = $result['result']['message_id'];
                
                // ثبت برای حذف خودکار
                $delete_time = date('Y-m-d H:i:s', time() + MOVIE_DISPLAY_TIME);
                $stmt = $this->db->prepare("INSERT INTO temp_messages (user_id, message_id, delete_time) VALUES (:uid, :mid, :dtime)");
                $stmt->bindValue(':uid', $this->user_id, SQLITE3_INTEGER);
                $stmt->bindValue(':mid', $result['result']['message_id'], SQLITE3_INTEGER);
                $stmt->bindValue(':dtime', $delete_time, SQLITE3_TEXT);
                $stmt->execute();
            }
        }
        
        // دکمه بعدی
        if ($offset + $limit < $total) {
            $new_offset = $offset + $limit;
            $keyboard = Keyboards::inlineNext($type, $new_offset);
            $this->telegram->sendMessage($this->chat_id, "📌 صفحه " . (floor($offset / $limit) + 1) . " از " . ceil($total / $limit), $keyboard);
        } else {
            $this->telegram->sendMessage($this->chat_id, "✅ به پایان لیست رسیدید.", Keyboards::mainMenu());
        }
   
        // ذخیره پیام‌های ارسال شده برای حذف بعدی
        $this->saveMovieSession($type, $offset, $message_ids);
    }
    
    // ذخیره جلسه فیلم برای حذف بعدی
    private function saveMovieSession($type, $offset, $message_ids) {
        $data = json_encode([
            'type' => $type,
            'offset' => $offset,
            'msg_ids' => $message_ids
        ]);
        
        $stmt = $this->db->prepare("INSERT OR REPLACE INTO user_states (user_id, state) VALUES (:uid, :state)");
        $stmt->bindValue(':uid', $this->user_id, SQLITE3_INTEGER);
        $stmt->bindValue(':state', $data, SQLITE3_TEXT);
        $stmt->execute();
    }
    
    // دریافت جلسه فیلم
    private function getMovieSession() {
        $stmt = $this->db->prepare("SELECT state FROM user_states WHERE user_id = :uid");
        $stmt->bindValue(':uid', $this->user_id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        $row = $result->fetchArray();
        
        if ($row && $row['state']) {
            return json_decode($row['state'], true);
        }
        return null;
    }
    
    // حذف پیام‌های قبلی
    private function deletePreviousMessages($msg_ids) {
        if (!is_array($msg_ids)) return;
        
        foreach ($msg_ids as $mid) {
            $this->telegram->deleteMessage($this->chat_id, $mid);
        }
    }
    
    // پاکسازی پیام‌های منقضی شده
    private function cleanupExpiredMessages() {
        $now = date('Y-m-d H:i:s');
        $results = $this->db->query("SELECT user_id, message_id FROM temp_messages WHERE delete_time <= '{$now}'");
        
        while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
            $this->telegram->deleteMessage($row['user_id'], $row['message_id']);
            $this->db->exec("DELETE FROM temp_messages WHERE message_id = {$row['message_id']}");
        }
    }
    
    // ==================== مدیریت پیام‌ها ====================
          public function handleMessage() {
        // حذف خط پاکسازی خودکار (رفع هنگی)
        // $this->cleanupExpiredMessages(); 
        
        $this->saveUser();
        
        // بررسی عضویت در کانال
        $notJoined = $this->checkChannelSubscription();
        if (!empty($notJoined) && !$this->isAdmin()) {
            $this->showJoinMessage($notJoined);
            return;
        }
        
        // --- اصلاح شده: دستور /start ---
        // از strpos استفاده شده تا لینک‌های دعوت هم کار کنند
        if (isset($this->text) && strpos($this->text, '/start') === 0) {
            $this->clearUserState();
            $this->telegram->sendMessage(
                $this->chat_id, 
                "👋 سلام! به ربات فیلم خوش آمدید.\n" .
                "لطفاً یکی از گزینه‌های زیر را انتخاب کنید:",
                Keyboards::mainMenu()
            );
            return;
        }

        // --- دستور /admin ---
        if ($this->text == '/admin' && $this->isAdmin()) {
            $this->telegram->sendMessage($this->chat_id, "🔧 پنل مدیریت ربات:", Keyboards::adminPanel());
            return;
        }
        
        // --- مدیریت وضعیت ---
        $state = $this->getUserState();
        if ($state) {
            $tempState = json_decode($state, true);
            
            if (is_array($tempState)) {
                // اگر JSON است اما action ندارد (جلسه فیلم)، وضعیت پاک می‌شود
                if (!isset($tempState['action'])) {
                    $this->clearUserState();
                } else {
                    // وضعیت فعال است، هندلر فراخوانی می‌شود
                    $this->handleState($state);
                    return;
                }
            } else {
                // وضعیت متن ساده است
                $this->handleState($state);
                return;
            }
        }
        
        // --- منوی اصلی ---
        $this->handleMainMenu();
    }


    // مدیریت منوی اصلی
    private function handleMainMenu() {
        switch ($this->text) {
            case '🎬 فیلم ایرانی':
                $this->showMovies('iranian', 0);
                break;
                
            case '🎬 فیلم خارجی':
                $this->showMovies('foreign', 0);
                break;
                
            case '⭐ فیلم های محبوب':
                $this->showMovies('popular', 0);
                break;
                
          case '📢 ثبت تبلیغ':
    $this->telegram->sendMessage($this->chat_id, 
        "جهت ثبت کانال خود در ربات به آیدی زیر پیام بدهید:\n\n" .
        "@dlarz_support",
        Keyboards::mainMenu()); // بازگشت به منوی اصلی
    // دیگر نیازی به setUserState نیست
    break;

                
            case '🔧 پنل مدیریت':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, "🔧 پنل مدیریت ربات:", Keyboards::adminPanel());
                } else {
                    $this->telegram->sendMessage($this->chat_id, "⛔ شما دسترسی ادمین ندارید.");
                }
                break;
                
            // ==================== بخش ادمین ====================
            case '👥 تعداد کاربران':
                if ($this->isAdmin()) {
                    $this->showUserStats();
                }
                break;
                
            case '🎥 مدیریت فیلم ها':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, "🎥 بخش مدیریت فیلم‌ها:", Keyboards::movieManagement());
                }
                break;
                
            case '👮 مدیریت ادمین ها':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, "👮 بخش مدیریت ادمین‌ها:", Keyboards::adminManagement());
                }
                break;
                
            case '📢 کانال های اجباری':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, "📢 بخش مدیریت کانال‌های اجباری:", Keyboards::channelManagement());
                }
                break;
                
            case '📨 ارسال همگانی':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, 
                        "📨 لطفا پیامی که می‌خواهید به همه کاربران ارسال شود را بنویسید:",
                        Keyboards::backKeyboard());
                    $this->setUserState('waiting_broadcast');
                }
                break;
                
            // ==================== مدیریت فیلم ====================
                     case '➕ افزودن فیلم ایرانی':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, 
                        "🎬 لطفا فیلم(های) ایرانی را فوروارد یا آپلود کنید.\n" .
                        "✅ پس از ارسال تمام فیلم‌ها، دکمه 'پایان افزودن' را بزنید.",
                        [
                            'keyboard' => [['✅ پایان افزودن', '❌ لغو']],
                            'resize_keyboard' => true
                        ]);
                    // ذخیره وضعیت به صورت JSON با لیست خالی
                    $this->setUserState(json_encode(['action' => 'waiting_movie_iranian', 'movies' => []]));
                }
                break;
                
            case '➕ افزودن فیلم خارجی':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, 
                        "🎬 لطفا فیلم(های) خارجی را فوروارد یا آپلود کنید.\n" .
                        "✅ پس از ارسال تمام فیلم‌ها، دکمه 'پایان افزودن' را بزنید.",
                        [
                            'keyboard' => [['✅ پایان افزودن', '❌ لغو']],
                            'resize_keyboard' => true
                        ]);
                    $this->setUserState(json_encode(['action' => 'waiting_movie_foreign', 'movies' => []]));
                }
                break;
                
            case '➕ افزودن فیلم محبوب':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, 
                        "⭐ لطفا فیلم(های) محبوب را فوروارد یا آپلود کنید.\n" .
                        "✅ پس از ارسال تمام فیلم‌ها، دکمه 'پایان افزودن' را بزنید.",
                        [
                            'keyboard' => [['✅ پایان افزودن', '❌ لغو']],
                            'resize_keyboard' => true
                        ]);
                    $this->setUserState(json_encode(['action' => 'waiting_movie_popular', 'movies' => []]));
                }
                break;

            case '✅ پایان افزودن':
                if ($this->isAdmin()) {
                    $this->finishAddingMovies();
                }
                break;

                
            case '🗑 حذف فیلم':
                if ($this->isAdmin()) {
                    $this->showMovieListForDelete();
                }
                break;
                
            case '📋 لیست فیلم ها':
                if ($this->isAdmin()) {
                    $this->showAllMoviesList();
                }
                break;
                
            // ==================== مدیریت ادمین ====================
            case '➕ افزودن ادمین':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, 
                        "👮 لطفا آیدی عددی کاربر جدید را ارسال کنید:",
                        Keyboards::backKeyboard());
                    $this->setUserState('waiting_admin_id');
                }
                break;
                
            case '🗑 حذف ادمین':
                if ($this->isAdmin()) {
                    $this->showAdminList();
                }
                break;
                
            case '📋 لیست ادمین ها':
                if ($this->isAdmin()) {
                    $this->showAllAdmins();
                }
                break;
                
            // ==================== مدیریت کانال ====================
            case '➕ افزودن کانال':
                if ($this->isAdmin()) {
                    $this->telegram->sendMessage($this->chat_id, 
                        "📢 لطفا اطلاعات کانال را به این صورت ارسال کنید:\n\n" .
                        "فرمت: `آیدی کانال | عنوان کانال | لینک کانال`\n\n" .
                        "مثال:\n" .
                        "`@mychannel | کانال من | https://t.me/mychannel`",
                        Keyboards::backKeyboard());
                    $this->setUserState('waiting_channel_info');
                }
                break;
                
            case '🗑 حذف کانال':
                if ($this->isAdmin()) {
                    $this->showChannelList();
                }
                break;
                
            case '📋 لیست کانال ها':
                if ($this->isAdmin()) {
                    $this->showAllChannels();
                }
                break;
                
            case '🔙 بازگشت':
                $this->clearUserState();
                $this->telegram->sendMessage($this->chat_id, "🔙 بازگشت به منوی اصلی:", Keyboards::mainMenu());
                break;
                
            case '🔙 بازگشت به منو':
                $this->clearUserState();
                $this->telegram->sendMessage($this->chat_id, "🔙 بازگشت به منوی اصلی:", Keyboards::mainMenu());
                break;
        }
    }
    
    // ==================== مدیریت وضعیت‌ها ====================
     private function handleState($state) {
        // ۱. مدیریت دکمه لغو
        if ($this->text == '❌ لغو') {
            $this->clearUserState();
            $this->telegram->sendMessage($this->chat_id, "❌ عملیات لغو شد.", Keyboards::mainMenu());
            return;
        }

        // ۲. مدیریت وضعیت‌های JSON (افزودن چندگانه فیلم)
        // اصلاح: استفاده از json_decode به جای strpos برای اطمینان
        $stateData = json_decode($state, true);
        
        if (is_array($stateData) && isset($stateData['action'])) {
            // مدیریت دکمه پایان افزودن
            if ($this->text == '✅ پایان افزودن') {
                $this->finishAddingMovies();
                return;
            }
            
            // مدیریت دریافت فیلم
            if (strpos($stateData['action'], 'waiting_movie_') === 0) {
                $this->accumulateMovie($stateData);
                return;
            }
        }
        
        // ۳. مدیریت سایر وضعیت‌های تک مرحله‌ای
        switch ($state) {
            case 'waiting_ad_content':
                $this->saveAdvertisement();
                break;
                
            case 'waiting_broadcast':
                $this->sendBroadcast();
                break;
                
            case 'waiting_admin_id':
                $this->addNewAdmin();
                break;
                
            case 'waiting_channel_info':
                $this->addNewChannel();
                break;
        }
    }

    // ==================== توابع ادمین ====================
    private function showUserStats() {
        $total = $this->db->querySingle("SELECT COUNT(*) FROM users");
        $today = $this->db->querySingle("SELECT COUNT(*) FROM users WHERE DATE(join_date) = DATE('now')");
        $week = $this->db->querySingle("SELECT COUNT(*) FROM users WHERE join_date >= DATE('now', '-7 days')");
        
        $text = "📊 آمار کاربران ربات:\n\n";
        $text .= "👥 کل کاربران: <b>{$total}</b>\n";
        $text .= "📅 عضو شده امروز: <b>{$today}</b>\n";
        $text .= "📆 عضو شده این هفته: <b>{$week}</b>\n";
        
        $this->telegram->sendMessage($this->chat_id, $text, Keyboards::adminPanel());
    }
    
    private function saveAdvertisement() {
        $content = '';
        
        if (isset($this->message['text'])) {
            $content = $this->message['text'];
        } elseif (isset($this->message['video'])) {
            $content = $this->message['video']['file_id'];
        } elseif (isset($this->message['photo'])) {
            $photo = end($this->message['photo']);
            $content = $photo['file_id'];
        }
        
        $stmt = $this->db->prepare("INSERT INTO advertisements (user_id, content) VALUES (:uid, :content)");
        $stmt->bindValue(':uid', $this->user_id, SQLITE3_INTEGER);
        $stmt->bindValue(':content', $content, SQLITE3_TEXT);
        $stmt->execute();
        
        $this->telegram->sendMessage($this->chat_id, 
            "✅ تبلیغ شما با موفقیت ثبت شد.\n" .
            "⏳ پس از بررسی توسط ادمین، نتیجه به شما اطلاع داده می‌شود.",
            Keyboards::mainMenu());
        
        // اطلاع به ادمین‌ها
        $admins = $this->db->query("SELECT user_id FROM admins");
        while ($admin = $admins->fetchArray()) {
            $this->telegram->sendMessage($admin['user_id'], 
                "📢 تبلیغ جدیدی ثبت شده است.\n" .
                "برای بررسی به پنل مدیریت مراجعه کنید.");
        }
        
        $this->clearUserState();
    }
    
    private function saveMovie($state) {
        $typeMap = [
            'waiting_movie_iranian' => 'iranian',
            'waiting_movie_foreign' => 'foreign',
            'waiting_movie_popular' => 'popular'
        ];
        
        $type = $typeMap[$state];
        $file_id = null;
        $file_type = 'text';
        $title = 'بدون عنوان';
        $description = '';
        
        if (isset($this->message['video'])) {
            $file_id = $this->message['video']['file_id'];
            $file_type = 'video';
            if (isset($this->message['caption'])) {
                $parts = explode("\n", $this->message['caption'], 2);
                $title = $parts[0];
                $description = isset($parts[1]) ? $parts[1] : '';
            }
        } elseif (isset($this->message['photo'])) {
            $photo = end($this->message['photo']);
            $file_id = $photo['file_id'];
            $file_type = 'photo';
            if (isset($this->message['caption'])) {
                $parts = explode("\n", $this->message['caption'], 2);
                $title = $parts[0];
                $description = isset($parts[1]) ? $parts[1] : '';
            }
        } elseif (isset($this->message['text'])) {
            $parts = explode("\n", $this->message['text'], 2);
            $title = $parts[0];
            $description = isset($parts[1]) ? $parts[1] : '';
        }
        
        if ($file_id) {
            $stmt = $this->db->prepare("INSERT INTO movies (type, title, description, file_id, file_type) VALUES (:type, :title, :desc, :fid, :ftype)");
            $stmt->bindValue(':type', $type, SQLITE3_TEXT);
            $stmt->bindValue(':title', $title, SQLITE3_TEXT);
            $stmt->bindValue(':desc', $description, SQLITE3_TEXT);
            $stmt->bindValue(':fid', $file_id, SQLITE3_TEXT);
            $stmt->bindValue(':ftype', $file_type, SQLITE3_TEXT);
            $stmt->execute();
            
            $typeNames = [
                'iranian' => 'ایرانی',
                'foreign' => 'خارجی',
                'popular' => 'محبوب'
            ];
            
            $this->telegram->sendMessage($this->chat_id, 
                "✅ فیلم {$typeNames[$type]} با موفقیت اضافه شد.\n" .
                "🎬 عنوان: {$title}",
                Keyboards::movieManagement());
        } else {
            $this->telegram->sendMessage($this->chat_id, 
                "⚠️ لطفا یک ویدیو یا عکس ارسال کنید.",
                Keyboards::backKeyboard());
            return;
        }
        
        $this->clearUserState();
    }
    
    private function showMovieListForDelete() {
        $movies = $this->db->query("SELECT id, title, type FROM movies ORDER BY id DESC LIMIT 20");
        $text = "🗑 لیست فیلم‌ها برای حذف:\n\n";
        $hasMovie = false;
        
        while ($movie = $movies->fetchArray(SQLITE3_ASSOC)) {
            $hasMovie = true;
            $typeNames = [
                'iranian' => '🇮🇷',
                'foreign' => '🌍',
                'popular' => '⭐'
            ];
            $icon = $typeNames[$movie['type']] ?? '🎬';
            $keyboard = Keyboards::inlineDelete($movie['id']);
            $this->telegram->sendMessage($this->chat_id, "{$icon} {$movie['title']}", $keyboard);
        }
        
        if (!$hasMovie) {
            $this->telegram->sendMessage($this->chat_id, "⚠️ فیلمی یافت نشد.", Keyboards::movieManagement());
        }
    }
    
    private function showAllMoviesList() {
        $iranian = $this->db->querySingle("SELECT COUNT(*) FROM movies WHERE type = 'iranian'");
        $foreign = $this->db->querySingle("SELECT COUNT(*) FROM movies WHERE type = 'foreign'");
        $popular = $this->db->querySingle("SELECT COUNT(*) FROM movies WHERE type = 'popular'");
        $total = $iranian + $foreign + $popular;
        
        $text = "📋 آمار فیلم‌های ربات:\n\n";
        $text .= "🎬 فیلم ایرانی: <b>{$iranian}</b>\n";
        $text .= "🎬 فیلم خارجی: <b>{$foreign}</b>\n";
        $text .= "⭐ فیلم محبوب: <b>{$popular}</b>\n";
        $text .= "━━━━━━━━━━━━━━━━━━━━\n";
        $text .= "📊 مجموع: <b>{$total}</b>";
        
        $this        ->telegram->sendMessage($this->chat_id, $text, Keyboards::movieManagement());
    }
    
    private function addNewAdmin() {
        $admin_id = trim($this->text);
        
        if (!is_numeric($admin_id)) {
            $this->telegram->sendMessage($this->chat_id, "⚠️ لطفا یک آیدی عددی معتبر ارسال کنید.", Keyboards::backKeyboard());
            return;
        }
        
        $admin_id = intval($admin_id);
        
        if ($admin_id == $this->user_id) {
            $this->telegram->sendMessage($this->chat_id, "⚠️ شما خودتان ادمین هستید.", Keyboards::adminManagement());
            $this->clearUserState();
            return;
        }
        
        $check = $this->db->querySingle("SELECT COUNT(*) FROM admins WHERE user_id = {$admin_id}");
        
        if ($check > 0) {
            $this->telegram->sendMessage($this->chat_id, "⚠️ این کاربر قبلا ادمین شده است.", Keyboards::adminManagement());
        } else {
            $stmt = $this->db->prepare("INSERT INTO admins (user_id, added_by) VALUES (:uid, :adder)");
            $stmt->bindValue(':uid', $admin_id, SQLITE3_INTEGER);
            $stmt->bindValue(':adder', $this->user_id, SQLITE3_INTEGER);
            $stmt->execute();
            
            $this->telegram->sendMessage($this->chat_id, "✅ ادمین جدید با موفقیت اضافه شد.\n🆔 آیدی: <code>{$admin_id}</code>", Keyboards::adminManagement());
            
            // اطلاع به ادمین جدید
            $this->telegram->sendMessage($admin_id, "🎉 شما به عنوان ادمین جدید ربات فیلم انتخاب شدید.\nبرای ورود /start را بزنید.");
        }
        
        $this->clearUserState();
    }
    
    private function showAdminList() {
        $admins = $this->db->query("SELECT id, user_id FROM admins WHERE user_id != " . ADMIN_ID);
        $hasAdmin = false;
        
        $this->telegram->sendMessage($this->chat_id, "👮 لیست ادمین‌ها برای حذف:");
        
        while ($admin = $admins->fetchArray(SQLITE3_ASSOC)) {
            $hasAdmin = true;
            $keyboard = [
                'inline_keyboard' => [
                    [['text' => '🗑 حذف', 'callback_data' => "deladmin_{$admin['id']}"]]
                ]
            ];
            $this->telegram->sendMessage($this->chat_id, "🆔 آیدی: <code>{$admin['user_id']}</code>", $keyboard);
        }
        
        if (!$hasAdmin) {
            $this->telegram->sendMessage($this->chat_id, "⚠️ ادمین دیگری وجود ندارد.", Keyboards::adminManagement());
        }
    }
    
    private function showAllAdmins() {
        $admins = $this->db->query("SELECT user_id FROM admins");
        $text = "📋 لیست تمام ادمین‌ها:\n\n";
        $count = 0;
        
        while ($admin = $admins->fetchArray(SQLITE3_ASSOC)) {
            $count++;
            $text .= "{$count}. <code>{$admin['user_id']}</code>\n";
        }
        
        $text .= "\n👥 مجموع: <b>{$count}</b>";
        $this->telegram->sendMessage($this->chat_id, $text, Keyboards::adminManagement());
    }
    
    private function addNewChannel() {
        $parts = explode('|', $this->text);
        
        if (count($parts) < 3) {
            $this->telegram->sendMessage($this->chat_id, 
                "⚠️ فرمت صحیح نیست.\n" .
                "فرمت صحیح: `آیدی کانال | عنوان کانال | لینک کانال`",
                Keyboards::backKeyboard());
            return;
        }
        
        $channel_id = trim($parts[0]);
        $channel_title = trim($parts[1]);
        $channel_link = trim($parts[2]);
        
        $stmt = $this->db->prepare("INSERT INTO channels (channel_id, channel_title, channel_link) VALUES (:cid, :ctitle, :clink)");
        $stmt->bindValue(':cid', $channel_id, SQLITE3_TEXT);
        $stmt->bindValue(':ctitle', $channel_title, SQLITE3_TEXT);
        $stmt->bindValue(':clink', $channel_link, SQLITE3_TEXT);
        
        if ($stmt->execute()) {
            $this->telegram->sendMessage($this->chat_id, 
                "✅ کانال با موفقیت اضافه شد.\n" .
                "📢 عنوان: {$channel_title}",
                Keyboards::channelManagement());
        } else {
            $this->telegram->sendMessage($this->chat_id, "⚠️ خطا در افزودن کانال. ممکن است قبلا وجود داشته باشد.", Keyboards::channelManagement());
        }
        
        $this->clearUserState();
    }
    
    private function showChannelList() {
        $channels = $this->db->query("SELECT id, channel_title, channel_id FROM channels");
        $hasChannel = false;
        
        $this->telegram->sendMessage($this->chat_id, "📢 لیست کانال‌ها برای حذف:");
        
        while ($channel = $channels->fetchArray(SQLITE3_ASSOC)) {
            $hasChannel = true;
            $keyboard = [
                'inline_keyboard' => [
                    [['text' => '🗑 حذف', 'callback_data' => "delchannel_{$channel['id']}"]]
                ]
            ];
            $this->telegram->sendMessage($this->chat_id, "📢 {$channel['channel_title']} ({$channel['channel_id']})", $keyboard);
        }
        
        if (!$hasChannel) {
            $this->telegram->sendMessage($this->chat_id, "⚠️ کانالی ثبت نشده است.", Keyboards::channelManagement());
        }
    }
    
    private function showAllChannels() {
        $channels = $this->db->query("SELECT channel_title, channel_link FROM channels");
        $text = "📋 لیست کانال‌های اجباری:\n\n";
        $count = 0;
        
        while ($channel = $channels->fetchArray(SQLITE3_ASSOC)) {
            $count++;
            $text .= "{$count}. <a href=\"{$channel['channel_link']}\">{$channel['channel_title']}</a>\n";
        }
        
        $text .= "\n📢 مجموع: <b>{$count}</b>";
        $this->telegram->sendMessage($this->chat_id, $text, Keyboards::channelManagement());
    }
    
    private function sendBroadcast() {
        $users = $this->db->query("SELECT user_id FROM users");
        $sent = 0;
        $failed = 0;
        
        $this->telegram->sendMessage($this->chat_id, "⏳ در حال ارسال پیام به کاربران...", Keyboards::removeKeyboard());
        
        // تشخیص نوع محتوا
        $content_type = 'text';
        $file_id = null;
        $text_content = null;
        
        if (isset($this->message['text'])) {
            $text_content = $this->message['text'];
            $content_type = 'text';
        } elseif (isset($this->message['video'])) {
            $file_id = $this->message['video']['file_id'];
            $text_content = isset($this->message['caption']) ? $this->message['caption'] : '';
            $content_type = 'video';
        } elseif (isset($this->message['photo'])) {
            $photo = end($this->message['photo']);
            $file_id = $photo['file_id'];
            $text_content = isset($this->message['caption']) ? $this->message['caption'] : '';
            $content_type = 'photo';
        }
        
        while ($user = $users->fetchArray(SQLITE3_ASSOC)) {
            $uid = $user['user_id'];
            
            // عدم ارسال به خود فرستنده
            if ($uid == $this->user_id) continue;
            
            if ($content_type == 'text') {
                $res = $this->telegram->sendMessage($uid, $text_content);
            } elseif ($content_type == 'video') {
                $res = $this->telegram->sendVideo($uid, $file_id, $text_content);
            } elseif ($content_type == 'photo') {
                $res = $this->telegram->sendPhoto($uid, $file_id, $text_content);
            }
            
            if (isset($res['ok']) && $res['ok']) {
                $sent++;
            } else {
                $failed++;
            }
            
            // جلوگیری از محدودیت Flood
            usleep(50000); // تاخیر 50 میلی‌ثانیه
        }
        
        $this->telegram->sendMessage($this->chat_id, 
            "✅ ارسال همگانی انجام شد.\n\n" .
            "📨 ارسال شده: <b>{$sent}</b>\n" .
            "❌ خطا: <b>{$failed}</b>",
            Keyboards::adminPanel());
            
        $this->clearUserState();
    }
    
    // ==================== مدیریت Callback ====================
     public function handleCallback() {
        $data = $this->callback['data'];
        $message_id = $this->callback['message']['message_id'];
        
        // پاسخ به Callback برای حذف حالت لودینگ
        $this->telegram->answerCallbackQuery($this->callback['id']);
        
        // ================= بخش جدید: بررسی دکمه عضو شدم =================
        if ($data == 'check_subscription') {
            $not_joined = $this->checkChannelSubscription();
            
            if (empty($not_joined)) {
                // کاربر عضو شده است
                $this->telegram->deleteMessage($this->chat_id, $message_id); // حذف پیام درخواست عضویت
                $this->saveUser(); // ذخیره کاربر در دیتابیس
                
                $welcome_text = "🎉 به ربات فیلم خوش آمدید!\n\nیکی از گزینه‌های زیر را انتخاب کنید:";
                $this->telegram->sendMessage($this->chat_id, $welcome_text, Keyboards::mainMenu());
            } else {
                // کاربر هنوز عضو نشده، پیام خطا نمایش داده می‌شود
                $this->telegram->answerCallbackQuery($this->callback['id'], "❌ شما هنوز در تمام کانال‌ها عضو نشده‌اید!", true);
            }
            return; // پایان پردازش
        }
        // ===============================================================

        // دکمه بعدی
        if (strpos($data, 'next_') === 0) {
            $parts = explode('_', $data);
            $type = $parts[1];
            $offset = intval($parts[2]);
            
            // حذف پیام دکمه بعدی قبلی
            $this->telegram->deleteMessage($this->chat_id, $message_id);
            
            // حذف فیلم‌های قبلی
            $session = $this->getMovieSession();
            if ($session && isset($session['msg_ids'])) {
                $this->deletePreviousMessages($session['msg_ids']);
            }
            
            // نمایش فیلم‌های بعدی
            $this->showMovies($type, $offset);
        }
        
        // حذف فیلم
        elseif (strpos($data, 'delmovie_') === 0) {
            $movie_id = intval(str_replace('delmovie_', '', $data));
            
            $this->db->exec("DELETE FROM movies WHERE id = {$movie_id}");
            
            $this->telegram->editMessageText($this->chat_id, $message_id, "🗑 فیلم با موفقیت حذف شد.");
        }
        
        // حذف ادمین
        elseif (strpos($data, 'deladmin_') === 0) {
            $admin_row_id = intval(str_replace('deladmin_', '', $data));
            
            $this->db->exec("DELETE FROM admins WHERE id = {$admin_row_id}");
            
            $this->telegram->editMessageText($this->chat_id, $message_id, "🗑 ادمین با موفقیت حذف شد.");
        }
        
        // حذف کانال
        elseif (strpos($data, 'delchannel_') === 0) {
            $channel_row_id = intval(str_replace('delchannel_', '', $data));
            
            $this->db->exec("DELETE FROM channels WHERE id = {$channel_row_id}");
            
         $this->telegram->editMessageText($this->chat_id, $message_id, "🗑 کانال با موفقیت حذف شد.");
        }
    }


    // ==================== اجرای اصلی ربات ====================
    public function run() {
        if (isset($this->update['callback_query'])) {
            $this->handleCallback();
        } elseif (isset($this->update['message'])) {
            $this->handleMessage();
        }
    }
}

// ==================== نقطه شروع برنامه ====================

// اطمینان از وجود جدول user_states
$db_init = new SQLite3(DB_FILE);
$db_init->exec("
    CREATE TABLE IF NOT EXISTS user_states (
        user_id INTEGER PRIMARY KEY,
        state TEXT
    )
");
$db_init->close();

// اجرای ربات
try {
    $bot = new MovieBot();
    $bot->run();
} catch (Exception $e) {
    // ثبت خطا در لاگ (اختیاری)
    file_put_contents('error_log.txt', date('Y-m-d H:i:s') . " - " . $e->getMessage() . "\n", FILE_APPEND);
}

       