<?php
if(($text == '📊 آمار ربات' || strpos($data, 'admin_stats:') === 0) && ($user->is_owner || $user->is_admin)) {
    $scope = 'all';

if(strpos($data, 'admin_stats:') === 0) {
        $scope = substr($data, strlen('admin_stats:'));
}

    $usersCond     = '';
    $ordersCond    = '';
    $coinsBuyCond  = "WHERE `status`='success'";
    $vipBuyCond    = "WHERE `status`='success'";
    $transfersCond = '';
    $joinsCond     = '';
    $leftCond      = '';
    $refCond       = '';

if($scope == 'today') {
        $usersCond     = "WHERE DATE(`created_at`) = CURDATE()";
        $ordersCond    = "WHERE DATE(`created_at`) = CURDATE()";
        $coinsBuyCond  = "WHERE DATE(`created_at`) = CURDATE() AND `status`='success'";
        $vipBuyCond    = "WHERE DATE(`created_at`) = CURDATE() AND `status`='success'";
        $transfersCond = "WHERE DATE(`created_at`) = CURDATE()";
        $joinsCond     = "WHERE DATE(`joined_at`) = CURDATE()";
        $leftCond      = "WHERE DATE(`left_at`) = CURDATE()";
        $refCond       = "WHERE DATE(`created_at`) = CURDATE()";
} elseif ($scope == 'week') {
        $usersCond     = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        $ordersCond    = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        $coinsBuyCond  = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY) AND `status`='success'";
        $vipBuyCond    = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY) AND `status`='success'";
        $transfersCond = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        $joinsCond     = "WHERE `joined_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        $leftCond      = "WHERE `left_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        $refCond       = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
} elseif ($scope == 'month') {
        $usersCond     = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
        $ordersCond    = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
        $coinsBuyCond  = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND `status`='success'";
        $vipBuyCond    = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND `status`='success'";
        $transfersCond = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
        $joinsCond     = "WHERE `joined_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
        $leftCond      = "WHERE `left_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
        $refCond       = "WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
}


if($text == '📊 آمار ربات') {
        $progress = "⏳ درحال دریافت آمار... 0%";
        $resp     = sendMessage($chat_id, $progress);
        $mid      = isset($resp->result->message_id) ? $resp->result->message_id : null;
        editMessage($chat_id, $mid, "⏳ درحال دریافت آمار... 35%");
}

    $stmt       = $pdo->query("SELECT COUNT(*) FROM `users`");
    $usersAll   = intval($stmt->fetchColumn());
    $stmt       = $pdo->query("SELECT COUNT(*) FROM `users` $usersCond");
    $usersScope = intval($stmt->fetchColumn());
    $stmt       = $pdo->query("SELECT COUNT(*) FROM `users` WHERE `is_vip`=1 AND `vip_expire`>NOW()");
    $vipActive  = intval($stmt->fetchColumn());
    $stmt               = $pdo->query("SELECT COUNT(*) FROM `orders`");
    $ordersAll          = intval($stmt->fetchColumn());
    $stmt               = $pdo->query("SELECT COUNT(*) FROM `orders` $ordersCond");
    $ordersScope        = intval($stmt->fetchColumn());
    $stmt               = $pdo->query("SELECT COUNT(*) FROM `orders` WHERE `status`='running'");
    $ordersRunning      = intval($stmt->fetchColumn());
    $stmt               = $pdo->query("SELECT COUNT(*) FROM `orders` WHERE `status`='completed'");
    $ordersCompleted    = intval($stmt->fetchColumn());
    $stmt               = $pdo->query("SELECT COUNT(*) FROM `orders` WHERE `status`='cancelled'");
    $ordersCancelled    = intval($stmt->fetchColumn());
    $stmt               = $pdo->query("SELECT SUM(`total_cost`) FROM `orders`");
    $ordersCostAll      = intval($stmt->fetchColumn() ?? 0);
    $stmt               = $pdo->query("SELECT SUM(`total_cost`) FROM `orders` $ordersCond");
    $ordersCostScope    = intval($stmt->fetchColumn() ?? 0);
    $stmt               = $pdo->query("SELECT AVG(`members_count`) FROM `orders`");
    $avgMembersPerOrder = floatval($stmt->fetchColumn() ?? 0);
    $stmt               = $pdo->query("SELECT SUM(`members_done`), SUM(`members_count`) FROM `orders`");
    $row                = $stmt->fetch();
    $progressAll        = ($row && $row->{"SUM(`members_count`)"} > 0) ? round(($row->{"SUM(`members_done`)"} / $row->{"SUM(`members_count`)"}) * 100, 1) : 0;
    $totalOrdersForRate = max(1, ($ordersRunning + $ordersCompleted + $ordersCancelled));
    $completionRate     = round(($ordersCompleted / $totalOrdersForRate) * 100, 1);
    $cancelRate         = round(($ordersCancelled / $totalOrdersForRate) * 100, 1);
    $stmt            = $pdo->query("SELECT COUNT(*) FROM `coin_transactions` WHERE `status`='success'");
    $coinBuyCountAll = intval($stmt->fetchColumn());
    $stmt            = $pdo->query("SELECT SUM(`price_toman`) FROM `coin_transactions` $coinsBuyCond");
    $coinBuySumScope   = intval($stmt->fetchColumn() ?? 0);
    $stmt           = $pdo->query("SELECT COUNT(*) FROM `vip_transactions` WHERE `status`='success'");
    $vipBuyCountAll = intval($stmt->fetchColumn());
    $stmt           = $pdo->query("SELECT SUM(`price_toman`) FROM `vip_transactions` $vipBuyCond");
    $vipBuySumScope   = intval($stmt->fetchColumn() ?? 0);
    $stmt            = $pdo->query("SELECT SUM(`coins`) FROM `users`");
    $coinsTotalUsers = intval($stmt->fetchColumn() ?? 0);
    $avgCoinsPerUser = ($usersAll > 0) ? round($coinsTotalUsers / $usersAll, 1) : 0;
    $stmt            = $pdo->query("SELECT COUNT(*) FROM `coin_transfers`");
    $transCountAll   = intval($stmt->fetchColumn());

