<?php
/**
 * MFA Hydra Bot - Main Webhook Handler
 * Hostinger Shared Hosting Compatible
 * 
 * This file receives all updates from Telegram
 * and routes them to appropriate handlers.
 */

define('BOT_SECURE', true);
require_once __DIR__ . '/../config.php';

// Set webhook on first visit (optional - can be done manually)
if (isset($_GET['setup']) && $_GET['setup'] === '1') {
    $telegram = new Telegram();
    $webhookUrl = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $webhookUrl = str_replace('?setup=1', '', $webhookUrl);

    $result = $telegram->setWebhook($webhookUrl, [
        'max_connections' => 20,
        'allowed_updates' => ['message', 'callback_query', 'pre_checkout_query']
    ]);

    if ($result) {
        echo "✅ Webhook set successfully!<br>URL: {$webhookUrl}";
    } else {
        echo "❌ Failed to set webhook. Check logs.";
    }
    exit;
}

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

if (empty($update)) {
    http_response_code(200);
    echo 'OK';
    exit;
}

// Log update for debugging
Helpers::log('webhook', 'Received update', $update);

// Initialize handlers
$telegram = new Telegram();
$ai = new GeminiAI();
$db = Database::getInstance();

// Process update
try {
    // Handle Callback Query (Inline Keyboard Buttons)
    if (isset($update['callback_query'])) {
        handleCallbackQuery($update['callback_query']);
    }
    // Handle Message
    elseif (isset($update['message'])) {
        handleMessage($update['message']);
    }
    // Handle Pre-checkout Query (Telegram Payments)
    elseif (isset($update['pre_checkout_query'])) {
        handlePreCheckoutQuery($update['pre_checkout_query']);
    }
} catch (Exception $e) {
    error_log('Bot Error: ' . $e->getMessage());
    Helpers::log('error', 'Exception: ' . $e->getMessage());
}

http_response_code(200);
echo 'OK';

// ============================================
// MESSAGE HANDLER
// ============================================
function handleMessage($message) {
    global $telegram, $ai, $db;

    $chatId = $message['chat']['id'];
    $userId = $message['from']['id'];
    $text = $message['text'] ?? '';
    $messageId = $message['message_id'] ?? null;

    // Rate limit check
    if (!Helpers::checkRateLimit($userId)) {
        $telegram->sendMessage($chatId, "⏳ Please slow down! Too many requests.");
        return;
    }

    // Get or create user
    $user = Helpers::getOrCreateUser($message['from']);

    // Check if banned
    if ($user['status'] === 'banned') {
        $telegram->sendMessage($chatId, "🚫 Your account has been suspended. Contact support.");
        return;
    }

    // Handle commands
    if (isset($message['entities']) && $message['entities'][0]['type'] === 'bot_command') {
        $command = strtolower(explode(' ', $text)[0]);

        switch ($command) {
            case '/start':
                handleStart($chatId, $user, $text);
                break;
            case '/help':
                handleHelp($chatId);
                break;
            case '/products':
            case '/catalog':
                showCategories($chatId);
                break;
            case '/orders':
                showOrders($chatId, $userId);
                break;
            case '/support':
                handleSupport($chatId, $userId);
                break;
            case '/balance':
                showBalance($chatId, $userId);
                break;
            case '/referral':
                showReferral($chatId, $userId, $user);
                break;
            case '/reseller':
                handleReseller($chatId, $userId, $user);
                break;
            case '/admin':
                handleAdmin($chatId, $userId);
                break;
            case '/broadcast':
                if (Helpers::isAdmin($userId)) {
                    $telegram->sendMessage($chatId, "📢 Broadcast mode activated.\nSend the message you want to broadcast to all users.");
                }
                break;
            case '/stats':
                if (Helpers::isAdmin($userId)) {
                    showAdminStats($chatId);
                }
                break;
            case '/users':
                if (Helpers::isAdmin($userId)) {
                    showUserList($chatId);
                }
                break;
            case '/webhook':
                if (Helpers::isAdmin($userId)) {
                    $telegram->sendMessage($chatId, "🔗 Webhook URL:\n<code>https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "</code>", ['parse_mode' => 'HTML']);
                }
                break;
            default:
                $telegram->sendMessage($chatId, "❓ Unknown command. Use /help to see available commands.");
        }
        return;
    }

    // Handle photos (payment screenshots)
    if (isset($message['photo'])) {
        handlePhotoUpload($chatId, $userId, $message['photo'], $message['caption'] ?? '');
        return;
    }

    // Handle documents
    if (isset($message['document'])) {
        $telegram->sendMessage($chatId, "📄 Document received. If this is a payment screenshot, please also send a photo instead.");
        return;
    }

    // Handle contact sharing
    if (isset($message['contact'])) {
        $contact = $message['contact'];
        $db->update('users',
            ['phone' => $contact['phone_number']],
            'telegram_id = ?',
            [$userId]
        );
        $telegram->sendMessage($chatId, "✅ Phone number saved: " . $contact['phone_number']);
        return;
    }

    // AI Response for regular messages
    $telegram->sendChatAction($chatId, 'typing');
    $aiResponse = $ai->generateResponse($userId, $text);

    // Add quick action buttons
    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('🛍️ Browse Products', 'browse_categories')],
        [Telegram::button('📞 Contact Support', 'open_support')],
        [Telegram::button('💼 Reseller Program', 'reseller_info')]
    ]);

    $telegram->sendMessage($chatId, $aiResponse, ['reply_markup' => $keyboard]);
}

