<?php
require_once '../../includes/functions.php';
require_once '../../includes/email_service.php';
require_once '../../includes/smm_api.php';

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

if (!$update) {
    http_response_code(200);
    exit;
}

$stmt = $pdo->query("SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN ('telegram_bot_token', 'telegram_admin_id')");
$settings = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$botToken = $settings['telegram_bot_token'] ?? '';
$adminId = $settings['telegram_admin_id'] ?? '';

if (empty($botToken) || empty($adminId)) {
    http_response_code(200);
    exit;
}

function sendTelegramMessage($botToken, $chatId, $text, $replyMarkup = null) {
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $data = [
        'chat_id' => $chatId,
        'text' => $text,
        'parse_mode' => 'HTML'
    ];
    
    if ($replyMarkup) {
        $data['reply_markup'] = json_encode($replyMarkup);
    }
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

function answerCallbackQuery($botToken, $callbackQueryId, $text = '') {
    $url = "https://api.telegram.org/bot{$botToken}/answerCallbackQuery";
    $data = [
        'callback_query_id' => $callbackQueryId,
        'text' => $text
    ];
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_exec($ch);
    curl_close($ch);
}

function editMessageText($botToken, $chatId, $messageId, $text, $replyMarkup = null) {
    $url = "https://api.telegram.org/bot{$botToken}/editMessageText";
    $data = [
        'chat_id' => $chatId,
        'message_id' => $messageId,
        'text' => $text,
        'parse_mode' => 'HTML'
    ];
    
    if ($replyMarkup) {
        $data['reply_markup'] = json_encode($replyMarkup);
    }
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_exec($ch);
    curl_close($ch);
}

function sendReplyKeyboard($botToken, $chatId, $text, array $keyboard) {
    $replyMarkup = [
        'keyboard' => $keyboard,
        'resize_keyboard' => true,
        'one_time_keyboard' => false
    ];
    sendTelegramMessage($botToken, $chatId, $text, $replyMarkup);
}

function sendOrderToSmmProvider($orderId, $forcedServiceId = null) {
    global $pdo;

    $stmt = $pdo->prepare("
        SELECT o.id, o.status, o.quantity, o.telegram_link, p.smm_service_id
        FROM orders o
        JOIN products p ON o.product_id = p.id
        WHERE o.id = ?
    ");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order) {
        return [false, 'سفارش یافت نشد', null];
    }
    if ($order['status'] !== 'pending') {
        return [false, 'این سفارش قابل ارسال به SMM نیست', null];
    }

    $targetServiceId = $forcedServiceId !== null ? (int)$forcedServiceId : (int)$order['smm_service_id'];
    if (empty($targetServiceId)) {
        return [false, 'Service ID برای این محصول تنظیم نشده است', null];
    }

    $stmt = $pdo->query("SELECT setting_value FROM app_settings WHERE setting_key = 'smm_api_key'");
    $smmApiKey = $stmt->fetchColumn();
    if (empty($smmApiKey)) {
        return [false, 'API Key SMM تنظیم نشده است', null];
    }

    $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = 'orders_sent_to_smm'");
    $stmt->execute();
    $smmData = $stmt->fetchColumn();
    $sentToSmm = [];
    if ($smmData) {
        $sentToSmm = json_decode($smmData, true) ?: [];
    }
    if (in_array($orderId, $sentToSmm)) {
        return [false, 'این سفارش قبلاً به SMM ارسال شده است', null];
    }

    $api = new SMMApi($smmApiKey);
    $telegramLink = $order['telegram_link'];
    if (!preg_match('/^https?:\/\//', $telegramLink)) {
        $telegramLink = 'https://' . $telegramLink;
    }

    $smmOrder = $api->order([
        'service' => $targetServiceId,
        'link' => $telegramLink,
        'quantity' => $order['quantity']
    ]);

    if (!$smmOrder || !isset($smmOrder->order)) {
        $errorMsg = isset($smmOrder->error) ? $smmOrder->error : 'خطای نامشخص';
        return [false, "خطا در ارسال به SMM: " . $errorMsg, null];
    }

    $sentToSmm[] = $orderId;
    $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $stmt->execute(['orders_sent_to_smm', json_encode($sentToSmm), json_encode($sentToSmm)]);

    $stmt = $pdo->query("SELECT setting_value FROM app_settings WHERE setting_key = 'smm_orders'");
    $smmOrdersData = $stmt->fetchColumn();
    $smmOrders = [];
    if ($smmOrdersData) {
        $smmOrders = json_decode($smmOrdersData, true) ?: [];
    }

    $smmOrders[$orderId] = [
        'smm_order_id' => $smmOrder->order,
        'status' => 'Pending',
        'sent_at' => date('Y-m-d H:i:s'),
        'service_id' => $targetServiceId,
        'route' => $forcedServiceId !== null ? 'cheap' : 'default'
    ];

    $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $stmt->execute(['smm_orders', json_encode($smmOrders), json_encode($smmOrders)]);

    return [true, '', ['smm_order_id' => $smmOrder->order, 'service_id' => $targetServiceId]];
}

function getAdminState($chatId) {
    global $pdo;
    $key = 'telegram_admin_state_' . $chatId;
    $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ?");
    $stmt->execute([$key]);
    $value = $stmt->fetchColumn();
    if ($value) {
        $state = json_decode($value, true);
        if (is_array($state)) {
            return $state;
        }
    }
    return [];
}

function storeAdminState($chatId, array $state) {
    global $pdo;
    $key = 'telegram_admin_state_' . $chatId;
    if (empty($state)) {
        $stmt = $pdo->prepare("DELETE FROM app_settings WHERE setting_key = ?");
        $stmt->execute([$key]);
        return [];
    }
    $json = json_encode($state, JSON_UNESCAPED_UNICODE);
    $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
    $stmt->execute([$key, $json]);
    return $state;
}

function updateAdminState($chatId, array $updates = [], $replace = false) {
    $state = $replace ? [] : getAdminState($chatId);
    foreach ($updates as $key => $value) {
        if ($value === null) {
            unset($state[$key]);
        } else {
            $state[$key] = $value;
        }
    }
    return storeAdminState($chatId, $state);
}

function clearAdminState($chatId) {
    storeAdminState($chatId, []);
}

function sendMainMenu($botToken, $chatId) {
    updateAdminState($chatId, [
        'current_menu' => 'main',
        'pending_action' => null,
        'pending_data' => null
    ], true);
    $keyboard = [
        ['📊 آمار و گزارش‌ها', '👥 مدیریت کاربران'],
        ['📋 سفارشات در انتظار']
    ];
    $text = "به پنل مدیریت ربات خوش آمدید!\n\nیکی از گزینه‌های زیر را انتخاب کنید:";
    sendReplyKeyboard($botToken, $chatId, $text, $keyboard);
}

function sendStatsMenu($botToken, $chatId) {
    updateAdminState($chatId, [
        'current_menu' => 'stats',
        'pending_action' => null,
        'pending_data' => null
    ], true);
    $keyboard = [
        ['📈 آمار کلی', '📅 آمار امروز'],
        ['📆 آمار هفتگی/ماهانه'],
        ['🏆 محصولات پرفروش'],
        ['⬅️ بازگشت']
    ];
    $text = "بخش آمار و گزارش‌ها:\nیکی از گزینه‌ها را انتخاب کنید یا با «⬅️ بازگشت» به منوی اصلی برگردید.";
    sendReplyKeyboard($botToken, $chatId, $text, $keyboard);
}

function sendUserManagementMenu($botToken, $chatId) {
    updateAdminState($chatId, [
        'current_menu' => 'user_management',
        'pending_action' => null,
        'pending_data' => null
    ], true);
    $keyboard = [
        ['🔎 جستجوی کاربر', '👤 مشاهده پروفایل'],
        ['💰 مدیریت سکه', '🚫 مسدود/فعال‌سازی'],
        ['📋 لیست کاربران'],
        ['⬅️ بازگشت']
    ];
    $text = "بخش مدیریت کاربران:\nگزینه مورد نظر را انتخاب کنید یا با «⬅️ بازگشت» به منوی اصلی برگردید.";
    sendReplyKeyboard($botToken, $chatId, $text, $keyboard);
}

function getPendingOrdersOverview() {
    global $pdo;
    $stmt = $pdo->prepare("
        SELECT o.id, o.quantity, o.total_coins, o.status, o.created_at, o.telegram_link, o.coin_type,
               u.username, u.full_name,
               p.name as product_name
        FROM orders o
        JOIN users u ON o.user_id = u.id
        JOIN products p ON o.product_id = p.id
        WHERE o.status != 'completed'
        ORDER BY o.created_at DESC
        LIMIT 20
    ");
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (empty($orders)) {
        return [
            'text' => "📋 <b>لیست سفارشات</b>\n\nهیچ سفارش در انتظاری وجود ندارد.",
            'keyboard' => null
        ];
    }
    $text = "📋 <b>لیست سفارشات</b>\n\n";
    $keyboardButtons = [];
    foreach ($orders as $order) {
        $statusText = $order['status'] === 'pending' ? '⏳ در انتظار' : '❌ لغو شده';
        $coinTypeText = $order['coin_type'] === 'free' ? '⭐ رایگان' : '💰 معمولی';
        $text .= "🆔 سفارش #{$order['id']}\n";
        $text .= "👤 کاربر: {$order['full_name']} (@{$order['username']})\n";
        $text .= "📦 محصول: {$order['product_name']}\n";
        $text .= "🔢 تعداد: {$order['quantity']}\n";
        $text .= "💵 قیمت: {$order['total_coins']} سکه ({$coinTypeText})\n";
        $text .= "📅 تاریخ: " . date('Y/m/d H:i', strtotime($order['created_at'])) . "\n";
        $text .= "🔗 لینک: {$order['telegram_link']}\n";
        $text .= "📊 وضعیت: {$statusText}\n\n";
        $keyboardButtons[] = [
            ['text' => "مشاهده سفارش #{$order['id']}", 'callback_data' => "view_order_{$order['id']}"]
        ];
    }
    return [
        'text' => $text,
        'keyboard' => ['inline_keyboard' => $keyboardButtons]
    ];
}

function sendOverallStats($botToken, $chatId) {
    global $pdo;
    $totalUsers = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $totalProducts = (int)$pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();
    $totalOrders = (int)$pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'completed'")->fetchColumn();
    $totalRevenue = (int)$pdo->query("SELECT COALESCE(SUM(total_coins), 0) FROM orders WHERE status = 'completed'")->fetchColumn();
    $totalAdmobCoins = (int)$pdo->query("SELECT COALESCE(SUM(coins_earned), 0) FROM video_rewards")->fetchColumn();
    $text = "📈 <b>آمار کلی</b>\n\n";
    $text .= "👥 کل کاربران: " . number_format($totalUsers) . "\n";
    $text .= "🛒 محصولات فعال: " . number_format($totalProducts) . "\n";
    $text .= "✅ سفارشات تکمیل‌شده: " . number_format($totalOrders) . "\n";
    $text .= "💰 درآمد کل (سکه): " . number_format($totalRevenue) . "\n";
    $text .= "🎁 سکه‌های دریافتی از ویدیو: " . number_format($totalAdmobCoins);
    sendTelegramMessage($botToken, $chatId, $text);
}

function sendTodayStats($botToken, $chatId) {
    global $pdo;
    $newUsers = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE DATE(created_at) = CURDATE()")->fetchColumn();
    $newOrders = (int)$pdo->query("SELECT COUNT(*) FROM orders WHERE DATE(created_at) = CURDATE()")->fetchColumn();
    $completedOrders = (int)$pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'completed' AND DATE(created_at) = CURDATE()")->fetchColumn();
    $revenueToday = (int)$pdo->query("SELECT COALESCE(SUM(total_coins), 0) FROM orders WHERE status = 'completed' AND DATE(created_at) = CURDATE()")->fetchColumn();
    $adViews = (int)$pdo->query("SELECT COUNT(*) FROM video_rewards WHERE DATE(viewed_at) = CURDATE()")->fetchColumn();
    $adCoins = (int)$pdo->query("SELECT COALESCE(SUM(coins_earned), 0) FROM video_rewards WHERE DATE(viewed_at) = CURDATE()")->fetchColumn();
    $text = "📅 <b>آمار امروز</b>\n\n";
    $text .= "👥 کاربران جدید: " . number_format($newUsers) . "\n";
    $text .= "🛒 سفارشات ثبت‌شده: " . number_format($newOrders) . "\n";
    $text .= "✅ سفارشات تکمیل‌شده: " . number_format($completedOrders) . "\n";
    $text .= "💰 درآمد امروز (سکه): " . number_format($revenueToday) . "\n";
    $text .= "🎬 ویدیوهای دیده‌شده: " . number_format($adViews) . "\n";
    $text .= "🎁 سکه‌های ویدیویی: " . number_format($adCoins);
    sendTelegramMessage($botToken, $chatId, $text);
}

function sendWeeklyMonthlyStats($botToken, $chatId) {
    global $pdo;
    $weekUsers = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetchColumn();
    $weekOrders = (int)$pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'completed' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetchColumn();
    $weekRevenue = (int)$pdo->query("SELECT COALESCE(SUM(total_coins), 0) FROM orders WHERE status = 'completed' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetchColumn();
    $monthUsers = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)")->fetchColumn();
    $monthOrders = (int)$pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'completed' AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)")->fetchColumn();
    $monthRevenue = (int)$pdo->query("SELECT COALESCE(SUM(total_coins), 0) FROM orders WHERE status = 'completed' AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)")->fetchColumn();
    $text = "📆 <b>آمار هفتگی و ماهانه</b>\n\n";
    $text .= "📈 ۷ روز اخیر:\n";
    $text .= " • کاربران جدید: " . number_format($weekUsers) . "\n";
    $text .= " • سفارشات تکمیل‌شده: " . number_format($weekOrders) . "\n";
    $text .= " • درآمد (سکه): " . number_format($weekRevenue) . "\n\n";
    $text .= "📈 ۳۰ روز اخیر:\n";
    $text .= " • کاربران جدید: " . number_format($monthUsers) . "\n";
    $text .= " • سفارشات تکمیل‌شده: " . number_format($monthOrders) . "\n";
    $text .= " • درآمد (سکه): " . number_format($monthRevenue);
    sendTelegramMessage($botToken, $chatId, $text);
}

function sendTopProducts($botToken, $chatId) {
    global $pdo;
    $stmt = $pdo->prepare("
        SELECT p.name, COUNT(o.id) AS orders_count, COALESCE(SUM(o.total_coins), 0) AS revenue
        FROM orders o
        JOIN products p ON o.product_id = p.id
        WHERE o.status = 'completed'
        GROUP BY p.id, p.name
        ORDER BY revenue DESC
        LIMIT 5
    ");
    $stmt->execute();
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (empty($products)) {
        sendTelegramMessage($botToken, $chatId, "🏆 هنوز محصول فروخته‌شده‌ای وجود ندارد.");
        return;
    }
    $text = "🏆 <b>محصولات پرفروش</b>\n\n";
    foreach ($products as $index => $product) {
        $rank = $index + 1;
        $text .= "{$rank}. {$product['name']}\n";
        $text .= "   • سفارشات: " . number_format($product['orders_count']) . "\n";
        $text .= "   • درآمد (سکه): " . number_format($product['revenue']) . "\n";
    }
    sendTelegramMessage($botToken, $chatId, $text);
}

function promptUserSearch($botToken, $chatId) {
    updateAdminState($chatId, ['pending_action' => 'search_user']);
    $text = "🔎 لطفا نام کاربری، ایمیل یا شناسه عددی کاربر را ارسال کنید.\nبرای لغو، عبارت «لغو» را ارسال کنید.";
    sendTelegramMessage($botToken, $chatId, $text);
}

function handleUserSearch($botToken, $chatId, $query) {
    global $pdo;
    $like = '%' . $query . '%';
    $userId = ctype_digit($query) ? (int)$query : 0;
    $stmt = $pdo->prepare("
        SELECT id, username, email, full_name, coins, free_coins, is_active, created_at
        FROM users
        WHERE username LIKE ? OR email LIKE ? OR id = ?
        ORDER BY created_at DESC
        LIMIT 5
    ");
    $stmt->execute([$like, $like, $userId]);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (empty($users)) {
        sendTelegramMessage($botToken, $chatId, "❌ کاربری با این مشخصات یافت نشد.");
    } else {
        $text = "🔍 <b>نتایج جستجو</b>\n\n";
        foreach ($users as $user) {
            $status = $user['is_active'] ? '✅ فعال' : '⛔️ غیرفعال';
            $text .= "🆔 {$user['id']} | @{$user['username']}\n";
            $text .= "👤 {$user['full_name']} | {$user['email']}\n";
            $text .= "💰 سکه: " . number_format($user['coins']) . " | ⭐ رایگان: " . number_format($user['free_coins']) . "\n";
            $text .= "📅 ثبت‌نام: " . date('Y/m/d H:i', strtotime($user['created_at'])) . "\n";
            $text .= "📊 وضعیت: {$status}\n\n";
        }
        sendTelegramMessage($botToken, $chatId, $text);
    }
    updateAdminState($chatId, ['pending_action' => null, 'pending_data' => null]);
}

function promptUserProfile($botToken, $chatId) {
    updateAdminState($chatId, ['pending_action' => 'view_user']);
    $text = "👤 لطفا شناسه عددی کاربر یا نام کاربری (بدون @) را ارسال کنید.\nبرای لغو، «لغو» را ارسال کنید.";
    sendTelegramMessage($botToken, $chatId, $text);
}

function handleUserProfile($botToken, $chatId, $input) {
    global $pdo;
    $identifier = ltrim(trim($input), '@');
    if ($identifier === '') {
        sendTelegramMessage($botToken, $chatId, "❌ ورودی نامعتبر است.");
        return;
    }
    if (ctype_digit($identifier)) {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([(int)$identifier]);
    } else {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$identifier]);
    }
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        sendTelegramMessage($botToken, $chatId, "❌ کاربر یافت نشد.");
        updateAdminState($chatId, ['pending_action' => null, 'pending_data' => null]);
        return;
    }
    $ordersCountStmt = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE user_id = ?");
    $ordersCountStmt->execute([$user['id']]);
    $ordersCount = (int)$ordersCountStmt->fetchColumn();
    $ordersSumStmt = $pdo->prepare("SELECT COALESCE(SUM(total_coins), 0) FROM orders WHERE user_id = ? AND status = 'completed'");
    $ordersSumStmt->execute([$user['id']]);
    $ordersCoins = (int)$ordersSumStmt->fetchColumn();
    $videosStmt = $pdo->prepare("SELECT COUNT(*), COALESCE(SUM(coins_earned), 0) FROM video_rewards WHERE user_id = ?");
    $videosStmt->execute([$user['id']]);
    [$videoCount, $videoCoins] = $videosStmt->fetch(PDO::FETCH_NUM);
    $status = $user['is_active'] ? '✅ فعال' : '⛔️ غیرفعال';
    $text = "👤 <b>پروفایل کاربر</b>\n\n";
    $text .= "🆔 شناسه: {$user['id']}\n";
    $text .= "🔖 نام کاربری: @{$user['username']}\n";
    $text .= "👤 نام: {$user['full_name']}\n";
    $text .= "📧 ایمیل: {$user['email']}\n";
    if (!empty($user['phone'])) {
        $text .= "📱 تلفن: {$user['phone']}\n";
    }
    $text .= "💰 سکه: " . number_format($user['coins']) . "\n";
    $text .= "⭐ سکه رایگان: " . number_format($user['free_coins']) . "\n";
    $text .= "📅 ثبت‌نام: " . date('Y/m/d H:i', strtotime($user['created_at'])) . "\n";
    $text .= "📊 وضعیت: {$status}\n\n";
    $text .= "🛒 سفارشات: " . number_format($ordersCount) . "\n";
    $text .= "💵 مجموع سکه سفارشات تکمیل‌شده: " . number_format($ordersCoins) . "\n";
    $text .= "🎬 ویدیوهای تماشا شده: " . number_format($videoCount) . "\n";
    $text .= "🎁 سکه دریافتی از ویدیو: " . number_format($videoCoins);
    sendTelegramMessage($botToken, $chatId, $text);
    updateAdminState($chatId, ['pending_action' => null, 'pending_data' => null]);
}

