<?php
/**
 * ربات ریپورتر تلگرام - اسکریپت نصب و ساخت ZIP
 * کافیه این فایل رو روی هاست آپلود کنی و اجرا کنی
 */

// ============================================
// تنظیمات اولیه
// ============================================
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: text/html; charset=utf-8');

// اطلاعات پیش‌فرض (بعداً میتونی تغییر بدی)
$defaultConfig = [
    'BOT_TOKEN' => '8830673953:AAEuhfaFQ-vKNRvhoilWtjyKXJCOa86OAQY',
    'OWNER_ID' => '6681317209',
    'OWNER_USERNAME' => 'admin',
    'DB_HOST' => 'localhost',
    'DB_NAME' => 'reporter_bot',
    'DB_USER' => 'root',
    'DB_PASS' => '',
    'BOT_URL' => 'https://yourdomain.com/bot/',
    'CARD_NUMBER' => '6037-9975-1234-5678',
    'CARD_HOLDER' => 'پارسا تریاکیان'
];

// ============================================
// اگر فرم ارسال شده، فایل‌ها رو بساز
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_bot'])) {
    
    $botToken = $_POST['bot_token'] ?? $defaultConfig['BOT_TOKEN'];
    $ownerId = $_POST['owner_id'] ?? $defaultConfig['OWNER_ID'];
    $ownerUsername = $_POST['owner_username'] ?? $defaultConfig['OWNER_USERNAME'];
    $dbHost = $_POST['db_host'] ?? $defaultConfig['DB_HOST'];
    $dbName = $_POST['db_name'] ?? $defaultConfig['DB_NAME'];
    $dbUser = $_POST['db_user'] ?? $defaultConfig['DB_USER'];
    $dbPass = $_POST['db_pass'] ?? $defaultConfig['DB_PASS'];
    $botUrl = $_POST['bot_url'] ?? $defaultConfig['BOT_URL'];
    $cardNumber = $_POST['card_number'] ?? $defaultConfig['CARD_NUMBER'];
    $cardHolder = $_POST['card_holder'] ?? $defaultConfig['CARD_HOLDER'];
    
    // ساخت فایل‌ها
    $files = createBotFiles([
        'BOT_TOKEN' => $botToken,
        'OWNER_ID' => $ownerId,
        'OWNER_USERNAME' => $ownerUsername,
        'DB_HOST' => $dbHost,
        'DB_NAME' => $dbName,
        'DB_USER' => $dbUser,
        'DB_PASS' => $dbPass,
        'BOT_URL' => $botUrl,
        'CARD_NUMBER' => $cardNumber,
        'CARD_HOLDER' => $cardHolder
    ]);
    
    // ساخت ZIP
    $zipName = 'reporter_bot_' . date('Y-m-d_H-i-s') . '.zip';
    $zip = new ZipArchive();
    $zip->open($zipName, ZipArchive::CREATE);
    
    foreach ($files as $filename => $content) {
        $zip->addFromString($filename, $content);
    }
    
    $zip->close();
    
    // دانلود فایل
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $zipName . '"');
    header('Content-Length: ' . filesize($zipName));
    readfile($zipName);
    unlink($zipName);
    exit;
}