// ============================================
// CALLBACK QUERY HANDLER
// ============================================
function handleCallbackQuery($callbackQuery) {
    global $telegram, $db;

    $callbackId = $callbackQuery['id'];
    $userId = $callbackQuery['from']['id'];
    $data = $callbackQuery['data'];
    $messageId = $callbackQuery['message']['message_id'] ?? null;
    $chatId = $callbackQuery['message']['chat']['id'] ?? null;

    // Answer callback immediately
    $telegram->answerCallbackQuery($callbackId);

    // Parse callback data
    $parts = explode(':', $data);
    $action = $parts[0];

    switch ($action) {
        // Product browsing
        case 'browse_categories':
            showCategories($chatId, $messageId);
            break;
        case 'category':
            $categoryId = $parts[1] ?? 0;
            showProducts($chatId, $categoryId, $messageId);
            break;
        case 'product':
            $productId = $parts[1] ?? 0;
            showProductDetail($chatId, $productId, $messageId);
            break;
        case 'buy_product':
            $productId = $parts[1] ?? 0;
            initiateOrder($chatId, $userId, $productId, $messageId);
            break;
        case 'confirm_payment':
            $orderId = $parts[1] ?? '';
            confirmPayment($chatId, $userId, $orderId, $messageId);
            break;
        case 'cancel_order':
            $orderId = $parts[1] ?? '';
            cancelOrder($chatId, $userId, $orderId, $messageId);
            break;

        // User account
        case 'my_orders':
            showOrders($chatId, $userId, $messageId);
            break;
        case 'my_balance':
            showBalance($chatId, $userId, $messageId);
            break;
        case 'my_referrals':
            showReferral($chatId, $userId, null, $messageId);
            break;
        case 'my_tickets':
            showTickets($chatId, $userId, $messageId);
            break;

        // Support
        case 'open_support':
            handleSupport($chatId, $userId, $messageId);
            break;
        case 'create_ticket':
            $telegram->sendMessage($chatId, "📝 <b>Create Support Ticket</b>\n\nPlease send your issue in one message including:\n• Subject\n• Detailed description\n• Order ID (if related to order)\n\nExample:\n<i>Subject: Netflix login not working</i>\n<i>Description: I purchased Netflix yesterday but the credentials are not working. Order ID: ORD-123456</i>");
            break;
        case 'faq':
            showFAQ($chatId, $messageId);
            break;
        case 'contact_whatsapp':
            $telegram->sendMessage($chatId, "📱 <b>Contact via WhatsApp</b>\n\nClick below to chat with us:\n👉 <a href='https://wa.me/" . SUPPORT_WHATSAPP . "'>Chat on WhatsApp</a>\n\nOr save this number: +" . SUPPORT_WHATSAPP);
            break;

        // Reseller
        case 'reseller_info':
            showResellerInfo($chatId, $userId, $messageId);
            break;
        case 'become_reseller':
            becomeReseller($chatId, $userId, $messageId);
            break;
        case 'reseller_dashboard':
            showResellerDashboard($chatId, $userId, $messageId);
            break;
        case 'withdraw':
            handleWithdrawal($chatId, $userId, $messageId);
            break;

        // Admin
        case 'admin_dashboard':
            if (Helpers::isAdmin($userId)) {
                showAdminDashboard($chatId, $messageId);
            }
            break;
        case 'admin_orders':
            if (Helpers::isAdmin($userId)) {
                showAdminOrders($chatId, $messageId);
            }
            break;
        case 'admin_users':
            if (Helpers::isAdmin($userId)) {
                showAdminUsers($chatId, $messageId);
            }
            break;
        case 'admin_tickets':
            if (Helpers::isAdmin($userId)) {
                showAdminTickets($chatId, $messageId);
            }
            break;
        case 'admin_products':
            if (Helpers::isAdmin($userId)) {
                showAdminProducts($chatId, $messageId);
            }
            break;
        case 'admin_broadcast':
            if (Helpers::isAdmin($userId)) {
                $telegram->sendMessage($chatId, "📢 <b>Broadcast Message</b>\n\nSend the message you want to broadcast to ALL users.\n\nSupported formats:\n• Text\n• Photo with caption\n\nType /cancel to abort.");
            }
            break;
        case 'process_order':
            if (Helpers::isAdmin($userId)) {
                $orderId = $parts[1] ?? '';
                processOrder($chatId, $orderId, $messageId);
            }
            break;
        case 'resolve_ticket':
            if (Helpers::isAdmin($userId)) {
                $ticketId = $parts[1] ?? '';
                resolveTicket($chatId, $ticketId, $messageId);
            }
            break;
        case 'ban_user':
            if (Helpers::isAdmin($userId)) {
                $targetUserId = $parts[1] ?? 0;
                banUser($chatId, $targetUserId, $messageId);
            }
            break;
        case 'unban_user':
            if (Helpers::isAdmin($userId)) {
                $targetUserId = $parts[1] ?? 0;
                unbanUser($chatId, $targetUserId, $messageId);
            }
            break;

        // Navigation
        case 'back_to_menu':
            showMainMenu($chatId, $messageId);
            break;
        case 'back_to_categories':
            showCategories($chatId, $messageId);
            break;

        default:
            $telegram->answerCallbackQuery($callbackId, "⚠️ Action not recognized", true);
    }
}

// ============================================
// COMMAND HANDLERS
// ============================================
function handleStart($chatId, $user, $text) {
    global $telegram;

    $firstName = $user['first_name'] ?? 'there';

    $welcomeText = "👋 <b>Welcome to Team Hydra Shop, {$firstName}!</b>\n\n";
    $welcomeText .= "🛍️ Your one-stop shop for premium digital products at unbeatable prices!\n\n";
    $welcomeText .= "<b>What we offer:</b>\n";
    $welcomeText .= "🎬 Netflix, Prime Video, Disney+\n";
    $welcomeText .= "🤖 ChatGPT Plus, Midjourney\n";
    $welcomeText .= "🎨 CapCut Pro, Canva Pro\n";
    $welcomeText .= "📺 Spotify, YouTube Premium\n\n";
    $welcomeText .= "✅ Instant Delivery\n";
    $welcomeText .= "✅ 24/7 Support\n";
    $welcomeText .= "✅ Best Prices Guaranteed\n\n";
    $welcomeText .= "🚀 Get started by browsing our products!";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('🛍️ Browse Products', 'browse_categories')],
        [Telegram::button('📦 My Orders', 'my_orders'), Telegram::button('💰 My Balance', 'my_balance')],
        [Telegram::button('📞 Support', 'open_support'), Telegram::button('💼 Reseller', 'reseller_info')],
        [Telegram::button('🌐 Visit Website', null, WEBSITE_URL)]
    ]);

    $telegram->sendMessage($chatId, $welcomeText, ['reply_markup' => $keyboard]);
}

function handleHelp($chatId) {
    global $telegram;

    $helpText = "📚 <b>Available Commands</b>\n\n";
    $helpText .= "/start - Start the bot\n";
    $helpText .= "/products - Browse product catalog\n";
    $helpText .= "/orders - View your orders\n";
    $helpText .= "/support - Contact support\n";
    $helpText .= "/balance - Check wallet balance\n";
    $helpText .= "/referral - Get referral link\n";
    $helpText .= "/reseller - Reseller dashboard\n";
    $helpText .= "/help - Show this help\n\n";
    $helpText .= "<b>Admin Commands:</b>\n";
    $helpText .= "/admin - Admin panel\n";
    $helpText .= "/stats - Bot statistics\n";
    $helpText .= "/users - User list\n";
    $helpText .= "/broadcast - Send broadcast\n\n";
    $helpText .= "💡 <i>You can also chat with our AI assistant for instant help!</i>";

    $telegram->sendMessage($chatId, $helpText);
}