function promptAdjustCoins($botToken, $chatId) {
    updateAdminState($chatId, ['pending_action' => 'adjust_coins']);
    $text = "💰 برای تنظیم سکه، ورودی را به شکل زیر ارسال کنید:\n\n<code>user_id مقدار نوع</code>\nمثال: <code>123 50 regular</code> یا <code>123 -20 free</code>\n\nنوع‌ها: <code>regular</code> یا <code>free</code>\nبرای لغو، «لغو» را ارسال کنید.";
    sendTelegramMessage($botToken, $chatId, $text);
}

function handleAdjustCoins($botToken, $chatId, $input) {
    global $pdo;
    $parts = preg_split('/\s+/', trim($input));
    if (count($parts) < 3) {
        sendTelegramMessage($botToken, $chatId, "❌ فرمت ورودی نامعتبر است. مثال: <code>123 50 regular</code>");
        return;
    }
    [$userPart, $amountPart, $typePart] = [$parts[0], $parts[1], strtolower($parts[2])];
    if (!ctype_digit($userPart)) {
        sendTelegramMessage($botToken, $chatId, "❌ شناسه کاربر باید عدد باشد.");
        return;
    }
    $userId = (int)$userPart;
    if (!preg_match('/^[+-]?\d+$/', $amountPart)) {
        sendTelegramMessage($botToken, $chatId, "❌ مقدار باید یک عدد صحیح باشد (مثبت یا منفی).");
        return;
    }
    $amount = (int)$amountPart;
    if ($amount === 0) {
        sendTelegramMessage($botToken, $chatId, "❌ مقدار باید غیر صفر باشد.");
        return;
    }
    $typeMappings = [
        'regular' => 'coins',
        'coin' => 'coins',
        'coins' => 'coins',
        'free' => 'free_coins',
        'freecoins' => 'free_coins',
        'free_coins' => 'free_coins'
    ];
    if (!isset($typeMappings[$typePart])) {
        sendTelegramMessage($botToken, $chatId, "❌ نوع باید یکی از «regular» یا «free» باشد.");
        return;
    }
    $column = $typeMappings[$typePart];
    $coinType = $column === 'coins' ? 'regular' : 'free';
    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("SELECT coins, free_coins FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            $pdo->rollBack();
            sendTelegramMessage($botToken, $chatId, "❌ کاربر یافت نشد.");
            return;
        }
        $currentBalance = (int)$user[$column];
        $newBalance = $currentBalance + $amount;
        if ($newBalance < 0) {
            $pdo->rollBack();
            sendTelegramMessage($botToken, $chatId, "❌ موجودی کافی نیست. موجودی فعلی: " . number_format($currentBalance));
            return;
        }
        $updateStmt = $pdo->prepare("UPDATE users SET {$column} = {$column} + ? WHERE id = ?");
        $updateStmt->execute([$amount, $userId]);
        $description = "Admin adjustment via bot ({$coinType})";
        $transactionStmt = $pdo->prepare("
            INSERT INTO transactions (user_id, type, amount, coin_type, description)
            VALUES (?, 'admin_adjustment', ?, ?, ?)
        ");
        $transactionStmt->execute([$userId, $amount, $coinType, $description]);
        $pdo->commit();
        $sign = $amount > 0 ? '+' : '';
        $text = "✅ تغییر سکه با موفقیت انجام شد.\n";
        $text .= "🆔 کاربر: {$userId}\n";
        $text .= "💰 تغییر: {$sign}" . number_format($amount) . " ({$coinType})\n";
        $text .= "💼 موجودی جدید: " . number_format($newBalance);
        sendTelegramMessage($botToken, $chatId, $text);
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        sendTelegramMessage($botToken, $chatId, "❌ خطا در ثبت تغییر: " . $e->getMessage());
    }
    updateAdminState($chatId, ['pending_action' => null, 'pending_data' => null]);
}

