<?php
/**
 * سیستم گزارش‌دهی پیشرفته برای ادمین
 * داشبورد کامل با آمار و تحلیل
 */

include_once 'config.php';

// ===============================
// داشبورد اصلی آمار
// ===============================
if($data == 'advancedReports' && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    
    $today_start = strtotime('today');
    $today_end = strtotime('tomorrow') - 1;
    $week_start = strtotime('-7 days');
    $month_start = strtotime('-30 days');
    
    // درآمد امروز
    $stmt = $connection->prepare("SELECT SUM(price) as total FROM `pays` WHERE `state` = 'completed' AND `request_date` >= ? AND `request_date` <= ?");
    $stmt->bind_param("ii", $today_start, $today_end);
    $stmt->execute();
    $today_income = $stmt->get_result()->fetch_assoc()['total'] ?? 0;
    $stmt->close();
    
    // درآمد هفته
    $stmt = $connection->prepare("SELECT SUM(price) as total FROM `pays` WHERE `state` = 'completed' AND `request_date` >= ?");
    $stmt->bind_param("i", $week_start);
    $stmt->execute();
    $week_income = $stmt->get_result()->fetch_assoc()['total'] ?? 0;
    $stmt->close();
    
    // درآمد ماه
    $stmt = $connection->prepare("SELECT SUM(price) as total FROM `pays` WHERE `state` = 'completed' AND `request_date` >= ?");
    $stmt->bind_param("i", $month_start);
    $stmt->execute();
    $month_income = $stmt->get_result()->fetch_assoc()['total'] ?? 0;
    $stmt->close();
    
    // کاربران جدید امروز
    $stmt = $connection->prepare("SELECT COUNT(*) as count FROM `users` WHERE `date` >= ? AND `date` <= ?");
    $stmt->bind_param("ii", $today_start, $today_end);
    $stmt->execute();
    $new_users_today = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // تعداد سفارشات امروز
    $stmt = $connection->prepare("SELECT COUNT(*) as count FROM `pays` WHERE `request_date` >= ? AND `request_date` <= ?");
    $stmt->bind_param("ii", $today_start, $today_end);
    $stmt->execute();
    $orders_today = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // سفارشات در انتظار
    $stmt = $connection->prepare("SELECT COUNT(*) as count FROM `pays` WHERE `state` = 'pending'");
    $stmt->execute();
    $pending_orders = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // تیکت‌های باز
    $stmt = $connection->prepare("SELECT COUNT(*) as count FROM `chats` WHERE `state` = 1");
    $stmt->execute();
    $open_tickets = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // محبوب‌ترین پلن این ماه
    $stmt = $connection->prepare("
        SELECT p.description, COUNT(*) as count 
        FROM `pays` p
        WHERE p.state = 'completed' 
        AND p.request_date >= ?
        GROUP BY p.description 
        ORDER BY count DESC 
        LIMIT 1
    ");
    $stmt->bind_param("i", $month_start);
    $stmt->execute();
    $popular_plan = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    $popular_plan_name = $popular_plan['description'] ?? 'هنوز خریدی نیست';
    $popular_plan_count = $popular_plan['count'] ?? 0;
    
    // نرخ تبدیل (Conversion Rate)
    $stmt = $connection->prepare("SELECT COUNT(*) as count FROM `users` WHERE `date` >= ?");
    $stmt->bind_param("i", $month_start);
    $stmt->execute();
    $total_users_month = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    $stmt = $connection->prepare("
        SELECT COUNT(DISTINCT user_id) as count 
        FROM `pays` 
        WHERE `state` = 'completed' 
        AND `request_date` >= ?
    ");
    $stmt->bind_param("i", $month_start);
    $stmt->execute();
    $buyers_month = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    $conversion_rate = $total_users_month > 0 ? round(($buyers_month / $total_users_month) * 100, 1) : 0;
    
    $message = "📊 <b>داشبورد آمار پیشرفته</b>

━━━━━━━━━━━━━━━━━━━━━━
💰 <b>درآمد</b>
━━━━━━━━━━━━━━━━━━━━━━

📅 امروز: <code>" . number_format($today_income) . "</code> تومان
📅 هفته اخیر: <code>" . number_format($week_income) . "</code> تومان
📅 ماه اخیر: <code>" . number_format($month_income) . "</code> تومان

━━━━━━━━━━━━━━━━━━━━━━
👥 <b>کاربران</b>
━━━━━━━━━━━━━━━━━━━━━━

🆕 کاربران جدید امروز: <b>$new_users_today</b>
🛍 سفارشات امروز: <b>$orders_today</b>
⏳ سفارشات در انتظر: <b>$pending_orders</b>
🎫 تیکت‌های باز: <b>$open_tickets</b>

━━━━━━━━━━━━━━━━━━━━━━
📈 <b>تحلیل ماه اخیر</b>
━━━━━━━━━━━━━━━━━━━━━━

🔥 محبوب‌ترین پلن:
   $popular_plan_name ($popular_plan_count فروش)

📊 نرخ تبدیل: <b>{$conversion_rate}%</b>
   ($buyers_month خریدار از $total_users_month کاربر)

━━━━━━━━━━━━━━━━━━━━━━

🔄 آخرین بروزرسانی: " . jdate('Y/m/d H:i');
    
    editText($message_id, $message, json_encode([
        'inline_keyboard' => [
            [['text' => '📊 نمودار فروش', 'callback_data' => 'salesChart']],
            [['text' => '👥 تحلیل کاربران', 'callback_data' => 'userAnalysis']],
            [['text' => '💳 تحلیل پرداخت‌ها', 'callback_data' => 'paymentAnalysis']],
            [['text' => '🎁 عملکرد کدهای تخفیف', 'callback_data' => 'discountPerformance']],
            [['text' => '🔄 بروزرسانی', 'callback_data' => 'advancedReports']],
            [['text' => '🔙 بازگشت', 'callback_data' => 'managePanel']]
        ]
    ]), 'HTML');
    exit;
}

// ===============================
// نمودار فروش
// ===============================
if($data == 'salesChart' && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    
    $chart_data = [];
    
    for($i = 6; $i >= 0; $i--) {
        $day_start = strtotime("-$i days midnight");
        $day_end = strtotime("-$i days midnight") + 86400 - 1;
        
        $stmt = $connection->prepare("
            SELECT COUNT(*) as count, SUM(price) as total 
            FROM `pays` 
            WHERE `state` = 'completed' 
            AND `request_date` >= ? 
            AND `request_date` <= ?
        ");
        $stmt->bind_param("ii", $day_start, $day_end);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        $chart_data[] = [
            'date' => jdate('m/d', $day_start),
            'count' => $result['count'],
            'total' => $result['total'] ?? 0
        ];
    }
    
    $message = "📊 <b>نمودار فروش 7 روز اخیر</b>\n\n";
    
    foreach($chart_data as $data_point) {
        $bar_length = min(20, ceil($data_point['count'] / 2));
        $bar = str_repeat('▓', $bar_length) . str_repeat('░', 20 - $bar_length);
        
        $message .= "📅 {$data_point['date']}\n";
        $message .= "   $bar\n";
        $message .= "   🛍 {$data_point['count']} سفارش - 💰 " . number_format($data_point['total']) . " تومان\n\n";
    }
    
    editText($message_id, $message, json_encode([
        'inline_keyboard' => [
            [['text' => '🔙 بازگشت به داشبورد', 'callback_data' => 'advancedReports']]
        ]
    ]), 'HTML');
    exit;
}

// ===============================
// تحلیل کاربران
// ===============================
if($data == 'userAnalysis' && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    
    // کل کاربران
    $stmt = $connection->prepare("SELECT COUNT(*) as count FROM `users`");
    $stmt->execute();
    $total_users = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // کاربران فعال (خرید داشته‌اند)
    $stmt = $connection->prepare("SELECT COUNT(DISTINCT user_id) as count FROM `pays` WHERE `state` = 'completed'");
    $stmt->execute();
    $active_users = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // کاربران VIP (دارای سرویس فعال)
    $now = time();
    $stmt = $connection->prepare("SELECT COUNT(DISTINCT userid) as count FROM `orders_list` WHERE `status` = 1 AND `expire_date` > ?");
    $stmt->bind_param("i", $now);
    $stmt->execute();
    $vip_users = $stmt->get_result()->fetch_assoc()['count'];
    $stmt->close();
    
    // میانگین خرید هر کاربر
    $stmt = $connection->prepare("
        SELECT AVG(order_count) as avg_orders
        FROM (
            SELECT user_id, COUNT(*) as order_count 
            FROM `pays` 
            WHERE `state` = 'completed' 
            GROUP BY user_id
        ) as user_orders
    ");
    $stmt->execute();
    $avg_orders = round($stmt->get_result()->fetch_assoc()['avg_orders'] ?? 0, 1);
    $stmt->close();
    
    // میانگین ارزش مشتری (CLTV)
    $stmt = $connection->prepare("
        SELECT AVG(total_spent) as avg_cltv
        FROM (
            SELECT user_id, SUM(price) as total_spent 
            FROM `pays` 
            WHERE `state` = 'completed' 
            GROUP BY user_id
        ) as user_spending
    ");
    $stmt->execute();
    $avg_cltv = round($stmt->get_result()->fetch_assoc()['avg_cltv'] ?? 0);
    $stmt->close();
    
    // بهترین مشتریان
    $stmt = $connection->prepare("
        SELECT p.user_id, u.name, SUM(p.price) as total_spent, COUNT(*) as order_count
        FROM `pays` p
        JOIN `users` u ON p.user_id = u.userid
        WHERE p.state = 'completed'
        GROUP BY p.user_id
        ORDER BY total_spent DESC
        LIMIT 5
    ");
    $stmt->execute();
    $top_customers = $stmt->get_result();
    $stmt->close();
    
    $message = "👥 <b>تحلیل کاربران</b>

━━━━━━━━━━━━━━━━━━━━━━
📊 <b>آمار کلی</b>
━━━━━━━━━━━━━━━━━━━━━━

👤 کل کاربران: <b>$total_users</b>
✅ کاربران فعال: <b>$active_users</b> (" . round(($active_users/$total_users)*100, 1) . "%)
💎 کاربران VIP: <b>$vip_users</b>

━━━━━━━━━━━━━━━━━━━━━━
💰 <b>تحلیل مالی</b>
━━━━━━━━━━━━━━━━━━━━━━

🛍 میانگین خرید: <b>$avg_orders</b> بار
💵 میانگین ارزش مشتری: <b>" . number_format($avg_cltv) . "</b> تومان

━━━━━━━━━━━━━━━━━━━━━━
🏆 <b>بهترین مشتریان</b>
━━━━━━━━━━━━━━━━━━━━━━

";
    
    $rank = 1;
    while($customer = $top_customers->fetch_assoc()) {
        $medals = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣'];
        $message .= $medals[$rank-1] . " {$customer['name']}\n";
        $message .= "   💰 " . number_format($customer['total_spent']) . " تومان";
        $message .= " | 🛍 {$customer['order_count']} سفارش\n\n";
        $rank++;
    }
    
    editText($message_id, $message, json_encode([
        'inline_keyboard' => [
            [['text' => '🔙 بازگشت به داشبورد', 'callback_data' => 'advancedReports']]
        ]
    ]), 'HTML');
    exit;
}

// ===============================
// عملکرد کدهای تخفیف
// ===============================
if($data == 'discountPerformance' && ($from_id == $admin || $userInfo['isAdmin'] == true)){
    
    $stmt = $connection->prepare("SELECT * FROM `discounts` WHERE `status` = 'active' ORDER BY `id` DESC");
    $stmt->execute();
    $discounts = $stmt->get_result();
    $stmt->close();
    
    $message = "🎁 <b>عملکرد کدهای تخفیف</b>\n\n";
    
    if($discounts->num_rows == 0) {
        $message .= "📭 هیچ کد تخفیف فعالی وجود ندارد.";
    } else {
        while($discount = $discounts->fetch_assoc()) {
            $used_count = $discount['used_count'];
            $max_uses = $discount['max_use'] > 0 ? $discount['max_use'] : '∞';
            
            $message .= "━━━━━━━━━━━━━━━━━━━━\n";
            $message .= "📝 <code>{$discount['code']}</code>\n";
            $message .= "💎 تخفیف: ";
            if($discount['type'] == 'fixed') {
                $message .= number_format($discount['amount']) . " تومان\n";
            } else {
                $message .= $discount['amount'] . "%\n";
            }
            $message .= "👥 استفاده: <b>$used_count</b> / $max_uses\n";
            
            if($discount['expire_date'] > 0) {
                $days_left = ceil(($discount['expire_date'] - time()) / 86400);
                $message .= "⏰ باقیمانده: $days_left روز\n";
            }
            $message .= "\n";
        }
    }
    
    editText($message_id, $message, json_encode([
        'inline_keyboard' => [
            [['text' => '➕ ایجاد کد جدید', 'callback_data' => 'createDiscount']],
            [['text' => '🔙 بازگشت به داشبورد', 'callback_data' => 'advancedReports']]
        ]
    ]), 'HTML');
    exit;
}
?>