function showMainMenu($chatId, $messageId = null) {
    global $telegram;

    $text = "🏠 <b>Main Menu</b>\n\nWhat would you like to do?";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('🛍️ Browse Products', 'browse_categories')],
        [Telegram::button('📦 My Orders', 'my_orders'), Telegram::button('💰 My Balance', 'my_balance')],
        [Telegram::button('📞 Support', 'open_support'), Telegram::button('💼 Reseller', 'reseller_info')],
        [Telegram::button('🌐 Visit Website', null, WEBSITE_URL)]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

// ============================================
// PRODUCT CATALOG
// ============================================
function showCategories($chatId, $messageId = null) {
    global $telegram, $db;

    $categories = $db->fetchAll("SELECT * FROM categories WHERE status = 'active' ORDER BY sort_order");

    $text = "🛍️ <b>Product Categories</b>\n\nSelect a category to browse products:";

    $buttons = [];
    foreach ($categories as $category) {
        $buttons[] = [Telegram::button(
            $category['icon'] . ' ' . $category['name'],
            'category:' . $category['id']
        )];
    }

    $buttons[] = [Telegram::button('🔙 Back to Menu', 'back_to_menu')];

    $keyboard = Telegram::inlineKeyboard($buttons);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function showProducts($chatId, $categoryId, $messageId = null) {
    global $telegram, $db;

    $category = $db->fetch("SELECT * FROM categories WHERE id = ?", [$categoryId], 'i');
    $products = $db->fetchAll(
        "SELECT * FROM products WHERE category_id = ? AND status = 'active' ORDER BY is_featured DESC, name",
        [$categoryId],
        'i'
    );

    if (empty($products)) {
        $text = "😔 No products available in this category right now.\n\nCheck back later or browse other categories!";
    } else {
        $text = "{$category['icon']} <b>{$category['name']}</b>\n<i>{$category['description']}</i>\n\n";
        $text .= "Select a product to view details:";
    }

    $buttons = [];
    foreach ($products as $product) {
        $priceText = ($product['original_price'] > 0) 
            ? "~~₹{$product['original_price']}~~ ₹{$product['price']}"
            : "₹{$product['price']}";

        $stockEmoji = $product['stock'] > 10 ? '✅' : ($product['stock'] > 0 ? '⚠️' : '❌');

        $buttons[] = [Telegram::button(
            "{$stockEmoji} {$product['name']} - {$priceText}",
            'product:' . $product['id']
        )];
    }

    $buttons[] = [Telegram::button('🔙 Back to Categories', 'back_to_categories')];

    $keyboard = Telegram::inlineKeyboard($buttons);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function showProductDetail($chatId, $productId, $messageId = null) {
    global $telegram, $db;

    $product = $db->fetch(
        "SELECT p.*, c.name as category_name, c.icon as category_icon 
         FROM products p 
         JOIN categories c ON p.category_id = c.id 
         WHERE p.id = ?",
        [$productId],
        'i'
    );

    if (!$product) {
        $telegram->sendMessage($chatId, "❌ Product not found.");
        return;
    }

    $discount = 0;
    if ($product['original_price'] > 0) {
        $discount = round((($product['original_price'] - $product['price']) / $product['original_price']) * 100);
    }

    $text = "{$product['category_icon']} <b>{$product['name']}</b>\n\n";
    $text .= "<i>{$product['short_desc']}</i>\n\n";
    $text .= "💰 <b>Price:</b> " . Helpers::formatPrice($product['price']);

    if ($product['original_price'] > 0) {
        $text .= " ~~" . Helpers::formatPrice($product['original_price']) . "~~";
        $text .= " ({$discount}% OFF)";
    }

    $text .= "\n\n";
    $text .= "📋 <b>Description:</b>\n{$product['description']}\n\n";
    $text .= "🛡️ <b>Warranty:</b> {$product['warranty_days']} days\n";
    $text .= "📦 <b>Delivery:</b> " . ucfirst($product['delivery_type']) . "\n";
    $text .= "🏷️ <b>Category:</b> {$product['category_name']}\n";
    $text .= "📊 <b>Stock:</b> " . ($product['stock'] > 0 ? $product['stock'] . ' available' : 'Out of stock') . "\n\n";

    if ($product['stock'] <= 0) {
        $text .= "❌ <b>Currently out of stock</b>\n";
        $text .= "🔔 We'll notify you when it's back!";
    }

    $buttons = [];

    if ($product['stock'] > 0) {
        $buttons[] = [Telegram::button('🛒 Buy Now', 'buy_product:' . $product['id'])];
    }

    $buttons[] = [Telegram::button('🔙 Back to Products', 'category:' . $product['category_id'])];
    $buttons[] = [Telegram::button('🏠 Main Menu', 'back_to_menu')];

    $keyboard = Telegram::inlineKeyboard($buttons);

    // Send photo if available
    if (!empty($product['image_url']) && !$messageId) {
        $telegram->sendPhoto($chatId, $product['image_url'], $text, ['reply_markup' => $keyboard]);
    } else {
        if ($messageId) {
            $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
        } else {
            $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
        }
    }
}

// ============================================
// ORDER SYSTEM
// ============================================
function initiateOrder($chatId, $userId, $productId, $messageId = null) {
    global $telegram, $db;

    $product = $db->fetch("SELECT * FROM products WHERE id = ? AND status = 'active'", [$productId], 'i');

    if (!$product || $product['stock'] <= 0) {
        $telegram->sendMessage($chatId, "❌ This product is currently out of stock.");
        return;
    }

    $orderId = Helpers::generateOrderId();

    // Create order
    $db->insert('orders', [
        'order_id' => $orderId,
        'user_id' => $userId,
        'product_id' => $productId,
        'quantity' => 1,
        'unit_price' => $product['price'],
        'total_price' => $product['price'],
        'payment_status' => 'pending',
        'order_status' => 'pending'
    ]);

    // Reduce stock
    $db->execute("UPDATE products SET stock = stock - 1 WHERE id = ?", [$productId], 'i');

    $text = "🛒 <b>Order Initiated</b>\n\n";
    $text .= "📦 <b>Product:</b> {$product['name']}\n";
    $text .= "💰 <b>Amount:</b> " . Helpers::formatPrice($product['price']) . "\n";
    $text .= "🆔 <b>Order ID:</b> <code>{$orderId}</code>\n\n";
    $text .= "<b>Payment Instructions:</b>\n";
    $text .= "1️⃣ Pay via UPI: <code>" . UPI_ID . "</code>\n";
    $text .= "2️⃣ Amount: <b>" . Helpers::formatPrice($product['price']) . "</b>\n";
    $text .= "3️⃣ Note: <code>{$orderId}</code>\n\n";
    $text .= "4️⃣ Send payment screenshot here\n\n";
    $text .= "⏳ <i>Order expires in 30 minutes if payment not confirmed</i>";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('❌ Cancel Order', 'cancel_order:' . $orderId)],
        [Telegram::button('🔙 Back to Products', 'category:' . $product['category_id'])]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }

    // Notify admin
    $user = $db->fetch("SELECT first_name, username FROM users WHERE telegram_id = ?", [$userId], 'i');
    $adminMsg = "🛒 <b>New Order!</b>\n\n";
    $adminMsg .= "👤 User: " . ($user['first_name'] ?? 'Unknown') . " (@" . ($user['username'] ?? 'N/A') . ")\n";
    $adminMsg .= "🆔 User ID: {$userId}\n";
    $adminMsg .= "📦 Product: {$product['name']}\n";
    $adminMsg .= "💰 Amount: " . Helpers::formatPrice($product['price']) . "\n";
    $adminMsg .= "🆔 Order: <code>{$orderId}</code>\n\n";
    $adminMsg .= "⏳ Waiting for payment confirmation...";

    Helpers::notifyAdmin($adminMsg);
}