if($transfersCond == '') {
        $stmt            = $pdo->query("SELECT COUNT(*) FROM `coin_transfers`");
        $transCountScope = intval($stmt->fetchColumn());
} else {
        $transCountScope = 0;
}

    $stmt        = $pdo->query("SELECT SUM(`coins`) FROM `coin_transfers`");
    $transSumAll = intval($stmt->fetchColumn() ?? 0);

if($transfersCond == '') {
        $stmt          = $pdo->query("SELECT SUM(`coins`) FROM `coin_transfers`");
        $transSumScope = intval($stmt->fetchColumn() ?? 0);
} else {
        $transSumScope = 0;
}

    $stmt             = $pdo->query("SELECT COUNT(*) FROM `memberships` WHERE `status`='active'");
    $joinsAll         = intval($stmt->fetchColumn());
    $stmt             = $pdo->query("SELECT COUNT(*) FROM `memberships` $joinsCond");
    $joinsScope       = intval($stmt->fetchColumn());
    $stmt             = $pdo->query("SELECT COUNT(*) FROM `memberships` WHERE `status`='left_refunded'");
    $leftRefundAll    = intval($stmt->fetchColumn());
    $stmt             = $pdo->query("SELECT COUNT(*) FROM `memberships` WHERE `status`='left_refunded' " . ($leftCond ? str_replace('WHERE', 'AND', $leftCond) : ''));
    $leftRefundScope  = intval($stmt->fetchColumn());
    $stmt             = $pdo->query("SELECT COUNT(*) FROM `memberships` WHERE `status`='left_expired'");
    $leftExpiredAll   = intval($stmt->fetchColumn());
    $stmt             = $pdo->query("SELECT COUNT(*) FROM `memberships` WHERE `status`='left_expired' " . ($leftCond ? str_replace('WHERE', 'AND', $leftCond) : ''));
    $leftExpiredScope = intval($stmt->fetchColumn());
    $stmt             = $pdo->query("SELECT SUM(`coins_received`) FROM `memberships` WHERE `status`='active'");
    $memIncomeAll     = intval($stmt->fetchColumn() ?? 0);
    $stmt             = $pdo->query("SELECT SUM(`coins_received`) FROM `memberships` WHERE `status`='active' " . ($joinsCond ? str_replace('WHERE', 'AND', $joinsCond) : ''));
    $memIncomeScope   = intval($stmt->fetchColumn() ?? 0);
    $stmt             = $pdo->query("SELECT SUM(`coins_received`) FROM `memberships` WHERE `status`='left_refunded'");
    $penaltyAll       = intval($stmt->fetchColumn() ?? 0);
    $stmt             = $pdo->query("SELECT SUM(`coins_received`) FROM `memberships` WHERE `status`='left_refunded' " . ($leftCond ? str_replace('WHERE', 'AND', $leftCond) : ''));
    $penaltyScope     = intval($stmt->fetchColumn() ?? 0);
    $stmt             = $pdo->query("SELECT COUNT(*) as c, SUM(`reward_coins`) as s FROM `referrals`");
    $row              = $stmt->fetch();
    $refCountAll   = intval($row->c ?? 0);
    $refSumAll     = intval($row->s ?? 0);
    $stmt          = $pdo->query("SELECT COUNT(*) as c, SUM(`reward_coins`) as s FROM `referrals` $refCond");
    $row           = $stmt->fetch();
    $refCountScope = intval($row->c ?? 0);
    $refSumScope   = intval($row->s ?? 0);
    $vipPercent = ($usersAll > 0) ? round(($vipActive / $usersAll) * 100, 1) : 0;
    $leftRate   = ($joinsAll > 0) ? round((($leftRefundAll + $leftExpiredAll) / $joinsAll) * 100, 1) : 0;