// ============================================
// تابع ساخت همه فایل‌ها
// ============================================
function createBotFiles($config) {
    $files = [];
    
    // 1. index.php
    $files['index.php'] = '<?php
/**
 * ربات ریپورتر تلگرام
 * ورژن: 3.0
 * توسعه‌دهنده: Reporter Bot Team
 */

error_reporting(0);
ini_set("display_errors", 0);
date_default_timezone_set("Asia/Tehran");

// لود فایل‌های ضروری
require_once __DIR__ . "/config.php";
require_once __DIR__ . "/database.php";
require_once __DIR__ . "/bot.php";

// دریافت آپدیت از تلگرام
$content = file_get_contents("php://input");
$update = json_decode($content, true);

if (!$update) {
    // تست سلامت ربات
    $bot = new ReporterBot();
    $bot->checkHealth();
    exit;
}

// پردازش آپدیت
try {
    $bot = new ReporterBot();
    $bot->processUpdate($update);
} catch (Exception $e) {
    error_log("Bot Error: " . $e->getMessage());
    // ذخیره خطا در فایل
    file_put_contents(__DIR__ . "/error.log", date("Y-m-d H:i:s") . " - " . $e->getMessage() . "\n", FILE_APPEND);
}
?>';

    // 2. config.php
    $files['config.php'] = '<?php
// ============================================
// تنظیمات ربات ریپورتر
// ============================================

// توکن ربات
define("BOT_TOKEN", "' . $config['BOT_TOKEN'] . '");

// اطلاعات ادمین اصلی
define("OWNER_ID", "' . $config['OWNER_ID'] . '");
define("OWNER_USERNAME", "' . $config['OWNER_USERNAME'] . '");

// تنظیمات دیتابیس
define("DB_HOST", "' . $config['DB_HOST'] . '");
define("DB_NAME", "' . $config['DB_NAME'] . '");
define("DB_USER", "' . $config['DB_USER'] . '");
define("DB_PASS", "' . $config['DB_PASS'] . '");

// آدرس ربات
define("BOT_URL", "' . $config['BOT_URL'] . '");

// اطلاعات پرداخت
define("CARD_NUMBER", "' . $config['CARD_NUMBER'] . '");
define("CARD_HOLDER", "' . $config['CARD_HOLDER'] . '");

// تنظیمات پورسانت و برداشت
define("COMMISSION_PERCENT", 20);
define("MIN_WITHDRAW", 100000);
define("REFERRAL_BONUS", 5000);

// نسخه ربات
define("BOT_VERSION", "3.0");

// پلن‌های اشتراک
$GLOBALS["plans"] = [
    "1month" => ["name" => "یک ماهه", "price" => 100000, "days" => 30, "traffic" => "50GB"],
    "2month" => ["name" => "دو ماهه", "price" => 180000, "days" => 60, "traffic" => "120GB"],
    "3month" => ["name" => "سه ماهه", "price" => 250000, "days" => 90, "traffic" => "200GB"],
    "6month" => ["name" => "شش ماهه", "price" => 450000, "days" => 180, "traffic" => "500GB"],
    "1year" => ["name" => "یک ساله", "price" => 800000, "days" => 365, "traffic" => "نامحدود"]
];

// سطوح دسترسی
$GLOBALS["accessLevels"] = [
    "owner" => 100,
    "super_admin" => 80,
    "admin" => 50,
    "moderator" => 30,
    "user" => 10
];

// منطقه زمانی
date_default_timezone_set("Asia/Tehran");
?>';

    // 3. database.php
    $files['database.php'] = '<?php
class Database {
    private $conn;
    private static $instance = null;
    
    public function __construct() {
        try {
            $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
            ];
            $this->conn = new PDO($dsn, DB_USER, DB_PASS, $options);
            $this->createTables();
        } catch(PDOException $e) {
            die("❌ خطا در اتصال به دیتابیس: " . $e->getMessage());
        }
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function createTables() {
        // جدول کاربران
        $this->conn->exec("CREATE TABLE IF NOT EXISTS users (
            user_id BIGINT PRIMARY KEY,
            username VARCHAR(255) DEFAULT NULL,
            first_name VARCHAR(255) DEFAULT NULL,
            phone VARCHAR(20) DEFAULT NULL,
            balance BIGINT DEFAULT 0,
            joined_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            referral_by BIGINT DEFAULT NULL,
            subscription_until TIMESTAMP NULL DEFAULT NULL,
            total_referrals INT DEFAULT 0,
            referral_earnings BIGINT DEFAULT 0,
            access_level INT DEFAULT 10,
            is_banned TINYINT DEFAULT 0,
            ban_reason TEXT DEFAULT NULL,
            total_purchases INT DEFAULT 0,
            INDEX idx_referral (referral_by),
            INDEX idx_access (access_level)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // جدول پرسنل
        $this->conn->exec("CREATE TABLE IF NOT EXISTS staff (
            user_id BIGINT PRIMARY KEY,
            username VARCHAR(255) DEFAULT NULL,
            full_name VARCHAR(255) DEFAULT NULL,
            role VARCHAR(50) DEFAULT NULL,
            access_level INT DEFAULT 50,
            added_by BIGINT DEFAULT NULL,
            added_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            permissions TEXT DEFAULT NULL,
            is_active TINYINT DEFAULT 1,
            INDEX idx_role (role)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // جدول زیرمجموعه‌ها
        $this->conn->exec("CREATE TABLE IF NOT EXISTS referrals (
            id INT AUTO_INCREMENT PRIMARY KEY,
            inviter_id BIGINT NOT NULL,
            invited_id BIGINT NOT NULL,
            date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            commission_paid BIGINT DEFAULT 0,
            UNIQUE KEY unique_referral (inviter_id, invited_id),
            INDEX idx_inviter (inviter_id),
            INDEX idx_invited (invited_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // جدول تراکنش‌ها
        $this->conn->exec("CREATE TABLE IF NOT EXISTS transactions (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id BIGINT NOT NULL,
            amount BIGINT NOT NULL,
            type VARCHAR(50) DEFAULT NULL,
            status VARCHAR(20) DEFAULT \"pending\",
            date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            plan VARCHAR(50) DEFAULT NULL,
            confirmed_by BIGINT DEFAULT NULL,
            receipt_file VARCHAR(255) DEFAULT NULL,
            INDEX idx_user (user_id),
            INDEX idx_status (status),
            INDEX idx_date (date)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // جدول برداشت‌ها
        $this->conn->exec("CREATE TABLE IF NOT EXISTS withdrawals (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id BIGINT NOT NULL,
            amount BIGINT NOT NULL,
            card_number VARCHAR(20) DEFAULT NULL,
            status VARCHAR(20) DEFAULT \"pending\",
            request_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            processed_date TIMESTAMP NULL DEFAULT NULL,
            processed_by BIGINT DEFAULT NULL,
            INDEX idx_user (user_id),
            INDEX idx_status (status)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // جدول لاگ‌ها
        $this->conn->exec("CREATE TABLE IF NOT EXISTS activity_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id BIGINT DEFAULT NULL,
            username VARCHAR(255) DEFAULT NULL,
            action VARCHAR(100) DEFAULT NULL,
            details TEXT DEFAULT NULL,
            timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_user (user_id),
            INDEX idx_action (action),
            INDEX idx_timestamp (timestamp)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // جدول کانال‌ها
        $this->conn->exec("CREATE TABLE IF NOT EXISTS channels (
            id INT AUTO_INCREMENT PRIMARY KEY,
            channel_id VARCHAR(255) UNIQUE NOT NULL,
            channel_name VARCHAR(255) DEFAULT NULL,
            type VARCHAR(20) DEFAULT NULL,
            added_by BIGINT DEFAULT NULL,
            added_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            is_required TINYINT DEFAULT 0
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // جدول تنظیمات
        $this->conn->exec("CREATE TABLE IF NOT EXISTS settings (
            setting_key VARCHAR(100) PRIMARY KEY,
            setting_value TEXT DEFAULT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        
        // اضافه کردن ادمین اصلی
        $stmt = $this->conn->prepare("INSERT IGNORE INTO staff (user_id, username, full_name, role, access_level) VALUES (?, ?, ?, \"owner\", 100)");
        $stmt->execute([OWNER_ID, OWNER_USERNAME, "مالک اصلی"]);
        
        $stmt = $this->conn->prepare("UPDATE users SET access_level = 100 WHERE user_id = ?");
        $stmt->execute([OWNER_ID]);
        
        // تنظیمات پیش‌فرض
        $defaultSettings = [
            "min_withdraw" => MIN_WITHDRAW,
            "commission_percent" => COMMISSION_PERCENT,
            "referral_bonus" => REFERRAL_BONUS,
            "bot_version" => BOT_VERSION,
            "support_username" => "@" . OWNER_USERNAME
        ];
        
        $stmt = $this->conn->prepare("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)");
        foreach ($defaultSettings as $key => $value) {
            $stmt->execute([$key, $value]);
        }
    }
    
    // متدهای کوئری
    public function query($sql, $params = []) {
        $stmt = $this->conn->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }
    
    public function fetch($sql, $params = []) {
        $stmt = $this->query($sql, $params);
        return $stmt->fetch();
    }
    
    public function fetchAll($sql, $params = []) {
        $stmt = $this->query($sql, $params);
        return $stmt->fetchAll();
    }
    
    public function insert($sql, $params = []) {
        $this->query($sql, $params);
        return $this->conn->lastInsertId();
    }
    
    // متدهای کاربران
    public function addUser($userId, $username, $firstName, $referralBy = null) {
        $user = $this->fetch("SELECT user_id FROM users WHERE user_id = ?", [$userId]);
        
        if (!$user) {
            $this->query("INSERT INTO users (user_id, username, first_name, referral_by) VALUES (?, ?, ?, ?)",
                [$userId, $username, $firstName, $referralBy]);
            
            if ($referralBy && $referralBy != $userId) {
                // ثبت زیرمجموعه
                $checkRef = $this->fetch("SELECT id FROM referrals WHERE inviter_id = ? AND invited_id = ?", 
                    [$referralBy, $userId]);
                
                if (!$checkRef) {
                    $this->query("INSERT INTO referrals (inviter_id, invited_id) VALUES (?, ?)",
                        [$referralBy, $userId]);
                    $this->query("UPDATE users SET total_referrals = total_referrals + 1 WHERE user_id = ?",
                        [$referralBy]);
                    
                    // هدیه ثبت‌نام
                    $bonus = REFERRAL_BONUS;
                    $this->query("UPDATE users SET referral_earnings = referral_earnings + ? WHERE user_id = ?",
                        [$bonus, $referralBy]);
                }
            }
        }
        
        return $this->getUser($userId);
    }
    
    public function getUser($userId) {
        return $this->fetch("SELECT * FROM users WHERE user_id = ?", [$userId]);
    }
    
    public function getUserAccess($userId) {
        $user = $this->getUser($userId);
        return $user ? $user["access_level"] : 10;
    }
    
    // متدهای پرسنل
    public function addStaff($userId, $username, $fullName, $role, $accessLevel, $addedBy) {
        $this->query("INSERT INTO staff (user_id, username, full_name, role, access_level, added_by) 
                     VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE full_name=?, role=?, access_level=?",
            [$userId, $username, $fullName, $role, $accessLevel, $addedBy, $fullName, $role, $accessLevel]);
        $this->query("UPDATE users SET access_level = ? WHERE user_id = ?", [$accessLevel, $userId]);
    }
    
    public function removeStaff($userId) {
        $this->query("DELETE FROM staff WHERE user_id = ?", [$userId]);
        $this->query("UPDATE users SET access_level = 10 WHERE user_id = ?", [$userId]);
    }
    
    public function getAllStaff() {
        return $this->fetchAll("SELECT * FROM staff WHERE is_active = 1 ORDER BY access_level DESC");
    }
    
    // متدهای مالی
    public function addTransaction($userId, $amount, $type, $plan = null, $receipt = null) {
        $sql = "INSERT INTO transactions (user_id, amount, type, plan, receipt_file) VALUES (?, ?, ?, ?, ?)";
        return $this->insert($sql, [$userId, $amount, $type, $plan, $receipt]);
    }
    
    public function confirmTransaction($txId, $confirmedBy) {
        $tx = $this->fetch("SELECT * FROM transactions WHERE id = ?", [$txId]);
        
        if ($tx && $tx["status"] == "pending") {
            $this->query("UPDATE transactions SET status = \"confirmed\", confirmed_by = ? WHERE id = ?",
                [$confirmedBy, $txId]);
            
            // فعال‌سازی اشتراک
            if ($tx["plan"] && isset($GLOBALS["plans"][$tx["plan"]])) {
                $days = $GLOBALS["plans"][$tx["plan"]]["days"];
                $this->addSubscription($tx["user_id"], $days);
                $this->query("UPDATE users SET total_purchases = total_purchases + 1 WHERE user_id = ?",
                    [$tx["user_id"]]);
            }
            
            // پورسانت معرف
            $user = $this->getUser($tx["user_id"]);
            if ($user && $user["referral_by"]) {
                $commission = intval($tx["amount"] * COMMISSION_PERCENT / 100);
                $this->query("UPDATE users SET referral_earnings = referral_earnings + ? WHERE user_id = ?",
                    [$commission, $user["referral_by"]]);
                $this->query("UPDATE referrals SET commission_paid = commission_paid + ? WHERE inviter_id = ? AND invited_id = ?",
                    [$commission, $user["referral_by"], $tx["user_id"]]);
            }
            
            return true;
        }
        return false;
    }
    
    public function addSubscription($userId, $days) {
        $user = $this->getUser($userId);
        $startDate = new DateTime();
        
        if ($user && $user["subscription_until"]) {
            $subDate = new DateTime($user["subscription_until"]);
            if ($subDate > $startDate) {
                $startDate = $subDate;
            }
        }
        
        $startDate->modify("+{$days} days");
        $this->query("UPDATE users SET subscription_until = ? WHERE user_id = ?",
            [$startDate->format("Y-m-d H:i:s"), $userId]);
    }
    
    public function getPendingTransactions() {
        return $this->fetchAll("SELECT t.*, u.username, u.first_name FROM transactions t 
                               LEFT JOIN users u ON t.user_id = u.user_id 
                               WHERE t.status = \"pending\" ORDER BY t.date DESC LIMIT 50");
    }
    
    public function requestWithdrawal($userId, $amount, $cardNumber) {
        $user = $this->getUser($userId);
        if ($user && $user["referral_earnings"] >= $amount) {
            $id = $this->insert("INSERT INTO withdrawals (user_id, amount, card_number) VALUES (?, ?, ?)",
                [$userId, $amount, $cardNumber]);
            $this->query("UPDATE users SET referral_earnings = referral_earnings - ? WHERE user_id = ?",
                [$amount, $userId]);
            return $id;
        }
        return false;
    }
    
    public function getPendingWithdrawals() {
        return $this->fetchAll("SELECT w.*, u.username, u.first_name FROM withdrawals w 
                               LEFT JOIN users u ON w.user_id = u.user_id 
                               WHERE w.status = \"pending\" ORDER BY w.request_date DESC");
    }
    
    public function confirmWithdrawal($withdrawalId, $processedBy) {
        $this->query("UPDATE withdrawals SET status = \"confirmed\", processed_date = NOW(), processed_by = ? WHERE id = ?",
            [$processedBy, $withdrawalId]);
    }
    
    // متدهای آماری
    public function getFullStats() {
        $stats = [];
        
        $stats["total_users"] = $this->fetch("SELECT COUNT(*) as cnt FROM users")["cnt"] ?? 0;
        $stats["total_admins"] = $this->fetch("SELECT COUNT(*) as cnt FROM users WHERE access_level >= 50")["cnt"] ?? 0;
        $stats["banned_users"] = $this->fetch("SELECT COUNT(*) as cnt FROM users WHERE is_banned = 1")["cnt"] ?? 0;
        
        $revenue = $this->fetch("SELECT COALESCE(SUM(amount), 0) as total, COUNT(*) as cnt FROM transactions WHERE status = \"confirmed\"");
        $stats["total_revenue"] = $revenue["total"] ?? 0;
        $stats["total_sales"] = $revenue["cnt"] ?? 0;
        
        $pending = $this->fetch("SELECT COALESCE(SUM(amount), 0) as total, COUNT(*) as cnt FROM transactions WHERE status = \"pending\"");
        $stats["pending_amount"] = $pending["total"] ?? 0;
        $stats["pending_count"] = $pending["cnt"] ?? 0;
        
        $stats["new_users_week"] = $this->fetch("SELECT COUNT(*) as cnt FROM users WHERE joined_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)")["cnt"] ?? 0;
        $stats["new_users_month"] = $this->fetch("SELECT COUNT(*) as cnt FROM users WHERE joined_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)")["cnt"] ?? 0;
        
        $weekRevenue = $this->fetch("SELECT COALESCE(SUM(amount), 0) as total FROM transactions WHERE status = \"confirmed\" AND date >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
        $stats["week_revenue"] = $weekRevenue["total"] ?? 0;
        
        return $stats;
    }
    
    // لاگ
    public function addLog($userId, $username, $action, $details = []) {
        $this->query("INSERT INTO activity_logs (user_id, username, action, details) VALUES (?, ?, ?, ?)",
            [$userId, $username, $action, json_encode($details, JSON_UNESCAPED_UNICODE)]);
    }
    
    public function getRecentLogs($limit = 50) {
        return $this->fetchAll("SELECT * FROM activity_logs ORDER BY timestamp DESC LIMIT ?", [$limit]);
    }
    
    // مسدودسازی
    public function banUser($userId, $reason) {
        $this->query("UPDATE users SET is_banned = 1, ban_reason = ? WHERE user_id = ?", [$reason, $userId]);
    }
    
    public function unbanUser($userId) {
        $this->query("UPDATE users SET is_banned = 0, ban_reason = NULL WHERE user_id = ?", [$userId]);
    }
    
    public function getBannedUsers() {
        return $this->fetchAll("SELECT * FROM users WHERE is_banned = 1");
    }
    
    // کانال‌ها
    public function addChannel($channelId, $channelName, $type, $addedBy, $isRequired = 0) {
        $this->query("INSERT INTO channels (channel_id, channel_name, type, added_by, is_required) 
                     VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE channel_name=?, is_required=?",
            [$channelId, $channelName, $type, $addedBy, $isRequired, $channelName, $isRequired]);
    }
    
    public function removeChannel($channelId) {
        $this->query("DELETE FROM channels WHERE channel_id = ?", [$channelId]);
    }
    
    public function getAllChannels() {
        return $this->fetchAll("SELECT * FROM channels ORDER BY added_date DESC");
    }
    
    public function getRequiredChannels() {
        return $this->fetchAll("SELECT * FROM channels WHERE is_required = 1");
    }
}
?>';

    // 4. bot.php (کلاس اصلی)
    $files['bot.php'] = '<?php
class ReporterBot {
    private $db;
    private $apiUrl;
    
    public function __construct() {
        $this->db = Database::getInstance();
        $this->apiUrl = "https://api.telegram.org/bot" . BOT_TOKEN;
    }
    
    public function checkHealth() {
        header("Content-Type: application/json");
        echo json_encode([
            "status" => "active",
            "bot_version" => BOT_VERSION,
            "time" => date("Y-m-d H:i:s"),
            "message" => "ربات با موفقیت راه‌اندازی شده است! ✅"
        ], JSON_UNESCAPED_UNICODE);
    }
    
    public function processUpdate($update) {
        try {
            if (isset($update["message"])) {
                $this->handleMessage($update["message"]);
            } elseif (isset($update["callback_query"])) {
                $this->handleCallback($update["callback_query"]);
            } elseif (isset($update["pre_checkout_query"])) {
                $this->answerPreCheckout($update["pre_checkout_query"]["id"]);
            }
        } catch (Exception $e) {
            error_log("Process Error: " . $e->getMessage());
        }
    }
    
    private function handleMessage($message) {
        $chatId = $message["chat"]["id"];
        $userId = $message["from"]["id"];
        $text = $message["text"] ?? "";
        $firstName = $message["from"]["first_name"] ?? "کاربر";
        $username = $message["from"]["username"] ?? "";
        
        // بررسی مسدود بودن
        $user = $this->db->getUser($userId);
        if ($user && $user["is_banned"]) {
            $this->sendMessage($chatId, "⛔ حساب شما مسدود شده است.\n📝 دلیل: " . $user["ban_reason"]);
            return;
        }
        
        // ثبت کاربر
        $referralBy = null;
        if (preg_match("/\/start\s+ref_(\d+)/", $text, $matches)) {
            $referralBy = $matches[1];
        }
        
        $this->db->addUser($userId, $username, $firstName, $referralBy);
        $accessLevel = $this->db->getUserAccess($userId);
        
        // منوی اصلی
        if (strpos($text, "/start") === 0) {
            $this->sendWelcomeMessage($chatId, $firstName, $userId, $accessLevel);
        } elseif ($text === "🔑 خرید اشتراک") {
            $this->showPlans($chatId);
        } elseif ($text === "👤 پروفایل من") {
            $this->showProfile($chatId, $userId);
        } elseif ($text === "💰 کیف پول") {
            $this->showWallet($chatId, $userId);
        } elseif ($text === "🔗 زیرمجموعه‌گیری") {
            $this->showReferralLink($chatId, $userId);
        } elseif ($text === "📊 آمار من") {
            $this->showUserStats($chatId, $userId);
        } elseif ($text === "📞 پشتیبانی") {
            $this->showSupport($chatId);
        } elseif ($text === "🎛️ پنل مدیریت" && $accessLevel >= 50) {
            $this->showAdminPanel($chatId, $userId);
        } else {
            $this->sendMainMenu($chatId, $accessLevel);
        }
    }
    
    private function handleCallback($callback) {
        $callbackId = $callback["id"];
        $userId = $callback["from"]["id"];
        $data = $callback["data"];
        $messageId = $callback["message"]["message_id"] ?? null;
        $chatId = $callback["message"]["chat"]["id"] ?? null;
        
        // پاسخ به کال‌بک
        $this->answerCallback($callbackId);
        
        // پردازش کال‌بک‌ها
        if (strpos($data, "buy_") === 0) {
            $planId = str_replace("buy_", "", $data);
            $this->showPaymentInfo($chatId, $messageId, $planId);
        } elseif (strpos($data, "pay_card_") === 0) {
            $planId = str_replace("pay_card_", "", $data);
            $this->showCardPayment($chatId, $messageId, $planId);
        } elseif (strpos($data, "paid_") === 0) {
            $planId = str_replace("paid_", "", $data);
            $this->processPayment($chatId, $messageId, $userId, $planId);
        } elseif (strpos($data, "confirm_tx_") === 0) {
            $txId = str_replace("confirm_tx_", "", $data);
            $this->confirmTransaction($chatId, $messageId, $userId, $txId);
        } elseif (strpos($data, "reject_tx_") === 0) {
            $txId = str_replace("reject_tx_", "", $data);
            $this->rejectTransaction($chatId, $messageId, $userId, $txId);
        } elseif (strpos($data, "confirm_withdraw_") === 0) {
            $wId = str_replace("confirm_withdraw_", "", $data);
            $this->confirmWithdrawal($chatId, $messageId, $userId, $wId);
        } elseif ($data === "admin_dashboard") {
            $this->showDashboard($chatId, $messageId, $userId);
        } elseif ($data === "admin_transactions") {
            $this->showPendingTransactions($chatId, $messageId, $userId);
        } elseif ($data === "admin_staff") {
            $this->showStaffList($chatId, $messageId, $userId);
        } elseif ($data === "admin_withdrawals") {
            $this->showPendingWithdrawals($chatId, $messageId, $userId);
        } elseif ($data === "admin_back") {
            $this->editAdminPanel($chatId, $messageId, $userId);
        } elseif ($data === "back_main" || $data === "admin_exit") {
            $this->deleteMessage($chatId, $messageId);
        }
    }
    
    // ========== متدهای ارسال پیام ==========
    private function sendMessage($chatId, $text, $keyboard = null, $parseMode = "HTML") {
        $params = [
            "chat_id" => $chatId,
            "text" => $text,
            "parse_mode" => $parseMode,
            "disable_web_page_preview" => true
        ];
        
        if ($keyboard) {
            $params["reply_markup"] = json_encode($keyboard);
        }
        
        return $this->callAPI("sendMessage", $params);
    }
    
    private function editMessage($chatId, $messageId, $text, $keyboard = null, $parseMode = "HTML") {
        $params = [
            "chat_id" => $chatId,
            "message_id" => $messageId,
            "text" => $text,
            "parse_mode" => $parseMode
        ];
        
        if ($keyboard) {
            $params["reply_markup"] = json_encode($keyboard);
        }
        
        return $this->callAPI("editMessageText", $params);
    }
    
    private function deleteMessage($chatId, $messageId) {
        return $this->callAPI("deleteMessage", [
            "chat_id" => $chatId,
            "message_id" => $messageId
        ]);
    }
    
    private function answerCallback($callbackId, $text = "", $showAlert = false) {
        return $this->callAPI("answerCallbackQuery", [
            "callback_query_id" => $callbackId,
            "text" => $text,
            "show_alert" => $showAlert
        ]);
    }
    
    private function callAPI($method, $params) {
        $url = $this->apiUrl . "/" . $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_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            error_log("CURL Error: " . $error);
        }
        
        return json_decode($response, true);
    }
    
    // ========== متدهای منو و نمایش ==========
    private function sendMainMenu($chatId, $accessLevel = 10) {
        $keyboard = [
            "keyboard" => [
                ["🔑 خرید اشتراک", "👤 پروفایل من"],
                ["💰 کیف پول", "🔗 زیرمجموعه‌گیری"],
                ["📊 آمار من", "📞 پشتیبانی"]
            ],
            "resize_keyboard" => true,
            "one_time_keyboard" => false
        ];
        
        if ($accessLevel >= 50) {
            $keyboard["keyboard"][] = ["🎛️ پنل مدیریت"];
        }
        
        $text = "🎯 <b>منوی اصلی</b>\n\nلطفاً یکی از گزینه‌ها را انتخاب کنید:";
        $this->sendMessage($chatId, $text, $keyboard);
    }
    
    private function sendWelcomeMessage($chatId, $firstName, $userId, $accessLevel) {
        $botUsername = $this->getBotUsername();
        $refLink = "https://t.me/{$botUsername}?start=ref_{$userId}";
        
        $text = "🎉 <b>سلام {$firstName} عزیز!</b>\n\n";
        $text .= "به ربات ریپورتر حرفه‌ای خوش آمدید! 🚀\n\n";
        $text .= "🔹 <b>امکانات ربات:</b>\n";
        $text .= "• خرید اشتراک VPN با قیمت مناسب\n";
        $text .= "• زیرمجموعه‌گیری و کسب درآمد 💰\n";
        $text .= "• پورسانت " . COMMISSION_PERCENT . "٪ از خرید زیرمجموعه\n";
        $text .= "• هدیه " . number_format(REFERRAL_BONUS) . " تومانی ثبت‌نام\n\n";
        $text .= "🔗 <b>لینک دعوت شما:</b>\n<code>{$refLink}</code>";
        
        $this->sendMessage($chatId, $text);
        $this->sendMainMenu($chatId, $accessLevel);
        $this->db->addLog($userId, "", "start_bot", []);
    }
    
    private function showPlans($chatId) {
        $keyboard = ["inline_keyboard" => []];
        
        foreach ($GLOBALS["plans"] as $planId => $plan) {
            $keyboard["inline_keyboard"][] = [[
                "text" => "📦 {$plan["name"]} - " . number_format($plan["price"]) . " تومان ({$plan["traffic"]})",
                "callback_data" => "buy_{$planId}"
            ]];
        }
        
        $keyboard["inline_keyboard"][] = [["text" => "🔙 بازگشت", "callback_data" => "back_main"]];
        
        $text = "📦 <b>پلن‌های اشتراک</b>\n\n";
        $text .= "برای مشاهده جزئیات و خرید، یک پلن انتخاب کنید:\n\n";
        
        foreach ($GLOBALS["plans"] as $planId => $plan) {
            $text .= "• <b>{$plan["name"]}</b>: " . number_format($plan["price"]) . " تومان | {$plan["traffic"]}\n";
        }
        
        $this->sendMessage($chatId, $text, $keyboard);
    }
    
    private function showProfile($chatId, $userId) {
        $user = $this->db->getUser($userId);
        
        if (!$user) {
            $this->sendMessage($chatId, "❌ کاربر یافت نشد!");
            return;
        }
        
        // وضعیت اشتراک
        $subStatus = "❌ غیرفعال";
        if ($user["subscription_until"]) {
            $subDate = new DateTime($user["subscription_until"]);
            $now = new DateTime();
            if ($subDate > $now) {
                $daysLeft = $now->diff($subDate)->days;
                $subStatus = "✅ فعال ({$daysLeft} روز باقی‌مانده)";
            } else {
                $subStatus = "⚠️ منقضی شده";
            }
        }
        
        $text = "👤 <b>پروفایل کاربری</b>\n\n";
        $text .= "🆔 شناسه: <code>{$user["user_id"]}</code>\n";
        $text .= "👤 نام: {$user["first_name"]}\n";
        $text .= "📱 تلفن: " . ($user["phone"] ?: "ثبت نشده") . "\n\n";
        $text .= "💳 <b>وضعیت اشتراک:</b> {$subStatus}\n";
        $text .= "📅 عضو از: " . date("Y/m/d", strtotime($user["joined_date"])) . "\n\n";
        $text .= "🔗 زیرمجموعه‌ها: <b>{$user["total_referrals"]}</b> نفر\n";
        $text .= "💰 درآمد: <b>" . number_format($user["referral_earnings"]) . "</b> تومان\n";
        $text .= "🛒 خریدها: <b>{$user["total_purchases"]}</b>";
        
        $this->sendMessage($chatId, $text);
    }
    
    private function showWallet($chatId, $userId) {
        $user = $this->db->getUser($userId);
        $earnings = $user ? $user["referral_earnings"] : 0;
        
        $keyboard = ["inline_keyboard" => [
            [["text" => "💰 برداشت موجودی", "callback_data" => "withdraw_request"]],
            [["text" => "🔙 بازگشت", "callback_data" => "back_main"]]
        ]];
        
        $text = "💰 <b>کیف پول شما</b>\n\n";
        $text .= "💸 موجودی قابل برداشت: <b>" . number_format($earnings) . " تومان</b>\n\n";
        $text .= "📊 پورسانت: <b>" . COMMISSION_PERCENT . "٪</b> از خرید زیرمجموعه\n";
        $text .= "🎁 هدیه ثبت‌نام: <b>" . number_format(REFERRAL_BONUS) . " تومان</b>\n\n";
        $text .= "⚠️ حداقل برداشت: <b>" . number_format(MIN_WITHDRAW) . " تومان</b>";
        
        $this->sendMessage($chatId, $text, $keyboard);
    }
    
    private function showReferralLink($chatId, $userId) {
        $botUsername = $this->getBotUsername();
        $refLink = "https://t.me/{$botUsername}?start=ref_{$userId}";
        $user = $this->db->getUser($userId);
        $refCount = $user ? $user["total_referrals"] : 0;
        
        $text = "🔗 <b>زیرمجموعه‌گیری</b>\n\n";
        $text .= "📱 لینک اختصاصی شما:\n";
        $text .= "<code>{$refLink}</code>\n\n";
        $text .= "📊 <b>آمار:</b>\n";
        $text .= "👥 زیرمجموعه: <b>{$refCount}</b> نفر\n";
        $text .= "💰 پورسانت: <b>" . COMMISSION_PERCENT . "٪</b>\n";
        $text .= "🎁 هدیه: <b>" . number_format(REFERRAL_BONUS) . " تومان</b>\n\n";
        $text .= "💡 لینک را با دوستان خود به اشتراک بگذارید و کسب درآمد کنید!";
        
        $this->sendMessage($chatId, $text);
    }
    
    private function showUserStats($chatId, $userId) {
        $user = $this->db->getUser($userId);
        if (!$user) return;
        
        $text = "📊 <b>آمار فعالیت شما</b>\n\n";
        $text .= "👥 زیرمجموعه: <b>{$user["total_referrals"]}</b> نفر\n";
        $text .= "💰 درآمد: <b>" . number_format($user["referral_earnings"]) . " تومان</b>\n";
        $text .= "🛒 خریدها: <b>{$user["total_purchases"]}</b>\n";
        $text .= "📅 تاریخ عضویت: " . date("Y/m/d", strtotime($user["joined_date"])) . "\n\n";
        $text .= "🎯 پورسانت شما: <b>" . COMMISSION_PERCENT . "٪</b>";
        
        $this->sendMessage($chatId, $text);
    }
    
    private function showSupport($chatId) {
        $text = "📞 <b>پشتیبانی</b>\n\n";
        $text .= "👤 ا