function confirmPayment($chatId, $userId, $orderId, $messageId = null) {
    global $telegram, $db;

    $order = $db->fetch("SELECT * FROM orders WHERE order_id = ? AND user_id = ?", [$orderId, $userId], 'si');

    if (!$order) {
        $telegram->sendMessage($chatId, "❌ Order not found.");
        return;
    }

    if ($order['payment_status'] === 'paid') {
        $telegram->sendMessage($chatId, "✅ This order is already paid and processed!");
        return;
    }

    // Update order
    $db->update('orders',
        ['payment_status' => 'paid', 'order_status' => 'processing'],
        'order_id = ?',
        [$orderId]
    );

    // Process auto-delivery if applicable
    $product = $db->fetch("SELECT * FROM products WHERE id = ?", [$order['product_id']], 'i');

    if ($product['delivery_type'] === 'auto' && !empty($product['delivery_content'])) {
        $deliveryData = json_decode($product['delivery_content'], true);

        $deliveryText = "🎉 <b>Order Delivered!</b>\n\n";
        $deliveryText .= "🆔 Order: <code>{$orderId}</code>\n";
        $deliveryText .= "📦 Product: {$product['name']}\n\n";
        $deliveryText .= "<b>Your Account Details:</b>\n";

        foreach ($deliveryData as $key => $value) {
            $deliveryText .= ucfirst($key) . ": <code>{$value}</code>\n";
        }

        $deliveryText .= "\n⚠️ <i>Do not share these credentials with anyone.</i>\n";
        $deliveryText .= "🛡️ Warranty: {$product['warranty_days']} days\n\n";
        $deliveryText .= "❓ Need help? Contact @teamhydrashops";

        $telegram->sendMessage($chatId, $deliveryText);

        // Update order status
        $db->update('orders',
            ['order_status' => 'completed', 'delivery_data' => $product['delivery_content']],
            'order_id = ?',
            [$orderId]
        );

        // Update user stats
        $db->execute("UPDATE users SET total_orders = total_orders + 1, total_spent = total_spent + ? WHERE telegram_id = ?",
            [$order['total_price'], $userId],
            'di'
        );

        // Process reseller commission
        $user = $db->fetch("SELECT referred_by FROM users WHERE telegram_id = ?", [$userId], 'i');
        if ($user && $user['referred_by']) {
            $commission = $order['total_price'] * (RESELLER_COMMISSION_RATE / 100);

            $db->insert('commissions', [
                'reseller_id' => $user['referred_by'],
                'order_id' => $order['id'],
                'amount' => $commission,
                'status' => 'pending'
            ]);

            // Notify reseller
            $telegram->sendMessage(
                $user['referred_by'],
                "💰 <b>New Commission!</b>\n\n" .
                "Someone purchased through your referral!\n" .
                "📦 Product: {$product['name']}\n" .
                "💵 Commission: " . Helpers::formatPrice($commission) . "\n" .
                "⏳ Status: Pending approval\n\n" .
                "Keep sharing your referral link!"
            );
        }
    } else {
        $text = "✅ <b>Payment Confirmed!</b>\n\n";
        $text .= "🆔 Order: <code>{$orderId}</code>\n";
        $text .= "📦 Product: {$product['name']}\n\n";
        $text .= "⏳ Your order is being processed.\n";
        $text .= "📩 You'll receive delivery details within 15-30 minutes.\n\n";
        $text .= "❓ Need help? Contact @teamhydrashops";

        $telegram->sendMessage($chatId, $text);
    }

    // Notify admin
    Helpers::notifyAdmin("✅ <b>Payment Received!</b>\n\nOrder: <code>{$orderId}</code>\nStatus: Paid & Processing\nUser ID: {$userId}");
}

function cancelOrder($chatId, $userId, $orderId, $messageId = null) {
    global $telegram, $db;

    $order = $db->fetch("SELECT * FROM orders WHERE order_id = ? AND user_id = ?", [$orderId, $userId], 'si');

    if (!$order) {
        $telegram->sendMessage($chatId, "❌ Order not found.");
        return;
    }

    if ($order['order_status'] === 'completed') {
        $telegram->sendMessage($chatId, "❌ Cannot cancel completed order. Contact support for refund.");
        return;
    }

    // Restore stock
    $db->execute("UPDATE products SET stock = stock + ? WHERE id = ?", [$order['quantity'], $order['product_id']], 'ii');

    // Cancel order
    $db->update('orders',
        ['order_status' => 'cancelled', 'payment_status' => 'cancelled'],
        'order_id = ?',
        [$orderId]
    );

    $telegram->sendMessage($chatId, "❌ Order <code>{$orderId}</code> has been cancelled.", ['parse_mode' => 'HTML']);
}