function promptToggleUserStatus($botToken, $chatId) {
    updateAdminState($chatId, ['pending_action' => 'toggle_user_status']);
    $text = "🚫 برای تغییر وضعیت کاربر، شناسه عددی او را ارسال کنید.\nبرای لغو، «لغو» را ارسال کنید.";
    sendTelegramMessage($botToken, $chatId, $text);
}

function handleToggleUserStatus($botToken, $chatId, $input) {
    global $pdo;
    if (!ctype_digit(trim($input))) {
        sendTelegramMessage($botToken, $chatId, "❌ شناسه کاربر باید عدد باشد.");
        return;
    }
    $userId = (int)$input;
    $stmt = $pdo->prepare("SELECT id, username, full_name, is_active FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        sendTelegramMessage($botToken, $chatId, "❌ کاربر یافت نشد.");
        updateAdminState($chatId, ['pending_action' => null, 'pending_data' => null]);
        return;
    }
    $newStatus = $user['is_active'] ? 0 : 1;
    $stmt = $pdo->prepare("UPDATE users SET is_active = ? WHERE id = ?");
    $stmt->execute([$newStatus, $userId]);
    $statusText = $newStatus ? '✅ فعال شد' : '⛔️ غیرفعال شد';
    $text = "وضعیت کاربر به‌روزرسانی شد:\n";
    $text .= "🆔 {$user['id']} | @{$user['username']}\n";
    $text .= "👤 {$user['full_name']}\n";
    $text .= "📊 وضعیت جدید: {$statusText}";
    sendTelegramMessage($botToken, $chatId, $text);
    updateAdminState($chatId, ['pending_action' => null, 'pending_data' => null]);
}

