<?php
require_once 'vendor/autoload.php';

use Telegram\Bot\Api;
use Telegram\Bot\Keyboard\Keyboard;

// Bot Configuration
define('BOT_TOKEN', 'YOUR_BOT_TOKEN_HERE');
define('DB_PATH', 'gmail_bot.db');

// Database Class
class Database {
    private $conn;

    public function __construct() {
        $this->conn = new SQLite3(DB_PATH);
        $this->conn->busyTimeout(5000);
        $this->createTables();
    }

    private function createTables() {
        $queries = [
            "CREATE TABLE IF NOT EXISTS users (
                user_id INTEGER PRIMARY KEY,
                username TEXT,
                first_name TEXT,
                balance REAL DEFAULT 0,
                gmail_sell_count INTEGER DEFAULT 0,
                total_withdraw REAL DEFAULT 0,
                is_admin BOOLEAN DEFAULT FALSE,
                join_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )",
            
            "CREATE TABLE IF NOT EXISTS gmail_submissions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                gmail TEXT UNIQUE,
                password TEXT,
                amount REAL DEFAULT 5.0,
                status TEXT DEFAULT 'pending',
                submission_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users (user_id)
            )",
            
            "CREATE TABLE IF NOT EXISTS withdrawals (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                amount REAL,
                method TEXT,
                number TEXT,
                status TEXT DEFAULT 'pending',
                request_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users (user_id)
            )",
            
            "CREATE TABLE IF NOT EXISTS payment_methods (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT UNIQUE,
                is_active BOOLEAN DEFAULT TRUE
            )",
            
            "CREATE TABLE IF NOT EXISTS settings (
                key TEXT PRIMARY KEY,
                value TEXT
            )",
            
            "INSERT OR IGNORE INTO settings (key, value) VALUES 
            ('min_withdraw', '100.0'), 
            ('gmail_price', '5.0')"
        ];

        foreach ($queries as $query) {
            $this->conn->exec($query);
        }
    }

    public function get_user($user_id) {
        $stmt = $this->conn->prepare('SELECT * FROM users WHERE user_id = :user_id');
        $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        return $result->fetchArray(SQLITE3_ASSOC);
    }

    public function create_user($user_id, $username, $first_name) {
        $stmt = $this->conn->prepare('
            INSERT OR IGNORE INTO users (user_id, username, first_name) 
            VALUES (:user_id, :username, :first_name)
        ');
        $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
        $stmt->bindValue(':username', $username, SQLITE3_TEXT);
        $stmt->bindValue(':first_name', $first_name, SQLITE3_TEXT);
        $stmt->execute();
    }

    public function get_admin_count() {
        $result = $this->conn->query('SELECT COUNT(*) FROM users WHERE is_admin = TRUE');
        return $result->fetchArray()[0];
    }

    public function make_admin($user_id) {
        $stmt = $this->conn->prepare('UPDATE users SET is_admin = TRUE WHERE user_id = :user_id');
        $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
        $stmt->execute();
    }

    public function update_balance($user_id, $amount) {
        $stmt = $this->conn->prepare('UPDATE users SET balance = balance + :amount WHERE user_id = :user_id');
        $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
        $stmt->execute();
    }

    public function get_user_balance($user_id) {
        $stmt = $this->conn->prepare('SELECT balance FROM users WHERE user_id = :user_id');
        $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        $row = $result->fetchArray();
        return $row ? $row['balance'] : 0;
    }

    public function add_gmail_submission($user_id, $gmail, $password, $amount = 5.0) {
        try {
            $stmt = $this->conn->prepare('
                INSERT INTO gmail_submissions (user_id, gmail, password, amount)
                VALUES (:user_id, :gmail, :password, :amount)
            ');
            $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
            $stmt->bindValue(':gmail', $gmail, SQLITE3_TEXT);
            $stmt->bindValue(':password', $password, SQLITE3_TEXT);
            $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
            $stmt->execute();
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function get_pending_gmails() {
        $result = $this->conn->query('
            SELECT gs.*, u.first_name 
            FROM gmail_submissions gs 
            JOIN users u ON gs.user_id = u.user_id 
            WHERE gs.status = "pending"
            ORDER BY gs.submission_date DESC
        ');
        
        $gmails = [];
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $gmails[] = $row;
        }
        return $gmails;
    }

    public function get_gmail_by_id($gmail_id) {
        $stmt = $this->conn->prepare('SELECT * FROM gmail_submissions WHERE id = :id');
        $stmt->bindValue(':id', $gmail_id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        return $result->fetchArray(SQLITE3_ASSOC);
    }

    public function update_gmail_status($gmail_id, $status) {
        $gmail_data = $this->get_gmail_by_id($gmail_id);
        
        if (!$gmail_data) return false;
        
        $current_status = $gmail_data['status'];
        $stmt = $this->conn->prepare('UPDATE gmail_submissions SET status = :status WHERE id = :id');
        $stmt->bindValue(':status', $status, SQLITE3_TEXT);
        $stmt->bindValue(':id', $gmail_id, SQLITE3_INTEGER);
        $stmt->execute();
        
        if ($status == 'success' && $current_status != 'success') {
            $this->update_balance($gmail_data['user_id'], $gmail_data['amount']);
            $stmt = $this->conn->prepare('UPDATE users SET gmail_sell_count = gmail_sell_count + 1 WHERE user_id = :user_id');
            $stmt->bindValue(':user_id', $gmail_data['user_id'], SQLITE3_INTEGER);
            $stmt->execute();
        } elseif ($status == 'rejected' && $current_status == 'success') {
            $this->update_balance($gmail_data['user_id'], -$gmail_data['amount']);
            $stmt = $this->conn->prepare('UPDATE users SET gmail_sell_count = gmail_sell_count - 1 WHERE user_id = :user_id');
            $stmt->bindValue(':user_id', $gmail_data['user_id'], SQLITE3_INTEGER);
            $stmt->execute();
        }
        
        return true;
    }

    public function add_withdrawal($user_id, $amount, $method, $number) {
        $user_balance = $this->get_user_balance($user_id);
        if ($user_balance < $amount) return null;
        
        $stmt = $this->conn->prepare('UPDATE users SET balance = balance - :amount WHERE user_id = :user_id');
        $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
        $stmt->execute();
        
        $stmt = $this->conn->prepare('
            INSERT INTO withdrawals (user_id, amount, method, number)
            VALUES (:user_id, :amount, :method, :number)
        ');
        $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
        $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
        $stmt->bindValue(':method', $method, SQLITE3_TEXT);
        $stmt->bindValue(':number', $number, SQLITE3_TEXT);
        $stmt->execute();
        
        return $this->conn->lastInsertRowID();
    }

    public function get_withdrawal_by_id($withdraw_id) {
        $stmt = $this->conn->prepare('SELECT * FROM withdrawals WHERE id = :id');
        $stmt->bindValue(':id', $withdraw_id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        return $result->fetchArray(SQLITE3_ASSOC);
    }

    public function update_withdrawal_status($withdraw_id, $status) {
        $withdraw_data = $this->get_withdrawal_by_id($withdraw_id);
        if (!$withdraw_data) return false;
        
        $current_status = $withdraw_data['status'];
        $stmt = $this->conn->prepare('UPDATE withdrawals SET status = :status WHERE id = :id');
        $stmt->bindValue(':status', $status, SQLITE3_TEXT);
        $stmt->bindValue(':id', $withdraw_id, SQLITE3_INTEGER);
        $stmt->execute();
        
        if ($status == 'rejected' && $current_status != 'rejected') {
            $stmt = $this->conn->prepare('UPDATE users SET balance = balance + :amount WHERE user_id = :user_id');
            $stmt->bindValue(':user_id', $withdraw_data['user_id'], SQLITE3_INTEGER);
            $stmt->bindValue(':amount', $withdraw_data['amount'], SQLITE3_FLOAT);
            $stmt->execute();
        } elseif ($status == 'success' && $current_status == 'pending') {
            $stmt = $this->conn->prepare('UPDATE users SET total_withdraw = total_withdraw + :amount WHERE user_id = :user_id');
            $stmt->bindValue(':user_id', $withdraw_data['user_id'], SQLITE3_INTEGER);
            $stmt->bindValue(':amount', $withdraw_data['amount'], SQLITE3_FLOAT);
            $stmt->execute();
        }
        
        return true;
    }

    public function get_payment_methods() {
        $result = $this->conn->query('SELECT * FROM payment_methods WHERE is_active = TRUE');
        $methods = [];
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $methods[] = $row;
        }
        return $methods;
    }

    public function add_payment_method($name) {
        try {
            $stmt = $this->conn->prepare('INSERT INTO payment_methods (name) VALUES (:name)');
            $stmt->bindValue(':name', $name, SQLITE3_TEXT);
            $stmt->execute();
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function get_setting($key) {
        $stmt = $this->conn->prepare('SELECT value FROM settings WHERE key = :key');
        $stmt->bindValue(':key', $key, SQLITE3_TEXT);
        $result = $stmt->execute();
        $row = $result->fetchArray();
        return $row ? floatval($row['value']) : null;
    }

    public function update_setting($key, $value) {
        $stmt = $this->conn->prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (:key, :value)');
        $stmt->bindValue(':key', $key, SQLITE3_TEXT);
        $stmt->bindValue(':value', $value, SQLITE3_TEXT);
        $stmt->execute();
    }

    public function get_all_users() {
        $result = $this->conn->query('SELECT * FROM users ORDER BY join_date DESC');
        $users = [];
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $users[] = $row;
        }
        return $users;
    }

    public function get_user_gmails($user_id) {
        $stmt = $this->conn->prepare('SELECT * FROM gmail_submissions WHERE user_id = :user_id ORDER BY submission_date DESC');
        $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        
        $gmails = [];
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $gmails[] = $row;
        }
        return $gmails;
    }

    public function get_user_withdrawals($user_id) {
        $stmt = $this->conn->prepare('SELECT * FROM withdrawals WHERE user_id = :user_id ORDER BY request_date DESC');
        $stmt->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        
        $withdrawals = [];
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $withdrawals[] = $row;
        }
        return $withdrawals;
    }
}

// Initialize database
$db = new Database();

// Bot Class
class GmailBuyBot {
    private $telegram;
    private $db;
    private $user_states = [];

    public function __construct($token) {
        $this->telegram = new Api($token);
        $this->db = new Database();
    }

    public function handleUpdate($update) {
        try {
            $message = $update->getMessage();
            $callback_query = $update->getCallbackQuery();
            
            if ($message) {
                $this->handleMessage($message);
            } elseif ($callback_query) {
                $this->handleCallbackQuery($callback_query);
            }
        } catch (Exception $e) {
            error_log("Bot Error: " . $e->getMessage());
        }
    }

    private function handleMessage($message) {
        $chat_id = $message->getChat()->getId();
        $text = $message->getText();
        $user_id = $message->getFrom()->getId();
        $username = $message->getFrom()->getUsername();
        $first_name = $message->getFrom()->getFirstName();

        // Create user if not exists
        $this->db->create_user($user_id, $username, $first_name);

        // Make first user admin
        if ($this->db->get_admin_count() == 0) {
            $this->db->make_admin($user_id);
            $this->sendMessage($chat_id, "🎉 Congratulations! You are the first user and have been made Admin!");
        }

        if ($text == '/start') {
            $this->showMainMenu($chat_id);
        } elseif ($text == 'Account') {
            $this->showAccount($chat_id, $user_id);
        } elseif ($text == 'Gmail Sell') {
            $this->showGmailSellInfo($chat_id);
        } elseif ($text == 'Withdraw') {
            $this->showWithdrawInfo($chat_id, $user_id);
        } elseif ($text == 'Withdraw List') {
            $this->showWithdrawList($chat_id, $user_id);
        } elseif ($text == 'Gmail History') {
            $this->showGmailHistory($chat_id, $user_id);
        } elseif ($text == 'Admin Panel') {
            $this->showAdminPanel($chat_id, $user_id);
        } elseif ($text == 'Back') {
            $this->showMainMenu($chat_id);
        } else {
            // Handle conversation states
            $this->handleConversation($chat_id, $user_id, $text);
        }
    }

    private function handleCallbackQuery($callback_query) {
        $chat_id = $callback_query->getMessage()->getChat()->getId();
        $data = $callback_query->getData();
        $message_id = $callback_query->getMessage()->getMessageId();

        $this->telegram->answerCallbackQuery([
            'callback_query_id' => $callback_query->getId()
        ]);

        switch ($data) {
            case 'back_main':
                $this->showMainMenu($chat_id);
                break;
            case 'gmail_sell':
                $this->startGmailSell($chat_id);
                break;
            case 'withdraw':
                $this->startWithdraw($chat_id);
                break;
            case 'withdraw_list':
                $this->showWithdrawList($chat_id, $callback_query->getFrom()->getId());
                break;
            case 'admin_back':
                $this->showAdminPanel($chat_id, $callback_query->getFrom()->getId());
                break;
            case 'admin_users':
                $this->showAdminUsers($chat_id);
                break;
            case 'admin_gmails':
                $this->showAdminGmails($chat_id);
                break;
            case 'admin_withdrawals':
                $this->showAdminWithdrawals($chat_id);
                break;
            case 'admin_settings':
                $this->showAdminSettings($chat_id);
                break;
            default:
                if (strpos($data, 'method_') === 0) {
                    $method_id = intval(substr($data, 7));
                    $this->startWithdrawAmount($chat_id, $callback_query->getFrom()->getId(), $method_id);
                }
                break;
        }
    }

    private function handleConversation($chat_id, $user_id, $text) {
        if (isset($this->user_states[$user_id])) {
            $state = $this->user_states[$user_id];
            
            switch ($state['type']) {
                case 'gmail_sell':
                    if (!isset($state['step'])) {
                        $this->user_states[$user_id]['step'] = 'enter_gmail';
                        $this->sendMessage($chat_id, "📧 Please enter your Gmail address:");
                    } elseif ($state['step'] == 'enter_gmail') {
                        if (!preg_match('/^[a-zA-Z0-9._%+-]+@gmail\.com$/i', $text)) {
                            $this->sendMessage($chat_id, "❌ Invalid Gmail address! Please enter a valid Gmail address:");
                            return;
                        }
                        $this->user_states[$user_id]['gmail'] = $text;
                        $this->user_states[$user_id]['step'] = 'enter_password';
                        $this->sendMessage($chat_id, "🔐 Please enter the password for this Gmail:");
                    } elseif ($state['step'] == 'enter_password') {
                        $gmail = $this->user_states[$user_id]['gmail'];
                        $password = $text;
                        $gmail_price = $this->db->get_setting('gmail_price');
                        
                        if (!$this->db->add_gmail_submission($user_id, $gmail, $password, $gmail_price)) {
                            $keyboard = [
                                [['text' => '🔄 Sell New Gmail', 'callback_data' => 'gmail_sell']],
                                [['text' => '🔙 Back to Main', 'callback_data' => 'back_main']]
                            ];
                            $this->sendMessage($chat_id, "❌ This Gmail has already been submitted! Please try with a different Gmail.", $keyboard);
                            unset($this->user_states[$user_id]);
                            return;
                        }
                        
                        $response = "✅ Gmail Submitted Successfully!\n\n📧 Gmail: $gmail\n💰 Amount: $gmail_price BDT\n📊 Status: ⏳ Pending\n\nYour Gmail is under review. Once approved, the amount will be added to your account balance.";
                        
                        $keyboard = [
                            [['text' => '🔄 Sell New Gmail', 'callback_data' => 'gmail_sell']],
                            [['text' => '🔙 Back to Main', 'callback_data' => 'back_main']]
                        ];
                        $this->sendMessage($chat_id, $response, $keyboard);
                        
                        // Notify admins
                        $this->notifyAdmins("📧 New Gmail Submission!\n\nGmail: $gmail\nUser ID: $user_id");
                        
                        unset($this->user_states[$user_id]);
                    }
                    break;
                    
                case 'withdraw':
                    if ($state['step'] == 'enter_amount') {
                        $amount = floatval($text);
                        $min_withdraw = $this->db->get_setting('min_withdraw');
                        $user_balance = $this->db->get_user_balance($user_id);
                        
                        if ($amount < $min_withdraw) {
                            $this->sendMessage($chat_id, "❌ Minimum withdrawal amount is $min_withdraw BDT. Please enter a higher amount:");
                            return;
                        }
                        
                        if ($amount > $user_balance) {
                            $this->sendMessage($chat_id, "❌ Insufficient balance! Your balance is $user_balance BDT. Please enter a lower amount:");
                            return;
                        }
                        
                        $this->user_states[$user_id]['amount'] = $amount;
                        $this->user_states[$user_id]['step'] = 'enter_number';
                        $this->sendMessage($chat_id, "📱 Please enter your phone number/account number for withdrawal:");
                    } elseif ($state['step'] == 'enter_number') {
                        $amount = $this->user_states[$user_id]['amount'];
                        $method_id = $this->user_states[$user_id]['method_id'];
                        $number = $text;
                        
                        // Get method name
                        $payment_methods = $this->db->get_payment_methods();
                        $method_name = "Unknown";
                        foreach ($payment_methods as $method) {
                            if ($method['id'] == $method_id) {
                                $method_name = $method['name'];
                                break;
                            }
                        }
                        
                        $withdraw_id = $this->db->add_withdrawal($user_id, $amount, $method_name, $number);
                        
                        if ($withdraw_id === null) {
                            $this->sendMessage($chat_id, "❌ Insufficient balance for withdrawal!");
                            unset($this->user_states[$user_id]);
                            return;
                        }
                        
                        $response = "✅ Withdrawal Request Submitted!\n\n📊 Request ID: #$withdraw_id\n💰 Amount: $amount BDT\n💳 Method: $method_name\n📱 Number: $number\n📊 Status: ⏳ Pending\n\n💰 Your balance has been deducted. The amount will be returned if rejected.";
                        
                        $keyboard = [
                            [['text' => '📋 Withdraw List', 'callback_data' => 'withdraw_list']],
                            [['text' => '🔙 Back to Main', 'callback_data' => 'back_main']]
                        ];
                        $this->sendMessage($chat_id, $response, $keyboard);
                        
                        // Notify admins
                        $this->notifyAdmins("💸 New Withdrawal Request!\n\nAmount: $amount BDT\nMethod: $method_name\nUser ID: $user_id");
                        
                        unset($this->user_states[$user_id]);
                    }
                    break;
            }
        }
    }

    private function showMainMenu($chat_id) {
        $text = "🤖 Welcome to Gmail Buy Bot!\n\n📋 How to use:\n1. Click 'Gmail Sell' to sell your Gmail accounts\n2. Click 'Withdraw' to withdraw your earnings\n3. Check your account details in 'Account'\n\n💰 Earn money by selling Gmail accounts!";
        
        $keyboard = [
            [['text' => 'Account'], ['text' => 'Gmail Sell']],
            [['text' => 'Withdraw'], ['text' => 'Withdraw List']],
            [['text' => 'Gmail History']]
        ];
        
        $this->sendMessage($chat_id, $text, $keyboard, true);
    }

    private function showAccount($chat_id, $user_id) {
        $user_data = $this->db->get_user($user_id);
        
        if ($user_data) {
            $text = "📊 Account Details:\n\n🆔 User ID: {$user_data['user_id']}\n👤 Name: {$user_data['first_name']}\n💰 Balance: {$user_data['balance']} BDT\n📧 Gmail Sold: {$user_data['gmail_sell_count']}\n💳 Total Withdraw: {$user_data['total_withdraw']} BDT";
            $this->sendMessage($chat_id, $text);
        }
    }

    private function showGmailSellInfo($chat_id) {
        $gmail_price = $this->db->get_setting('gmail_price');
        
        $text = "📧 Gmail Selling\n\n💰 Price per Gmail: $gmail_price BDT\n\n📝 How to sell:\n1. Click 'Start Selling' button\n2. Enter your Gmail address\n3. Enter password\n4. Submit for review\n\n✅ After approval, money will be added to your account!";
        
        $keyboard = [
            [['text' => '🚀 Start Selling', 'callback_data' => 'gmail_sell']],
            [['text' => '🔙 Back', 'callback_data' => 'back_main']]
        ];
        $this->sendMessage($chat_id, $text, $keyboard);
    }

    private function startGmailSell($chat_id) {
        $this->user_states[$chat_id] = ['type' => 'gmail_sell'];
        $this->sendMessage($chat_id, "📧 Please enter your Gmail address:");
    }

    private function showWithdrawInfo($chat_id, $user_id) {
        $user_data = $this->db->get_user($user_id);
        $min_withdraw = $this->db->get_setting('min_withdraw');
        
        $text = "💳 Withdraw Money\n\n💰 Current Balance: {$user_data['balance']} BDT\n📊 Minimum Withdraw: $min_withdraw BDT\n\n📋 Available Payment Methods:\n";
        
        $payment_methods = $this->db->get_payment_methods();
        foreach ($payment_methods as $method) {
            $text .= "• {$method['name']}\n";
        }
        
        if ($user_data['balance'] >= $min_withdraw) {
            $keyboard = [[['text' => '💸 Withdraw Now', 'callback_data' => 'withdraw']]];
        } else {
            $keyboard = [[['text' => '❌ Insufficient Balance', 'callback_data' => 'insufficient']]];
        }
        
        $keyboard[] = [['text' => '🔙 Back', 'callback_data' => 'back_main']];
        $this->sendMessage($chat_id, $text, $keyboard);
    }

    private function startWithdraw($chat_id) {
        $payment_methods = $this->db->get_payment_methods();
        
        if (empty($payment_methods)) {
            $this->sendMessage($chat_id, "❌ No payment methods available! Please contact admin.");
            return;
        }
        
        $keyboard = [];
        foreach ($payment_methods as $method) {
            $keyboard[] = [[
                'text' => $method['name'], 
                'callback_data' => 'method_' . $method['id']
            ]];
        }
        
        $this->sendMessage($chat_id, "💳 Select Payment Method:", $keyboard);
    }

    private function startWithdrawAmount($chat_id, $user_id, $method_id) {
        $user_balance = $this->db->get_user_balance($user_id);
        $this->user_states[$user_id] = [
            'type' => 'withdraw',
            'step' => 'enter_amount',
            'method_id' => $method_id
        ];
        $this->sendMessage($chat_id, "💰 Your balance: $user_balance BDT\n\nEnter withdrawal amount:");
    }

    private function showWithdrawList($chat_id, $user_id) {
        $withdrawals = $this->db->get_user_withdrawals($user_id);
        
        if (empty($withdrawals)) {
            $text = "📋 You have no withdrawal history.";
        } else {
            $text = "📋 Your Withdrawal History:\n\n";
            foreach ($withdrawals as $withdraw) {
                $status_emoji = $withdraw['status'] == 'pending' ? '⏳' : ($withdraw['status'] == 'success' ? '✅' : '❌');
                $date_str = explode(' ', $withdraw['request_date'])[0];
                $text .= "#{$withdraw['id']} | {$withdraw['amount']} BDT | {$withdraw['method']} | {$withdraw['number']} | $status_emoji {$withdraw['status']}\n";
                $text .= "📅 $date_str\n\n";
            }
        }
        
        $keyboard = [[['text' => '🔙 Back', 'callback_data' => 'back_main']]];
        $this->sendMessage($chat_id, $text, $keyboard);
    }

    private function showGmailHistory($chat_id, $user_id) {
        $gmails = $this->db->get_user_gmails($user_id);
        
        if (empty($gmails)) {
            $text = "📧 You have no Gmail submission history.";
        } else {
            $text = "📧 Your Gmail Submission History:\n\n";
            foreach ($gmails as $gmail) {
                $status_emoji = $gmail['status'] == 'pending' ? '⏳' : ($gmail['status'] == 'success' ? '✅' : '❌');
                $date_str = explode(' ', $gmail['submission_date'])[0];
                $text .= "#{$gmail['id']} | {$gmail['gmail']} | $status_emoji {$gmail['status']}\n";
                $text .= "💰 {$gmail['amount']} BDT | 📅 $date_str\n\n";
            }
        }
        
        $keyboard = [[['text' => '🔙 Back', 'callback_data' => 'back_main']]];
        $this->sendMessage($chat_id, $text, $keyboard);
    }

    private function showAdminPanel($chat_id, $user_id) {
        $user_data = $this->db->get_user($user_id);
        
        if (!$user_data || !$user_data['is_admin']) {
            $this->sendMessage($chat_id, "❌ Access denied! Admin only.");
            return;
        }
        
        $text = "👑 Admin Panel\n\nChoose an option to manage:";
        $keyboard = [
            [['text' => '👥 Users', 'callback_data' => 'admin_users']],
            [['text' => '📧 Gmail List', 'callback_data' => 'admin_gmails']],
            [['text' => '💳 Withdraw List', 'callback_data' => 'admin_withdrawals']],
            [['text' => '⚙️ Settings', 'callback_data' => 'admin_settings']],
            [['text' => '🔙 Back to Main', 'callback_data' => 'back_main']]
        ];
        $this->sendMessage($chat_id, $text, $keyboard);
    }

    private function showAdminUsers($chat_id) {
        $users = $this->db->get_all_users();
        
        $text = "👥 Total Users: " . count($users) . "\n\n";
        foreach (array_slice($users, 0, 10) as $user) {
            $admin_badge = $user['is_admin'] ? " 👑" : "";
            $date_str = explode(' ', $user['join_date'])[0];
            $text .= "🆔 {$user['user_id']} | 👤 {$user['first_name']}$admin_badge\n";
            $text .= "💰 {$user['balance']} BDT | 📧 {$user['gmail_sell_count']} | 💳 {$user['total_withdraw']} BDT\n";
            $text .= "📅 $date_str\n\n";
        }
        
        if (count($users) > 10) {
            $text .= "... and " . (count($users) - 10) . " more users";
        }
        
        $keyboard = [[['text' => '🔙 Back to Admin', 'callback_data' => 'admin_back']]];
        $this->sendMessage($chat_id, $text, $keyboard);
    }

    private function showAdminGmails($chat_id) {
        $text = "📧 Gmail Management\n\nChoose category:";
        $keyboard = [
            [['text' => '⏳ Pendings', 'callback_data' => 'gmails_pending']],
            [['text' => '✅ Success', 'callback_data' => 'gmails_success']],
            [['text' => '❌ Rejected', 'callback_data' => 'gmails_rejected']],
            [['text' => '🔙 Back to Admin', 'callback_data' => 'admin_back']]
        ];
        $this->sendMessage($chat_id, $text, $keyboard);
    }

    private function showAdminWithdrawals($chat_id) {
        $text = "💳 Withdrawal Management\n\nChoose category:";
        $keyboard = [
            [['text' => '⏳ Pendings', 'callback_data' => 'withdrawals_pending']],
            [['text' => '✅ Success', 'callback_data' => 'withdrawals_success']],
            [['text' => '❌ Rejected', 'callback_data' => 'withdrawals_rejected']],
            [['text' => '🔙 Back to Admin', 'callback_data' => 'admin_back']]
        ];
        $this->sendMessage($chat_id, $text, $keyboard);
    }

    private function showAdminSettings($chat_id) {
        $min_withdraw = $this->db->get_setting('min_withdraw');
        $gmail_price = $this->db->get_setting('gmail_price');
        $payment_methods = $this->db->get_payment_methods();
        
        $text = "⚙️ Bot Settings\n\n💰 Gmail Price: $gmail_price BDT\n💳 Min Withdraw: $min_withdraw BDT\n\n📋 Payment Methods:\n";
        foreach ($payment_methods as $method) {
            $text .= "• {$method['name']}\n";
        }
        
        $keyboard = [
            [['text' => '➕ Add Payment Method', 'callback_data' => 'add_payment_method']],
            [['text' => '💰 Update Gmail Price', 'callback_data' => 'update_gmail_price']],
            [['text' => '📊 Update Min Withdraw', 'callback_data' => 'update_min_withdraw']],
            [['text' => '🔙 Back to Admin', 'callback_data' => 'admin_back']]
        ];
        $this->sendMessage($chat_id, $text, $keyboard);
    }

    private function notifyAdmins($message) {
        $admins = $this->db->get_all_users();
        foreach ($admins as $admin) {
            if ($admin['is_admin']) {
                $this->sendMessage($admin['user_id'], $message);
            }
        }
    }

    private function sendMessage($chat_id, $text, $keyboard = null, $reply_markup = false) {
        $params = [
            'chat_id' => $chat_id,
            'text' => $text,
            'parse_mode' => 'HTML'
        ];
        
        if ($keyboard) {
            $params['reply_markup'] = json_encode([
                'inline_keyboard' => $keyboard
            ]);
        } elseif ($reply_markup) {
            $params['reply_markup'] = json_encode([
                'keyboard' => $keyboard,
                'resize_keyboard' => true
            ]);
        }
        
        try {
            $this->telegram->sendMessage($params);
        } catch (Exception $e) {
            error_log("Telegram API Error: " . $e->getMessage());
        }
    }
}

// Main execution
$bot_token = getenv('BOT_TOKEN') ?: BOT_TOKEN;
$bot = new GmailBuyBot($bot_token);

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

if ($update) {
    $bot->handleUpdate($update);
} else {
    // For testing
    echo "🤖 Gmail Buy Bot is running...\n";
}
?>