if(isset($mid)) {
        editMessage($chat_id, $mid, "⏳ درحال دریافت آمار... 70%");
}

    $stmt     = $pdo->query("SELECT COUNT(*) FROM ( 
        SELECT user_id FROM `orders` WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        UNION 
        SELECT user_id FROM `memberships` WHERE `joined_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        UNION 
        SELECT user_id FROM `coin_transactions` WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        UNION 
        SELECT user_id FROM `vip_transactions` WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    ) u");
    $active7d = intval($stmt->fetchColumn());
    $stmt      = $pdo->query("SELECT COUNT(*) FROM ( 
        SELECT user_id FROM `orders` WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        UNION 
        SELECT user_id FROM `memberships` WHERE `joined_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        UNION 
        SELECT user_id FROM `coin_transactions` WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        UNION 
        SELECT user_id FROM `vip_transactions` WHERE `created_at` >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ) u");
    $active30d = intval($stmt->fetchColumn());
    $threshold = time() - 300;
    $stmt      = $pdo->prepare("SELECT COUNT(*) FROM `spam_check` WHERE `last_request` >= ?");
    $stmt->execute([$threshold]);
    $onlineNow = intval($stmt->fetchColumn());
    $vipOrders        = intval($pdo->query("SELECT COUNT(*) FROM `orders` WHERE `is_vip`=1")->fetchColumn());
    $normalOrders     = max(0, $ordersAll - $vipOrders);
    $boostedOrders    = intval($pdo->query("SELECT COUNT(*) FROM `orders` WHERE `boost_manual` > 0")->fetchColumn());
    $nonBoostedOrders = max(0, $ordersAll - $boostedOrders);
    $penaltyOrders    = intval($pdo->query("SELECT COUNT(DISTINCT `order_id`) FROM `memberships` WHERE `status`='left_refunded'")->fetchColumn());
    $stmt             = $pdo->query("SELECT AVG(TIMESTAMPDIFF(MINUTE, o.created_at, mj.last_join)) 
        FROM `orders` o 
        JOIN (SELECT `order_id`, MAX(`joined_at`) as last_join FROM `memberships` GROUP BY `order_id`) mj 
        ON mj.order_id = o.order_id 
        WHERE o.`status`='completed'");
    $avgCompleteMin   = floatval($stmt->fetchColumn() ?? 0);
    $avgCompleteHours = round($avgCompleteMin / 60, 2);
    $succCoin = intval($pdo->query("SELECT COUNT(*) FROM `coin_transactions` WHERE `status`='success'")->fetchColumn());
    $pendCoin = intval($pdo->query("SELECT COUNT(*) FROM `coin_transactions` WHERE `status`='pending'")->fetchColumn());
    $failCoin = intval($pdo->query("SELECT COUNT(*) FROM `coin_transactions` WHERE `status`='failed'")->fetchColumn());
    $succVip  = intval($pdo->query("SELECT COUNT(*) FROM `vip_transactions` WHERE `status`='success'")->fetchColumn());
    $pendVip  = intval($pdo->query("SELECT COUNT(*) FROM `vip_transactions` WHERE `status`='pending'")->fetchColumn());
    $failVip  = intval($pdo->query("SELECT COUNT(*) FROM `vip_transactions` WHERE `status`='failed'")->fetchColumn());
    $succAll  = $succCoin + $succVip;
    $pendAll  = $pendCoin + $pendVip;
    $failAll  = $failCoin + $failVip;
    $sumPaidCoin = intval($pdo->query("SELECT SUM(`price_toman`) FROM `coin_transactions` $coinsBuyCond")->fetchColumn() ?? 0);
    $sumPaidVip  = intval($pdo->query("SELECT SUM(`price_toman`) FROM `vip_transactions` $vipBuyCond")->fetchColumn() ?? 0);
    $sumPaidAll  = $sumPaidCoin + $sumPaidVip;
    $stmt           = $pdo->query("SELECT COUNT(*) FROM `referrals`");
    $refTotal       = intval($stmt->fetchColumn());
    $stmt           = $pdo->query("SELECT COUNT(*) FROM (SELECT DISTINCT r.invited_id FROM `referrals` r JOIN `orders` o ON o.user_id = r.invited_id UNION SELECT DISTINCT r.invited_id FROM `referrals` r JOIN `memberships` m ON m.user_id = r.invited_id) t");
    $refActiveUsers = intval($stmt->fetchColumn());
    $stmt       = $pdo->query("SELECT COUNT(*) FROM `reports`");
    $newReports = intval($stmt->fetchColumn());
    $stmt          = $pdo->query("SELECT `user_id`, COUNT(*) as c FROM `memberships` WHERE `status`='left_refunded' GROUP BY `user_id` ORDER BY c DESC LIMIT 5");
    $riskUsers     = $stmt->fetchAll();
    $riskUsersList = '';

if($riskUsers) {

foreach($riskUsers as $RU) {
            $riskUsersList .= ($riskUsersList ? "\n" : "") . $RU->user_id . " (" . number_format($RU->c) . ")";
}

} else {
        $riskUsersList = "\nبدون اطلاعات!";
}

    $title = "آمار ربات";

if($scope == 'today')
        $title = "آمار امروز";
    elseif ($scope == 'week')
        $title = "آمار هفتگی";
    elseif ($scope == 'month')
        $title = "آمار ماهانه";
    $msg = "📊 $title\n\n" .
        "👥 *کاربران*\n" .
        "▫️ کل کاربران: *" . number_format($usersAll) . " نفر*\n" .
        "▫️ ورودی جدید: *" . number_format($usersScope) . " نفر*\n" .
        "▫️ آنلاین: *" . number_format($onlineNow) . " نفر*\n" .
        "▫️ ویژه: *" . number_format($vipActive) . " نفر*\n\n" .
        "🛍 *سفارشات*\n" .
        "▫️ کل سفارشات: *" . number_format($ordersAll) . "*\n" .
        "▫️ در حال اجرا: *" . number_format($ordersRunning) . "*\n" .
        "▫️ تکمیل شده: *" . number_format($ordersCompleted) . "*\n\n" .
        "💰 *مالی*\n" .
        "▫️ فروش سکه: *" . number_format($sumPaidCoin) . " تومان*\n" .
        "▫️ فروش اشتراک: *" . number_format($sumPaidVip) . " تومان*\n" .
        "▫️ کل درآمد: *" . number_format($sumPaidAll) . " تومان*\n\n" .
        "💎 *وضعیت سکه‌ها*\n" .
        "▫️ موجودی کاربران: *" . number_format($coinsTotalUsers) . "*\n" .
        "▫️ جریمه‌ها: *" . number_format($penaltyAll) . "*\n\n" .
        "🎫 *پشتیبانی*\n" .
        "▫️ گزارشات جدید: *" . number_format($newReports) . "*";
    $keyboard = json_encode([
        "inline_keyboard" => [
            [
                ['text' => ($scope == 'today' ? '🔘 ' : '') . 'امروز', 'callback_data' => 'admin_stats:today'],
                ['text' => ($scope == 'week' ? '🔘 ' : '') . 'هفته', 'callback_data' => 'admin_stats:week'],
                ['text' => ($scope == 'month' ? '🔘 ' : '') . 'ماه', 'callback_data' => 'admin_stats:month']
            ]
        ]
    ]);

if($text == '📊 آمار ربات') {
        editMessage($chat_id, $mid, "⏳ درحال دریافت آمار... 100%");
        editMessage($chat_id, $mid, $msg, $keyboard);
} else {
        editMessage($chat_id, $message_id, $msg, $keyboard);
}

    die;
}