function sendLatestUsersList($botToken, $chatId) {
    global $pdo;
    $stmt = $pdo->query("
        SELECT id, username, email, full_name, coins, free_coins, is_active, created_at
        FROM users
        ORDER BY created_at DESC
        LIMIT 10
    ");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (empty($users)) {
        sendTelegramMessage($botToken, $chatId, "📋 هیچ کاربری ثبت نشده است.");
        return;
    }
    $text = "📋 <b>آخرین کاربران ثبت‌نام‌شده</b>\n\n";
    foreach ($users as $user) {
        $status = $user['is_active'] ? '✅' : '⛔️';
        $text .= "{$status} {$user['id']} | @{$user['username']} | {$user['email']}\n";
        $text .= "👤 {$user['full_name']} | 💰 " . number_format($user['coins']) . " | ⭐ " . number_format($user['free_coins']) . "\n";
        $text .= "📅 " . date('Y/m/d H:i', strtotime($user['created_at'])) . "\n\n";
    }
    sendTelegramMessage($botToken, $chatId, $text);
}

if (isset($update['message'])) {
    $message = $update['message'];
    $chatId = $message['chat']['id'];
    $userId = (string)$chatId;
    $text = isset($message['text']) ? trim($message['text']) : '';
    
    if ($userId !== $adminId) {
        sendTelegramMessage($botToken, $chatId, "شما دسترسی لازم را ندارید");
        http_response_code(200);
        exit;
    }
    
    if ($text === '') {
        http_response_code(200);
        exit;
    }
    
    $state = getAdminState($chatId);
    
    if (in_array($text, ['/start', '/menu', 'بازگشت به منوی اصلی'])) {
        sendMainMenu($botToken, $chatId);
        http_response_code(200);
        exit;
    }
    
    if ($text === '⬅️ بازگشت') {
        sendMainMenu($botToken, $chatId);
        http_response_code(200);
        exit;
    }
    
    if (!empty($state['pending_action'])) {
        if (in_array($text, ['لغو', 'انصراف'])) {
            updateAdminState($chatId, ['pending_action' => null, 'pending_data' => null]);
            if (($state['current_menu'] ?? '') === 'user_management') {
                sendUserManagementMenu($botToken, $chatId);
            } else {
                sendMainMenu($botToken, $chatId);
            }
            http_response_code(200);
            exit;
        }
        
        switch ($state['pending_action']) {
            case 'search_user':
                handleUserSearch($botToken, $chatId, $text);
                http_response_code(200);
                exit;
            case 'view_user':
                handleUserProfile($botToken, $chatId, $text);
                http_response_code(200);
                exit;
            case 'adjust_coins':
                handleAdjustCoins($botToken, $chatId, $text);
                http_response_code(200);
                exit;
            case 'toggle_user_status':
                handleToggleUserStatus($botToken, $chatId, $text);
                http_response_code(200);
                exit;
            default:
                updateAdminState($chatId, ['pending_action' => null, 'pending_data' => null]);
        }
    }
    
    switch ($text) {
        case '📊 آمار و گزارش‌ها':
            sendStatsMenu($botToken, $chatId);
            break;
        case '👥 مدیریت کاربران':
            sendUserManagementMenu($botToken, $chatId);
            break;
        case '📋 سفارشات در انتظار':
            $overview = getPendingOrdersOverview();
            sendTelegramMessage($botToken, $chatId, $overview['text'], $overview['keyboard']);
            break;
        case '📈 آمار کلی':
            sendOverallStats($botToken, $chatId);
            break;
        case '📅 آمار امروز':
            sendTodayStats($botToken, $chatId);
            break;
        case '📆 آمار هفتگی/ماهانه':
            sendWeeklyMonthlyStats($botToken, $chatId);
            break;
        case '🏆 محصولات پرفروش':
            sendTopProducts($botToken, $chatId);
            break;
        case '🔎 جستجوی کاربر':
            promptUserSearch($botToken, $chatId);
            break;
        case '👤 مشاهده پروفایل':
            promptUserProfile($botToken, $chatId);
            break;
        case '💰 مدیریت سکه':
            promptAdjustCoins($botToken, $chatId);
            break;
        case '🚫 مسدود/فعال‌سازی':
            promptToggleUserStatus($botToken, $chatId);
            break;
        case '📋 لیست کاربران':
            sendLatestUsersList($botToken, $chatId);
            break;
        default:
            sendTelegramMessage($botToken, $chatId, "❔ دستور نامعتبر است. برای نمایش منو «/menu» را ارسال کنید.");
            break;
    }
    
    http_response_code(200);
    exit;
}