function showOrders($chatId, $userId, $messageId = null) {
    global $telegram, $db;

    $orders = $db->fetchAll(
        "SELECT o.*, p.name as product_name, p.icon as product_icon 
         FROM orders o 
         JOIN products p ON o.product_id = p.id 
         WHERE o.user_id = ? 
         ORDER BY o.created_at DESC 
         LIMIT 10",
        [$userId],
        'i'
    );

    if (empty($orders)) {
        $text = "📦 <b>My Orders</b>\n\nYou haven't placed any orders yet.\n\nStart browsing products!";
    } else {
        $text = "📦 <b>My Orders</b>\n\n";
        foreach ($orders as $order) {
            $statusEmoji = [
                'pending' => '⏳',
                'processing' => '⚙️',
                'completed' => '✅',
                'cancelled' => '❌',
                'refunded' => '💸'
            ][$order['order_status']] ?? '❓';

            $text .= "{$statusEmoji} <code>{$order['order_id']}</code>\n";
            $text .= "   {$order['product_name']}\n";
            $text .= "   " . Helpers::formatPrice($order['total_price']) . " | {$order['order_status']}\n";
            $text .= "   " . Helpers::formatDate($order['created_at'], 'd M') . "\n\n";
        }
    }

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('🛍️ Browse Products', 'browse_categories')],
        [Telegram::button('🏠 Main Menu', 'back_to_menu')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

// ============================================
// SUPPORT SYSTEM
// ============================================
function handleSupport($chatId, $userId, $messageId = null) {
    global $telegram;

    $text = "📞 <b>Customer Support</b>\n\n";
    $text .= "We're here to help you 24/7!\n\n";
    $text .= "<b>Quick Options:</b>";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('📝 Create Ticket', 'create_ticket')],
        [Telegram::button('📱 WhatsApp Support', null, 'https://wa.me/' . SUPPORT_WHATSAPP)],
        [Telegram::button('📢 Join Channel', null, 'https://t.me/' . str_replace('@', '', SUPPORT_CHANNEL))],
        [Telegram::button('❓ FAQ', 'faq')],
        [Telegram::button('🏠 Main Menu', 'back_to_menu')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function showFAQ($chatId, $messageId = null) {
    global $telegram;

    $text = "❓ <b>Frequently Asked Questions</b>\n\n";
    $text .= "<b>Q: How does delivery work?</b>\n";
    $text .= "A: Most products are delivered automatically within minutes after payment confirmation. Some require manual processing (15-30 mins).\n\n";
    $text .= "<b>Q: What payment methods do you accept?</b>\n";
    $text .= "A: We accept UPI (Google Pay, PhonePe, Paytm), Bank Transfer, and select cryptocurrencies.\n\n";
    $text .= "<b>Q: Are these accounts shared or private?</b>\n";
    $text .= "A: We offer both! Product description mentions the type. Private accounts cost slightly more.\n\n";
    $text .= "<b>Q: What if the account stops working?</b>\n";
    $text .= "A: We offer warranty as mentioned on each product. Contact support with your Order ID for replacement.\n\n";
    $text .= "<b>Q: Can I get a refund?</b>\n";
    $text .= "A: Full refund if not delivered within 24 hours. No refund after credentials are used.\n\n";
    $text .= "<b>Q: How do I become a reseller?</b>\n";
    $text .= "A: Click 'Reseller Program' in the menu to get your unique referral code and start earning!";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('📝 Create Ticket', 'create_ticket')],
        [Telegram::button('🔙 Back to Support', 'open_support')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function showTickets($chatId, $userId, $messageId = null) {
    global $telegram, $db;

    $tickets = $db->fetchAll(
        "SELECT * FROM tickets WHERE user_id = ? ORDER BY created_at DESC LIMIT 5",
        [$userId],
        'i'
    );

    if (empty($tickets)) {
        $text = "🎫 <b>My Tickets</b>\n\nNo tickets found.\n\nCreate one if you need help!";
    } else {
        $text = "🎫 <b>My Tickets</b>\n\n";
        foreach ($tickets as $ticket) {
            $statusEmoji = ['open' => '🟢', 'in_progress' => '🟡', 'resolved' => '✅', 'closed' => '🔴'][$ticket['status']] ?? '❓';
            $text .= "{$statusEmoji} <code>{$ticket['ticket_id']}</code>\n";
            $text .= "   {$ticket['subject']}\n";
            $text .= "   Status: {$ticket['status']}\n\n";
        }
    }

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('📝 New Ticket', 'create_ticket')],
        [Telegram::button('🏠 Main Menu', 'back_to_menu')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

// ============================================
// BALANCE & WALLET
// ============================================
function showBalance($chatId, $userId, $messageId = null) {
    global $telegram, $db;

    $user = $db->fetch("SELECT balance, total_spent, total_orders FROM users WHERE telegram_id = ?", [$userId], 'i');
    $stats = Helpers::getUserStats($userId);

    $text = "💰 <b>My Wallet</b>\n\n";
    $text .= "💵 <b>Balance:</b> " . Helpers::formatPrice($user['balance'] ?? 0) . "\n";
    $text .= "💸 <b>Total Spent:</b> " . Helpers::formatPrice($user['total_spent'] ?? 0) . "\n";
    $text .= "📦 <b>Total Orders:</b> " . ($user['total_orders'] ?? 0) . "\n";
    $text .= "👥 <b>Referrals:</b> " . $stats['referrals'] . "\n";
    $text .= "💵 <b>Commission Earned:</b> " . Helpers::formatPrice($stats['commission_earned']) . "\n\n";

    if (Helpers::isReseller($userId)) {
        $text .= "🤝 <b>Reseller Status:</b> Active ✅\n";
        $text .= "Use /reseller for dashboard\n";
    }

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('💼 Reseller Panel', 'reseller_info')],
        [Telegram::button('📦 My Orders', 'my_orders')],
        [Telegram::button('🏠 Main Menu', 'back_to_menu')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

// ============================================
// REFERRAL SYSTEM
// ============================================
function showReferral($chatId, $userId, $user = null, $messageId = null) {
    global $telegram, $db;

    if (!$user) {
        $user = $db->fetch("SELECT * FROM users WHERE telegram_id = ?", [$userId], 'i');
    }

    // Generate referral code if not exists
    if (empty($user['reseller_code'])) {
        $code = Helpers::generateResellerCode($user['first_name'] ?? 'User');
        $db->update('users', ['reseller_code' => $code], 'telegram_id = ?', [$userId]);
        $user['reseller_code'] = $code;
    }

    $referralLink = "https://t.me/" . BOT_USERNAME . "?start=" . $user['reseller_code'];
    $stats = Helpers::getUserStats($userId);

    $text = "🤝 <b>Referral Program</b>\n\n";
    $text .= "Invite friends and earn " . Helpers::formatPrice(REFERRAL_BONUS) . " per referral!\n\n";
    $text .= "<b>Your Stats:</b>\n";
    $text .= "👥 Total Referrals: {$stats['referrals']}\n";
    $text .= "💰 Bonus Earned: " . Helpers::formatPrice($stats['referrals'] * REFERRAL_BONUS) . "\n\n";
    $text .= "<b>Your Referral Link:</b>\n";
    $text .= "<code>{$referralLink}</code>\n\n";
    $text .= "📤 Share this link with friends. When they join and make their first purchase, you get rewarded!";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('📤 Share Link', null, "https://t.me/share/url?url=" . urlencode($referralLink) . "&text=" . urlencode("Join Team Hydra Shop for premium digital products at best prices!"))],
        [Telegram::button('💼 Become Reseller', 'become_reseller')],
        [Telegram::button('🏠 Main Menu', 'back_to_menu')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

// ============================================
// RESELLER SYSTEM
// ============================================
function handleReseller($chatId, $userId, $user) {
    global $telegram;

    if (Helpers::isReseller($userId)) {
        showResellerDashboard($chatId, $userId);
    } else {
        showResellerInfo($chatId, $userId);
    }
}

function showResellerInfo($chatId, $userId, $messageId = null) {
    global $telegram;

    $text = "💼 <b>Reseller Program</b>\n\n";
    $text .= "Start your own digital product business with ZERO investment!\n\n";
    $text .= "<b>Benefits:</b>\n";
    $text .= "✅ " . RESELLER_COMMISSION_RATE . "% commission on every sale\n";
    $text .= "✅ Real-time earnings tracking\n";
    $text .= "✅ Automatic commission calculation\n";
    $text .= "✅ Minimum withdrawal: " . Helpers::formatPrice(MIN_WITHDRAWAL) . "\n";
    $text .= "✅ Weekly payouts\n";
    $text .= "✅ Marketing materials provided\n\n";
    $text .= "<b>How it works:</b>\n";
    $text .= "1️⃣ Get your unique reseller code\n";
    $text .= "2️⃣ Share with friends & customers\n";
    $text .= "3️⃣ Earn on every purchase\n";
    $text .= "4️⃣ Withdraw earnings to UPI/Bank\n\n";
    $text .= "🚀 Ready to start earning?";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('🚀 Become Reseller', 'become_reseller')],
        [Telegram::button('📊 Reseller Dashboard', 'reseller_dashboard')],
        [Telegram::button('🔙 Back to Menu', 'back_to_menu')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function becomeReseller($chatId, $userId, $messageId = null) {
    global $telegram, $db;

    $user = $db->fetch("SELECT is_reseller, reseller_code FROM users WHERE telegram_id = ?", [$userId], 'i');

    if ($user['is_reseller']) {
        $telegram->sendMessage($chatId, "✅ You're already a reseller! Use /reseller for dashboard.");
        return;
    }

    // Generate code if not exists
    if (empty($user['reseller_code'])) {
        $userData = $db->fetch("SELECT first_name FROM users WHERE telegram_id = ?", [$userId], 'i');
        $code = Helpers::generateResellerCode($userData['first_name'] ?? 'User');
        $db->update('users', ['reseller_code' => $code, 'is_reseller' => 1], 'telegram_id = ?', [$userId]);
    } else {
        $db->update('users', ['is_reseller' => 1], 'telegram_id = ?', [$userId]);
    }

    $text = "🎉 <b>Congratulations!</b>\n\n";
    $text .= "You're now an official Team Hydra Shop reseller!\n\n";
    $text .= "<b>Next Steps:</b>\n";
    $text .= "1️⃣ Get your referral link from /referral\n";
    $text .= "2️⃣ Share on social media, WhatsApp, groups\n";
    $text .= "3️⃣ Track earnings in Reseller Dashboard\n";
    $text .= "4️⃣ Withdraw when you reach " . Helpers::formatPrice(MIN_WITHDRAWAL) . "\n\n";
    $text .= "💡 <i>Tip: Share your link with people interested in Netflix, ChatGPT, Spotify, etc.</i>";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('📊 Reseller Dashboard', 'reseller_dashboard')],
        [Telegram::button('🔗 Get Referral Link', 'my_referrals')],
        [Telegram::button('🏠 Main Menu', 'back_to_menu')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }

    // Notify admin
    $userData = $db->fetch("SELECT first_name, username FROM users WHERE telegram_id = ?", [$userId], 'i');
    Helpers::notifyAdmin("🤝 <b>New Reseller!</b>\n\nUser: " . ($userData['first_name'] ?? 'Unknown') . "\nID: {$userId}\nUsername: @" . ($userData['username'] ?? 'N/A'));
}

function showResellerDashboard($chatId, $userId, $messageId = null) {
    global $telegram, $db;

    $stats = Helpers::getUserStats($userId);
    $commissions = $db->fetchAll(
        "SELECT * FROM commissions WHERE reseller_id = ? ORDER BY created_at DESC LIMIT 5",
        [$userId],
        'i'
    );

    $pending = $db->fetch("SELECT SUM(amount) as total FROM commissions WHERE reseller_id = ? AND status = 'pending'", [$userId], 'i');
    $approved = $db->fetch("SELECT SUM(amount) as total FROM commissions WHERE reseller_id = ? AND status = 'approved'", [$userId], 'i');
    $paid = $db->fetch("SELECT SUM(amount) as total FROM commissions WHERE reseller_id = ? AND status = 'paid'", [$userId], 'i');

    $text = "📊 <b>Reseller Dashboard</b>\n\n";
    $text .= "<b>Earnings Summary:</b>\n";
    $text .= "⏳ Pending: " . Helpers::formatPrice($pending['total'] ?? 0) . "\n";
    $text .= "✅ Approved: " . Helpers::formatPrice($approved['total'] ?? 0) . "\n";
    $text .= "💰 Paid Out: " . Helpers::formatPrice($paid['total'] ?? 0) . "\n";
    $text .= "👥 Total Referrals: {$stats['referrals']}\n\n";

    if (!empty($commissions)) {
        $text .= "<b>Recent Commissions:</b>\n";
        foreach ($commissions as $comm) {
            $text .= "• " . Helpers::formatPrice($comm['amount']) . " - {$comm['status']}\n";
        }
        $text .= "\n";
    }

    $text .= "💡 Minimum withdrawal: " . Helpers::formatPrice(MIN_WITHDRAWAL);

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('💸 Request Withdrawal', 'withdraw')],
        [Telegram::button('🔗 Get Referral Link', 'my_referrals')],
        [Telegram::button('🏠 Main Menu', 'back_to_menu')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function handleWithdrawal($chatId, $userId, $messageId = null) {
    global $telegram, $db;

    $user = $db->fetch("SELECT balance FROM users WHERE telegram_id = ?", [$userId], 'i');
    $balance = $user['balance'] ?? 0;

    if ($balance < MIN_WITHDRAWAL) {
        $text = "❌ <b>Withdrawal Failed</b>\n\n";
        $text .= "Your balance: " . Helpers::formatPrice($balance) . "\n";
        $text .= "Minimum required: " . Helpers::formatPrice(MIN_WITHDRAWAL) . "\n\n";
        $text .= "Keep referring customers to reach the minimum!";

        $keyboard = Telegram::inlineKeyboard([
            [Telegram::button('🔗 Get Referral Link', 'my_referrals')],
            [Telegram::button('🔙 Back', 'reseller_dashboard')]
        ]);
    } else {
        $text = "💸 <b>Withdrawal Request</b>\n\n";
        $text .= "Available: " . Helpers::formatPrice($balance) . "\n\n";
        $text .= "To request withdrawal:\n";
        $text .= "1️⃣ Send your UPI ID\n";
        $text .= "2️⃣ Mention 'Withdrawal Request'\n";
        $text .= "3️⃣ Our team will process within 24 hours\n\n";
        $text .= "📱 Or contact us on WhatsApp: " . SUPPORT_WHATSAPP;

        $keyboard = Telegram::inlineKeyboard([
            [Telegram::button('📱 WhatsApp Withdrawal', null, 'https://wa.me/' . SUPPORT_WHATSAPP)],
            [Telegram::button('🔙 Back', 'reseller_dashboard')]
        ]);
    }

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

// ============================================
// PHOTO UPLOAD (Payment Screenshots)
// ============================================
function handlePhotoUpload($chatId, $userId, $photos, $caption) {
    global $telegram, $db;

    // Get largest photo
    $photo = end($photos);
    $fileId = $photo['file_id'];

    // Find pending order for this user
    $order = $db->fetch(
        "SELECT * FROM orders WHERE user_id = ? AND payment_status = 'pending' AND order_status = 'pending' ORDER BY created_at DESC LIMIT 1",
        [$userId],
        'i'
    );

    if (!$order) {
        $telegram->sendMessage($chatId, "📸 Photo received!\n\nIf this is a payment screenshot, please initiate an order first by browsing products and clicking 'Buy Now'.\n\nCaption: {$caption}");
        return;
    }

    // Update order with screenshot info
    $db->update('orders',
        ['notes' => "Payment screenshot received. File ID: {$fileId}. Caption: {$caption}"],
        'order_id = ?',
        [$order['order_id']]
    );

    $telegram->sendMessage($chatId, "✅ <b>Payment Screenshot Received!</b>\n\nOrder: <code>{$order['order_id']}</code>\n\n⏳ We're verifying your payment. You'll receive confirmation within 10-15 minutes.\n\n❓ Need urgent help? Contact @teamhydrashops", ['parse_mode' => 'HTML']);

    // Notify admin with photo
    $user = $db->fetch("SELECT first_name, username FROM users WHERE telegram_id = ?", [$userId], 'i');
    $adminMsg = "📸 <b>Payment Screenshot!</b>\n\n";
    $adminMsg .= "👤 User: " . ($user['first_name'] ?? 'Unknown') . "\n";
    $adminMsg .= "🆔 User ID: {$userId}\n";
    $adminMsg .= "🆔 Order: <code>{$order['order_id']}</code>\n";
    $adminMsg .= "💰 Amount: " . Helpers::formatPrice($order['total_price']) . "\n";
    $adminMsg .= "📝 Caption: {$caption}\n\n";
    $adminMsg .= "Click to process:";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('✅ Confirm Payment', 'process_order:' . $order['order_id'])],
        [Telegram::button('❌ Cancel Order', 'cancel_order:' . $order['order_id'])]
    ]);

    $telegram->sendPhoto(ADMIN_TELEGRAM_ID, $fileId, $adminMsg, ['reply_markup' => $keyboard]);
}

// ============================================
// ADMIN PANEL
// ============================================
function handleAdmin($chatId, $userId) {
    global $telegram;

    if (!Helpers::isAdmin($userId)) {
        $telegram->sendMessage($chatId, "🚫 You don't have admin access.");
        return;
    }

    showAdminDashboard($chatId);
}

function showAdminDashboard($chatId, $messageId = null) {
    global $telegram;

    $stats = Helpers::getBotStats();

    $text = "🔐 <b>Admin Dashboard</b>\n\n";
    $text .= "<b>Bot Statistics:</b>\n";
    $text .= "👥 Total Users: {$stats['total_users']}\n";
    $text .= "📈 New Today: {$stats['new_users_today']}\n";
    $text .= "📦 Total Orders: {$stats['total_orders']}\n";
    $text .= "📊 Orders Today: {$stats['orders_today']}\n";
    $text .= "💰 Total Revenue: " . Helpers::formatPrice($stats['total_revenue']) . "\n";
    $text .= "🎫 Open Tickets: {$stats['open_tickets']}\n";
    $text .= "🤝 Resellers: {$stats['total_resellers']}\n\n";
    $text .= "Select an option:";

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('📦 Orders', 'admin_orders'), Telegram::button('👥 Users', 'admin_users')],
        [Telegram::button('🎫 Tickets', 'admin_tickets'), Telegram::button('📦 Products', 'admin_products')],
        [Telegram::button('📢 Broadcast', 'admin_broadcast'), Telegram::button('📊 Stats', 'admin_dashboard')],
        [Telegram::button('🏠 Main Menu', 'back_to_menu')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function showAdminStats($chatId) {
    global $telegram;

    $stats = Helpers::getBotStats();

    $text = "📊 <b>Detailed Statistics</b>\n\n";
    $text .= "<b>Users:</b>\n";
    $text .= "• Total: {$stats['total_users']}\n";
    $text .= "• Today: {$stats['new_users_today']}\n\n";
    $text .= "<b>Orders:</b>\n";
    $text .= "• Total: {$stats['total_orders']}\n";
    $text .= "• Today: {$stats['orders_today']}\n";
    $text .= "• Revenue: " . Helpers::formatPrice($stats['total_revenue']) . "\n\n";
    $text .= "<b>Support:</b>\n";
    $text .= "• Open Tickets: {$stats['open_tickets']}\n\n";
    $text .= "<b>Resellers:</b>\n";
    $text .= "• Total: {$stats['total_resellers']}";

    $telegram->sendMessage($chatId, $text);
}

function showAdminOrders($chatId, $messageId = null) {
    global $telegram, $db;

    $orders = $db->fetchAll(
        "SELECT o.*, p.name as product_name, u.first_name, u.username 
         FROM orders o 
         JOIN products p ON o.product_id = p.id 
         JOIN users u ON o.user_id = u.telegram_id 
         WHERE o.order_status IN ('pending', 'processing') 
         ORDER BY o.created_at DESC 
         LIMIT 10"
    );

    if (empty($orders)) {
        $text = "📦 <b>Pending Orders</b>\n\nNo pending orders! 🎉";
    } else {
        $text = "📦 <b>Pending Orders</b>\n\n";
        foreach ($orders as $order) {
            $text .= "<code>{$order['order_id']}</code>\n";
            $text .= "👤 {$order['first_name']} (@{$order['username']})\n";
            $text .= "📦 {$order['product_name']}\n";
            $text .= "💰 " . Helpers::formatPrice($order['total_price']) . " | {$order['payment_status']}\n";
            $text .= "📅 " . Helpers::formatDate($order['created_at']) . "\n\n";
        }
    }

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('🔙 Back to Admin', 'admin_dashboard')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function showAdminUsers($chatId, $messageId = null) {
    global $telegram, $db;

    $users = $db->fetchAll("SELECT telegram_id, first_name, username, is_reseller, created_at FROM users ORDER BY created_at DESC LIMIT 10");

    if (empty($users)) {
        $text = "👥 <b>Users</b>\n\nNo users found.";
    } else {
        $text = "👥 <b>Recent Users</b>\n\n";
        foreach ($users as $user) {
            $resellerBadge = $user['is_reseller'] ? ' 🤝' : '';
            $text .= "• {$user['first_name']}{$resellerBadge}\n";
            $text .= "  ID: <code>{$user['telegram_id']}</code>\n";
            $text .= "  @{$user['username']} | " . Helpers::formatDate($user['created_at'], 'd M') . "\n\n";
        }
    }

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('🔙 Back to Admin', 'admin_dashboard')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function showAdminTickets($chatId, $messageId = null) {
    global $telegram, $db;

    $tickets = $db->fetchAll(
        "SELECT t.*, u.first_name, u.username 
         FROM tickets t 
         JOIN users u ON t.user_id = u.telegram_id 
         WHERE t.status IN ('open', 'in_progress') 
         ORDER BY t.created_at DESC 
         LIMIT 10"
    );

    if (empty($tickets)) {
        $text = "🎫 <b>Open Tickets</b>\n\nNo open tickets! 🎉";
    } else {
        $text = "🎫 <b>Open Tickets</b>\n\n";
        foreach ($tickets as $ticket) {
            $text .= "<code>{$ticket['ticket_id']}</code>\n";
            $text .= "👤 {$ticket['first_name']} (@{$ticket['username']})\n";
            $text .= "📌 {$ticket['subject']}\n";
            $text .= "🔴 {$ticket['priority']} | {$ticket['status']}\n\n";
        }
    }

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('🔙 Back to Admin', 'admin_dashboard')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function showAdminProducts($chatId, $messageId = null) {
    global $telegram, $db;

    $products = $db->fetchAll("SELECT p.*, c.name as category_name FROM products p JOIN categories c ON p.category_id = c.id ORDER BY p.id DESC LIMIT 10");

    $text = "📦 <b>Products</b>\n\n";
    foreach ($products as $product) {
        $statusEmoji = $product['status'] === 'active' ? '✅' : '❌';
        $text .= "{$statusEmoji} {$product['name']}\n";
        $text .= "   " . Helpers::formatPrice($product['price']) . " | Stock: {$product['stock']}\n";
        $text .= "   {$product['category_name']}\n\n";
    }

    $keyboard = Telegram::inlineKeyboard([
        [Telegram::button('🔙 Back to Admin', 'admin_dashboard')]
    ]);

    if ($messageId) {
        $telegram->editMessageText($chatId, $messageId, $text, ['reply_markup' => $keyboard]);
    } else {
        $telegram->sendMessage($chatId, $text, ['reply_markup' => $keyboard]);
    }
}

function processOrder($chatId, $orderId, $messageId = null) {
    global $telegram, $db;

    $order = $db->fetch("SELECT * FROM orders WHERE order_id = ?", [$orderId], 's');

    if (!$order) {
        $telegram->sendMessage($chatId, "❌ Order not found.");
        return;
    }

    // Process the order (same logic as confirmPayment)
    confirmPayment($order['user_id'], $order['user_id'], $orderId);

    $telegram->sendMessage($chatId, "✅ Order <code>{$orderId}</code> processed successfully!", ['parse_mode' => 'HTML']);
}

function resolveTicket($chatId, $ticketId, $messageId = null) {
    global $telegram, $db;

    $db->update('tickets',
        ['status' => 'resolved', 'resolved_at' => date('Y-m-d H:i:s')],
        'ticket_id = ?',
        [$ticketId]
    );

    $ticket = $db->fetch("SELECT user_id FROM tickets WHERE ticket_id = ?", [$ticketId], 's');

    if ($ticket) {
        $telegram->sendMessage(
            $ticket['user_id'],
            "✅ <b>Ticket Resolved!</b>\n\nYour ticket <code>{$ticketId}</code> has been resolved.\n\nIf you need further assistance, feel free to create a new ticket."
        );
    }

    $telegram->sendMessage($chatId, "✅ Ticket <code>{$ticketId}</code> resolved!", ['parse_mode' => 'HTML']);
}

function banUser($chatId, $targetUserId, $messageId = null) {
    global $telegram, $db;

    $db->update('users', ['status' => 'banned'], 'telegram_id = ?', [$targetUserId]);

    $telegram->sendMessage($targetUserId, "🚫 Your account has been suspended. Contact admin for more information.");
    $telegram->sendMessage($chatId, "🚫 User <code>{$targetUserId}</code> has been banned.", ['parse_mode' => 'HTML']);
}

function unbanUser($chatId, $targetUserId, $messageId = null) {
    global $telegram, $db;

    $db->update('users', ['status' => 'active'], 'telegram_id = ?', [$targetUserId]);

    $telegram->sendMessage($targetUserId, "✅ Your account has been reinstated. You can now use the bot again.");
    $telegram->sendMessage($chatId, "✅ User <code>{$targetUserId}</code> has been unbanned.", ['parse_mode' => 'HTML']);
}

function showUserList($chatId) {
    global $telegram, $db;

    $count = $db->fetch("SELECT COUNT(*) as total FROM users");
    $telegram->sendMessage($chatId, "👥 Total users: {$count['total']}\n\nUse /admin for detailed user management.");
}

// ============================================
// PRE-CHECKOUT QUERY (Telegram Payments)
// ============================================
function handlePreCheckoutQuery($preCheckoutQuery) {
    global $telegram;

    $preCheckoutQueryId = $preCheckoutQuery['id'];

    // Always approve for now (implement your logic)
    $telegram->answerPreCheckoutQuery($preCheckoutQueryId, true);
}