if (isset($update['callback_query'])) {
    $callback = $update['callback_query'];
    $chatId = $callback['message']['chat']['id'];
    $userId = (string)$chatId;
    $data = $callback['data'];
    $messageId = $callback['message']['message_id'];
    $callbackQueryId = $callback['id'];
    
    if ($userId !== $adminId) {
        answerCallbackQuery($botToken, $callbackQueryId, "شما دسترسی لازم را ندارید");
        http_response_code(200);
        exit;
    }
    
    if ($data === 'list_orders') {
        $overview = getPendingOrdersOverview();
        if (!$overview['keyboard']) {
            answerCallbackQuery($botToken, $callbackQueryId, "سفارشی یافت نشد");
            editMessageText($botToken, $chatId, $messageId, $overview['text']);
        } else {
            answerCallbackQuery($botToken, $callbackQueryId);
            editMessageText($botToken, $chatId, $messageId, $overview['text'], $overview['keyboard']);
        }
    } elseif (strpos($data, 'view_order_') === 0) {
        $orderId = (int)str_replace('view_order_', '', $data);
        
        $stmt = $pdo->prepare("
            SELECT o.id, o.quantity, o.total_coins, o.status, o.created_at, o.telegram_link, o.coin_type,
                   u.username, u.full_name, u.email,
                   p.name as product_name, p.price_coins as product_price
            FROM orders o
            JOIN users u ON o.user_id = u.id
            JOIN products p ON o.product_id = p.id
            WHERE o.id = ?
        ");
        $stmt->execute([$orderId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$order) {
            answerCallbackQuery($botToken, $callbackQueryId, "سفارش یافت نشد");
            http_response_code(200);
            exit;
        }
        
        $statusText = $order['status'] === 'pending' ? '⏳ در انتظار' : ($order['status'] === 'completed' ? '✅ تکمیل شده' : '❌ لغو شده');
        $coinTypeText = $order['coin_type'] === 'free' ? '⭐ رایگان' : '💰 معمولی';
        
        $text = "📦 <b>جزئیات سفارش #{$order['id']}</b>\n\n";
        $text .= "👤 <b>اطلاعات کاربر:</b>\n";
        $text .= "نام: {$order['full_name']}\n";
        $text .= "نام کاربری: @{$order['username']}\n";
        $text .= "ایمیل: {$order['email']}\n\n";
        $text .= "📦 <b>اطلاعات محصول:</b>\n";
        $text .= "نام: {$order['product_name']}\n";
        $text .= "قیمت واحد: {$order['product_price']} سکه\n";
        $text .= "تعداد: {$order['quantity']}\n";
        $text .= "قیمت کل: {$order['total_coins']} سکه ({$coinTypeText})\n\n";
        $text .= "🔗 لینک تلگرام: {$order['telegram_link']}\n";
        $text .= "📅 تاریخ: " . date('Y/m/d H:i', strtotime($order['created_at'])) . "\n";
        $text .= "📊 وضعیت: {$statusText}\n";
        
        $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = 'orders_sent_to_smm'");
        $stmt->execute();
        $smmData = $stmt->fetchColumn();
        $sentToSmm = [];
        if ($smmData) {
            $sentToSmm = json_decode($smmData, true) ?: [];
        }
        $isSentToSmm = in_array($orderId, $sentToSmm);
        
        $keyboardButtons = [];
        if ($order['status'] === 'pending' && !$isSentToSmm) {
            $keyboardButtons[] = [
                ['text' => '❌ کنسل و ریفاند', 'callback_data' => "cancel_order_{$orderId}"],
                ['text' => '📤 ارسال به SMM', 'callback_data' => "send_to_smm_{$orderId}"]
            ];
            $keyboardButtons[] = [
                ['text' => '💸 ارسال به سرویس ارزان', 'callback_data' => "send_to_cheap_{$orderId}"]
            ];
        } elseif ($isSentToSmm) {
            $text .= "\n⚠️ این سفارش به SMM ارسال شده است.";
        }
        
        $keyboard = ['inline_keyboard' => $keyboardButtons];
        answerCallbackQuery($botToken, $callbackQueryId);
        editMessageText($botToken, $chatId, $messageId, $text, $keyboard);
    } elseif (strpos($data, 'cancel_order_') === 0) {
        $orderId = (int)str_replace('cancel_order_', '', $data);
        
        $stmt = $pdo->prepare("SELECT user_id, total_coins, coin_type, status FROM orders WHERE id = ?");
        $stmt->execute([$orderId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$order) {
            answerCallbackQuery($botToken, $callbackQueryId, "سفارش یافت نشد");
            http_response_code(200);
            exit;
        }
        
        if ($order['status'] !== 'pending') {
            answerCallbackQuery($botToken, $callbackQueryId, "این سفارش قابل کنسل نیست");
            http_response_code(200);
            exit;
        }
        
        $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = 'orders_sent_to_smm'");
        $stmt->execute();
        $smmData = $stmt->fetchColumn();
        $sentToSmm = [];
        if ($smmData) {
            $sentToSmm = json_decode($smmData, true) ?: [];
        }
        if (in_array($orderId, $sentToSmm)) {
            answerCallbackQuery($botToken, $callbackQueryId, "این سفارش به SMM ارسال شده و قابل کنسل نیست");
            http_response_code(200);
            exit;
        }
        
        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare("UPDATE orders SET status = 'cancelled' WHERE id = ?");
            $stmt->execute([$orderId]);
            
            $userId = $order['user_id'];
            $totalCoins = $order['total_coins'];
            $coinType = $order['coin_type'];
            
            if ($coinType === 'free') {
                $stmt = $pdo->prepare("UPDATE users SET free_coins = free_coins + ? WHERE id = ?");
            } else {
                $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
            }
            $stmt->execute([$totalCoins, $userId]);
            
            $stmt = $pdo->prepare("
                INSERT INTO transactions (user_id, type, amount, coin_type, description, created_at) 
                VALUES (?, 'refund', ?, ?, 'Order cancellation refund', NOW())
            ");
            $stmt->execute([$userId, $totalCoins, $coinType]);
            
            $pdo->commit();
            answerCallbackQuery($botToken, $callbackQueryId, "سفارش کنسل شد و سکه‌ها برگردانده شد");
            
            $text = "✅ سفارش #{$orderId} با موفقیت کنسل شد و {$totalCoins} سکه به کاربر برگردانده شد.";
            editMessageText($botToken, $chatId, $messageId, $text);

            $stmt = $pdo->prepare("
                SELECT o.id, o.total_coins, u.email, u.full_name, p.name AS product_name
                FROM orders o
                JOIN users u ON u.id = o.user_id
                JOIN products p ON p.id = o.product_id
                WHERE o.id = ?
            ");
            $stmt->execute([$orderId]);
            $emailRow = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($emailRow && !empty($emailRow['email'])) {
                try {
                    sendSystemEmail(
                        $pdo,
                        'order_cancelled',
                        $emailRow['email'],
                        [
                            'full_name' => $emailRow['full_name'],
                            'order_id' => $emailRow['id'],
                            'product_name' => $emailRow['product_name'],
                            'total_coins' => $emailRow['total_coins'],
                        ],
                        [
                            'triggered_by' => 'telegram_admin_cancel',
                            'context' => [
                                'order_id' => $orderId,
                                'source' => 'api/telegram/webhook.php',
                            ],
                        ]
                    );
                } catch (Exception $e) {
                    error_log('Telegram cancel order email: ' . $e->getMessage());
                }
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            answerCallbackQuery($botToken, $callbackQueryId, "خطا در کنسل کردن سفارش");
        }
    } elseif (strpos($data, 'send_to_smm_') === 0) {
        $orderId = (int)str_replace('send_to_smm_', '', $data);
        [$ok, $errorMessage, $meta] = sendOrderToSmmProvider($orderId, null);
        if (!$ok) {
            answerCallbackQuery($botToken, $callbackQueryId, $errorMessage);
            http_response_code(200);
            exit;
        }
        answerCallbackQuery($botToken, $callbackQueryId, "سفارش به SMM ارسال شد");
        $text = "📤 سفارش #{$orderId} به SMM ارسال شد.\n\n";
        $text .= "🧩 Service ID: {$meta['service_id']}\n";
        $text .= "🆔 Order ID در SMM: {$meta['smm_order_id']}\n";
        $text .= "⚠️ از این پس این سفارش فقط توسط SMM قابل کنسل است.";
        editMessageText($botToken, $chatId, $messageId, $text);
    } elseif (strpos($data, 'send_to_cheap_') === 0) {
        $orderId = (int)str_replace('send_to_cheap_', '', $data);
        [$ok, $errorMessage, $meta] = sendOrderToSmmProvider($orderId, 10978);
        if (!$ok) {
            answerCallbackQuery($botToken, $callbackQueryId, $errorMessage);
            http_response_code(200);
            exit;
        }
        answerCallbackQuery($botToken, $callbackQueryId, "سفارش به سرویس ارزان ارسال شد");
        $text = "💸 سفارش #{$orderId} به سرویس ارزان ارسال شد.\n\n";
        $text .= "🧩 Service ID: {$meta['service_id']}\n";
        $text .= "🆔 Order ID در SMM: {$meta['smm_order_id']}\n";
        $text .= "⚠️ از این پس این سفارش فقط توسط SMM قابل کنسل است.";
        editMessageText($botToken, $chatId, $messageId, $text);
    }
}

http_response_code(200);
?>

