<?php
require_once 'config/database.php';
secureSessionStart();
requireLogin();

$conn = getConnection();
$message = '';
$message_type = '';

// Enable error reporting for debugging
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Get filter parameters
$date_range = isset($_GET['date_range']) ? $_GET['date_range'] : 'this_month';
$custom_from = isset($_GET['from_date']) ? $_GET['from_date'] : '';
$custom_to = isset($_GET['to_date']) ? $_GET['to_date'] : '';
$commission_type = isset($_GET['commission_type']) ? sanitize($conn, $_GET['commission_type']) : '';
$user_id_filter = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$level_filter = isset($_GET['level']) ? intval($_GET['level']) : 0;

// Set date range based on selection
$from_date = '';
$to_date = date('Y-m-d');

switch ($date_range) {
    case 'today':
        $from_date = date('Y-m-d');
        break;
    case 'yesterday':
        $from_date = date('Y-m-d', strtotime('-1 day'));
        $to_date = $from_date;
        break;
    case 'this_week':
        $from_date = date('Y-m-d', strtotime('monday this week'));
        break;
    case 'this_month':
        $from_date = date('Y-m-01');
        break;
    case 'last_month':
        $from_date = date('Y-m-01', strtotime('first day of last month'));
        $to_date = date('Y-m-t', strtotime('last day of last month'));
        break;
    case 'this_quarter':
        $quarter = ceil(date('n') / 3);
        $from_date = date('Y-' . (($quarter - 1) * 3 + 1) . '-01');
        break;
    case 'this_year':
        $from_date = date('Y-01-01');
        break;
    case 'custom':
        if ($custom_from) $from_date = $custom_from;
        if ($custom_to) $to_date = $custom_to;
        break;
}

// DEBUG: First, let's see what income types exist in your database
$debug_types = mysqli_query($conn, "SELECT DISTINCT income_type FROM income_history WHERE income_type IS NOT NULL");
echo "<!-- DEBUG: Available income types: ";
while ($type = mysqli_fetch_assoc($debug_types)) {
    echo $type['income_type'] . " ";
}
echo " -->\n";

// DEBUG: Check date range of data
$debug_dates = mysqli_query($conn, "SELECT MIN(created_at) as min_date, MAX(created_at) as max_date FROM income_history");
$date_range_info = mysqli_fetch_assoc($debug_dates);
echo "<!-- DEBUG: Data date range: " . $date_range_info['min_date'] . " to " . $date_range_info['max_date'] . " -->\n";
echo "<!-- DEBUG: Selected range: " . $from_date . " to " . $to_date . " -->\n";

// Build WHERE clause for commission data
$where = ["1=1"];

if ($from_date && $to_date) {
    // Handle different date formats - created_at might be string or datetime
    $where[] = "DATE(STR_TO_DATE(ih.created_at, '%Y-%m-%d %H:%i:%s')) BETWEEN '$from_date' AND '$to_date' 
                OR DATE(ih.created_at) BETWEEN '$from_date' AND '$to_date'";
}

if ($commission_type) {
    $where[] = "ih.income_type = '$commission_type'";
}

if ($user_id_filter > 0) {
    $where[] = "ih.user_id = $user_id_filter";
}

if ($level_filter > 0) {
    $where[] = "ih.level = $level_filter";
}

// Get actual income types from database for the filter
$available_types = [];
$type_query = "SELECT DISTINCT income_type FROM income_history WHERE income_type IS NOT NULL ORDER BY income_type";
$type_result = mysqli_query($conn, $type_query);
while ($row = mysqli_fetch_assoc($type_result)) {
    $available_types[] = $row['income_type'];
}

// Build the WHERE clause with actual types that exist
$type_list = "'" . implode("','", $available_types) . "'";
$where[] = "ih.income_type IN ($type_list)";

$where_clause = "WHERE " . implode(" AND ", $where);

// Get commission summary
$summary = [];

// First, let's get total count to see if any data exists
$count_query = "SELECT COUNT(*) as total FROM income_history ih $where_clause";
$count_result = mysqli_query($conn, $count_query);
$total_count = mysqli_fetch_assoc($count_result)['total'];
echo "<!-- DEBUG: Total records matching criteria: " . $total_count . " -->\n";

// Total commissions by type
$type_stats = [];
$query = "SELECT 
            ih.income_type,
            COUNT(*) as transaction_count,
            COALESCE(SUM(ih.amount), 0) as total_amount,
            COALESCE(AVG(ih.amount), 0) as average_amount
          FROM income_history ih
          $where_clause
          GROUP BY ih.income_type
          ORDER BY total_amount DESC";
$type_result = mysqli_query($conn, $query);

if (!$type_result) {
    echo "<!-- DEBUG: Query error: " . mysqli_error($conn) . " -->\n";
} else {
    while ($row = mysqli_fetch_assoc($type_result)) {
        $type_stats[] = $row;
        $summary['total_commission'] = ($summary['total_commission'] ?? 0) + $row['total_amount'];
        $summary['total_transactions'] = ($summary['total_transactions'] ?? 0) + $row['transaction_count'];
    }
}

// Level-wise commission breakdown
$level_stats = [];
$level_query = "SELECT 
                  ih.level,
                  COUNT(*) as count,
                  COALESCE(SUM(ih.amount), 0) as total
                FROM income_history ih
                WHERE ih.income_type = 'level_reward' AND ih.level IS NOT NULL
                " . ($from_date && $to_date ? "AND (DATE(STR_TO_DATE(ih.created_at, '%Y-%m-%d %H:%i:%s')) BETWEEN '$from_date' AND '$to_date' OR DATE(ih.created_at) BETWEEN '$from_date' AND '$to_date')" : "") . "
                GROUP BY ih.level
                ORDER BY ih.level";
$level_result = mysqli_query($conn, $level_query);
while ($row = mysqli_fetch_assoc($level_result)) {
    $level_stats[] = $row;
}

// Top earners (users with highest commissions)
$top_earners = [];
$earner_query = "SELECT 
                    ih.user_id,
                    u.name,
                    u.mobile,
                    COUNT(*) as transaction_count,
                    COALESCE(SUM(ih.amount), 0) as total_commission,
                    COALESCE(SUM(CASE WHEN ih.income_type = 'level_reward' THEN ih.amount ELSE 0 END), 0) as level_commission,
                    COALESCE(SUM(CASE WHEN ih.income_type = 'referral_bonus' THEN ih.amount ELSE 0 END), 0) as referral_commission,
                    COALESCE(SUM(CASE WHEN ih.income_type = 'pair_matching' THEN ih.amount ELSE 0 END), 0) as pair_commission
                  FROM income_history ih
                  LEFT JOIN users u ON ih.user_id = u.user_id
                  $where_clause
                  GROUP BY ih.user_id
                  ORDER BY total_commission DESC
                  LIMIT 20";
$earner_result = mysqli_query($conn, $earner_query);
while ($row = mysqli_fetch_assoc($earner_result)) {
    $top_earners[] = $row;
}

// Daily commission trend
$daily_trend = [];
$trend_query = "SELECT 
                  DATE(STR_TO_DATE(ih.created_at, '%Y-%m-%d %H:%i:%s')) as date,
                  COALESCE(SUM(CASE WHEN ih.income_type = 'level_reward' THEN ih.amount ELSE 0 END), 0) as level_amount,
                  COALESCE(SUM(CASE WHEN ih.income_type = 'referral_bonus' THEN ih.amount ELSE 0 END), 0) as referral_amount,
                  COALESCE(SUM(CASE WHEN ih.income_type = 'pair_matching' THEN ih.amount ELSE 0 END), 0) as pair_amount,
                  COUNT(*) as transaction_count
                FROM income_history ih
                WHERE DATE(STR_TO_DATE(ih.created_at, '%Y-%m-%d %H:%i:%s')) BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE()
                GROUP BY DATE(STR_TO_DATE(ih.created_at, '%Y-%m-%d %H:%i:%s'))
                ORDER BY date ASC";
$trend_result = mysqli_query($conn, $trend_query);
while ($row = mysqli_fetch_assoc($trend_result)) {
    $daily_trend[] = $row;
}

// Get all users for filter dropdown
$users = mysqli_query($conn, "SELECT user_id, name FROM users ORDER BY name LIMIT 1000");

// Get average commission metrics
$avg_query = "SELECT 
                COALESCE(AVG(amount), 0) as overall_avg,
                COALESCE(MAX(amount), 0) as max_commission,
                COALESCE(MIN(amount), 0) as min_commission
              FROM income_history ih
              $where_clause";
$avg_result = mysqli_query($conn, $avg_query);
$avg_metrics = mysqli_fetch_assoc($avg_result);

// If no data found, show debug info in the page
$no_data = empty($type_stats) && empty($level_stats) && empty($top_earners);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Commission Report - MLM System</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">
    
    <!-- Select2 -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <style>
        * {
            font-family: 'Inter', sans-serif;
        }
        
        .report-header {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            padding: 30px;
            border-radius: 20px;
            margin-bottom: 30px;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
        }
        
        .stat-card.total::before { background: linear-gradient(180deg, #4154f1, #6f42c1); }
        .stat-card.level::before { background: linear-gradient(180deg, #ffc107, #fd7e14); }
        .stat-card.referral::before { background: linear-gradient(180deg, #28a745, #20c997); }
        .stat-card.pair::before { background: linear-gradient(180deg, #17a2b8, #0dcaf0); }
        .stat-card.avg::before { background: linear-gradient(180deg, #dc3545, #fd7e14); }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.05);
        }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-bottom: 15px;
        }
        
        .stat-icon.total { background: rgba(65, 84, 241, 0.1); color: #4154f1; }
        .stat-icon.level { background: rgba(255, 193, 7, 0.1); color: #ffc107; }
        .stat-icon.referral { background: rgba(40, 167, 69, 0.1); color: #28a745; }
        .stat-icon.pair { background: rgba(23, 162, 184, 0.1); color: #17a2b8; }
        .stat-icon.avg { background: rgba(220, 53, 69, 0.1); color: #dc3545; }
        
        .stat-value {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 5px;
            color: #1a1a1a;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 14px;
            font-weight: 500;
        }
        
        .filter-card {
            background: white;
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .chart-container {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .chart-box {
            position: relative;
            height: 300px;
            width: 100%;
        }
        
        .table-container {
            background: white;
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .commission-badge {
            padding: 6px 12px;
            border-radius: 30px;
            font-weight: 500;
            font-size: 12px;
        }
        
        .commission-badge.level {
            background: rgba(255, 193, 7, 0.15);
            color: #856404;
        }
        
        .commission-badge.referral {
            background: rgba(40, 167, 69, 0.15);
            color: #28a745;
        }
        
        .commission-badge.pair {
            background: rgba(23, 162, 184, 0.15);
            color: #0c5460;
        }
        
        .commission-badge.spill {
            background: rgba(111, 66, 193, 0.15);
            color: #563d7c;
        }
        
        .commission-badge.direct {
            background: rgba(255, 193, 7, 0.15);
            color: #856404;
        }
        
        .level-box {
            display: inline-block;
            width: 30px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border-radius: 8px;
            font-weight: 600;
            font-size: 14px;
            background: #f8f9fa;
        }
        
        .level-1 { background: rgba(255, 193, 7, 0.2); color: #856404; }
        .level-2 { background: rgba(23, 162, 184, 0.2); color: #0c5460; }
        .level-3 { background: rgba(40, 167, 69, 0.2); color: #155724; }
        .level-4 { background: rgba(111, 66, 193, 0.2); color: #563d7c; }
        .level-5 { background: rgba(220, 53, 69, 0.2); color: #721c24; }
        
        .progress-commission {
            height: 8px;
            border-radius: 4px;
        }
        
        .debug-info {
            background: #f8f9fa;
            border-left: 4px solid #17a2b8;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
            font-family: monospace;
            font-size: 12px;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        
        .empty-state i {
            font-size: 60px;
            color: #dee2e6;
            margin-bottom: 20px;
        }
        
        .export-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            z-index: 1000;
            width: 60px;
            height: 60px;
            border-radius: 30px;
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            box-shadow: 0 4px 20px rgba(40, 167, 69, 0.3);
            cursor: pointer;
            transition: all 0.3s;
            border: none;
        }
        
        .export-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 25px rgba(40, 167, 69, 0.4);
        }
        
        .export-menu {
            position: fixed;
            bottom: 100px;
            right: 30px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            padding: 10px 0;
            display: none;
            z-index: 999;
        }
        
        .export-menu.show {
            display: block;
        }
        
        .export-menu a {
            display: block;
            padding: 10px 20px;
            color: #333;
            text-decoration: none;
            transition: all 0.2s;
        }
        
        .export-menu a:hover {
            background: #f8f9fa;
            color: #28a745;
        }
        
        .commission-summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 16px;
            margin-bottom: 30px;
        }
        
        .summary-stat {
            text-align: center;
            padding: 15px;
        }
        
        .summary-stat .value {
            font-size: 32px;
            font-weight: 700;
        }
        
        .summary-stat .label {
            font-size: 14px;
            opacity: 0.9;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    <?php include 'includes/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>Commission Report</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item active">Commission Report</li>
                </ol>
            </nav>
        </div>

        <section class="section">
            <!-- Debug Info (remove in production) -->
            <div class="debug-info">
                <strong>Debug Information:</strong><br>
                Available income types: <?php echo implode(', ', $available_types); ?><br>
                Data date range: <?php echo $date_range_info['min_date'] ?? 'N/A'; ?> to <?php echo $date_range_info['max_date'] ?? 'N/A'; ?><br>
                Selected range: <?php echo $from_date ?: 'Start'; ?> to <?php echo $to_date ?: 'Now'; ?><br>
                Records found: <?php echo $total_count; ?><br>
                Commission types with data: <?php echo count($type_stats); ?>
            </div>
            
            <!-- Report Header -->
            <div class="report-header">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h2><i class="fas fa-hand-holding-usd me-3"></i>Commission Analytics</h2>
                        <p class="mb-0 opacity-75">Detailed commission breakdown for period: 
                            <strong><?php echo $from_date ? date('d M Y', strtotime($from_date)) : 'Start'; ?> - <?php echo $to_date ? date('d M Y', strtotime($to_date)) : 'Now'; ?></strong>
                        </p>
                    </div>
                    <div class="col-md-4 text-end">
                        <div class="btn-group">
                            <button class="btn btn-light btn-sm" onclick="window.location.href='?date_range=today'">Today</button>
                            <button class="btn btn-light btn-sm" onclick="window.location.href='?date_range=this_week'">This Week</button>
                            <button class="btn btn-light btn-sm" onclick="window.location.href='?date_range=this_month'">This Month</button>
                            <button class="btn btn-light btn-sm" onclick="window.location.href='?date_range=this_year'">This Year</button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Commission Summary Cards -->
            <div class="commission-summary-card">
                <div class="row">
                    <div class="col-md-3 summary-stat">
                        <div class="value">₹<?php echo number_format($summary['total_commission'] ?? 0, 2); ?></div>
                        <div class="label">Total Commissions</div>
                    </div>
                    <div class="col-md-3 summary-stat">
                        <div class="value"><?php echo number_format($summary['total_transactions'] ?? 0); ?></div>
                        <div class="label">Total Transactions</div>
                    </div>
                    <div class="col-md-3 summary-stat">
                        <div class="value">₹<?php echo number_format($avg_metrics['overall_avg'] ?? 0, 2); ?></div>
                        <div class="label">Average Commission</div>
                    </div>
                    <div class="col-md-3 summary-stat">
                        <div class="value">₹<?php echo number_format($avg_metrics['max_commission'] ?? 0, 2); ?></div>
                        <div class="label">Highest Commission</div>
                    </div>
                </div>
            </div>
            
            <!-- Statistics Cards -->
            <?php if (!empty($type_stats)): ?>
            <div class="stats-grid">
                <?php 
                $type_colors = [
                    'level_reward' => ['icon' => 'level', 'color' => 'level', 'label' => 'Level Rewards'],
                    'referral_bonus' => ['icon' => 'referral', 'color' => 'referral', 'label' => 'Referral Bonus'],
                    'pair_matching' => ['icon' => 'pair', 'color' => 'pair', 'label' => 'Pair Matching'],
                    'spill_income' => ['icon' => 'total', 'color' => 'total', 'label' => 'Spill Income'],
                    'direct_commission' => ['icon' => 'total', 'color' => 'total', 'label' => 'Direct Commission']
                ];
                
                foreach ($type_stats as $stat): 
                    $type_info = $type_colors[$stat['income_type']] ?? ['icon' => 'total', 'color' => 'total', 'label' => ucwords(str_replace('_', ' ', $stat['income_type']))];
                ?>
                <div class="stat-card <?php echo $type_info['color']; ?>">
                    <div class="stat-icon <?php echo $type_info['icon']; ?>">
                        <?php if ($stat['income_type'] == 'level_reward'): ?>
                            <i class="fas fa-layer-group"></i>
                        <?php elseif ($stat['income_type'] == 'referral_bonus'): ?>
                            <i class="fas fa-user-plus"></i>
                        <?php elseif ($stat['income_type'] == 'pair_matching'): ?>
                            <i class="fas fa-handshake"></i>
                        <?php elseif ($stat['income_type'] == 'spill_income'): ?>
                            <i class="fas fa-arrow-down"></i>
                        <?php elseif ($stat['income_type'] == 'direct_commission'): ?>
                            <i class="fas fa-user-check"></i>
                        <?php else: ?>
                            <i class="fas fa-coins"></i>
                        <?php endif; ?>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($stat['total_amount'], 2); ?></div>
                    <div class="stat-label"><?php echo $type_info['label']; ?></div>
                    <small class="text-muted"><?php echo $stat['transaction_count']; ?> transactions</small>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            
            <!-- Filter Card -->
            <div class="filter-card">
                <h5 class="mb-4"><i class="fas fa-filter me-2"></i>Filter Commission Data</h5>
                
                <form method="GET" class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label">Date Range</label>
                        <select name="date_range" class="form-select" onchange="toggleCustomDates(this.value)">
                            <option value="today" <?php echo $date_range == 'today' ? 'selected' : ''; ?>>Today</option>
                            <option value="yesterday" <?php echo $date_range == 'yesterday' ? 'selected' : ''; ?>>Yesterday</option>
                            <option value="this_week" <?php echo $date_range == 'this_week' ? 'selected' : ''; ?>>This Week</option>
                            <option value="this_month" <?php echo $date_range == 'this_month' ? 'selected' : ''; ?>>This Month</option>
                            <option value="last_month" <?php echo $date_range == 'last_month' ? 'selected' : ''; ?>>Last Month</option>
                            <option value="this_quarter" <?php echo $date_range == 'this_quarter' ? 'selected' : ''; ?>>This Quarter</option>
                            <option value="this_year" <?php echo $date_range == 'this_year' ? 'selected' : ''; ?>>This Year</option>
                            <option value="custom" <?php echo $date_range == 'custom' ? 'selected' : ''; ?>>Custom Range</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2 custom-date" style="display: <?php echo $date_range == 'custom' ? 'block' : 'none'; ?>;">
                        <label class="form-label">From Date</label>
                        <input type="date" class="form-control" name="from_date" value="<?php echo $custom_from; ?>">
                    </div>
                    
                    <div class="col-md-2 custom-date" style="display: <?php echo $date_range == 'custom' ? 'block' : 'none'; ?>;">
                        <label class="form-label">To Date</label>
                        <input type="date" class="form-control" name="to_date" value="<?php echo $custom_to; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">Commission Type</label>
                        <select name="commission_type" class="form-select">
                            <option value="">All Types</option>
                            <?php foreach ($available_types as $type): ?>
                                <option value="<?php echo $type; ?>" <?php echo $commission_type == $type ? 'selected' : ''; ?>>
                                    <?php echo ucwords(str_replace('_', ' ', $type)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">Level</label>
                        <select name="level" class="form-select">
                            <option value="0">All Levels</option>
                            <option value="1" <?php echo $level_filter == 1 ? 'selected' : ''; ?>>Level 1</option>
                            <option value="2" <?php echo $level_filter == 2 ? 'selected' : ''; ?>>Level 2</option>
                            <option value="3" <?php echo $level_filter == 3 ? 'selected' : ''; ?>>Level 3</option>
                            <option value="4" <?php echo $level_filter == 4 ? 'selected' : ''; ?>>Level 4</option>
                            <option value="5" <?php echo $level_filter == 5 ? 'selected' : ''; ?>>Level 5</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">User</label>
                        <select name="user_id" class="form-select user-select">
                            <option value="0">All Users</option>
                            <?php 
                            if ($users && mysqli_num_rows($users) > 0) {
                                mysqli_data_seek($users, 0);
                                while ($user = mysqli_fetch_assoc($users)): 
                                ?>
                                    <option value="<?php echo $user['user_id']; ?>" <?php echo $user_id_filter == $user['user_id'] ? 'selected' : ''; ?>>
                                        <?php echo $user['user_id']; ?> - <?php echo htmlspecialchars($user['name']); ?>
                                    </option>
                                <?php 
                                endwhile;
                            } 
                            ?>
                        </select>
                    </div>
                    
                    <div class="col-md-1 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </form>
            </div>
            
            <?php if ($no_data): ?>
                <!-- Empty State -->
                <div class="empty-state">
                    <i class="fas fa-chart-pie"></i>
                    <h5>No Commission Data Found</h5>
                    <p class="text-muted">There are no commission records for the selected period. Try adjusting your filters or date range.</p>
                    <button class="btn btn-primary mt-3" onclick="window.location.href='commission-report.php'">
                        <i class="fas fa-undo me-2"></i>Reset Filters
                    </button>
                </div>
            <?php else: ?>
                
                <!-- Charts Row -->
                <div class="row">
                    <div class="col-md-8">
                        <div class="chart-container">
                            <h5 class="mb-3"><i class="fas fa-chart-line me-2"></i>Daily Commission Trend</h5>
                            <div class="chart-box">
                                <canvas id="commissionTrendChart"></canvas>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="chart-container">
                            <h5 class="mb-3"><i class="fas fa-chart-pie me-2"></i>Commission Distribution</h5>
                            <div class="chart-box">
                                <canvas id="commissionPieChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Level Breakdown -->
                <?php if (!empty($level_stats)): ?>
                <div class="chart-container">
                    <h5 class="mb-4"><i class="fas fa-layer-group me-2"></i>Level-wise Commission Breakdown</h5>
                    
                    <div class="row">
                        <?php foreach ($level_stats as $level): ?>
                            <div class="col-md-4 mb-3">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <span class="level-box level-<?php echo $level['level']; ?>">L<?php echo $level['level']; ?></span>
                                            <span class="fw-bold text-success">₹<?php echo number_format($level['total'], 2); ?></span>
                                        </div>
                                        <div class="progress-commission mb-2">
                                            <div class="progress">
                                                <?php 
                                                $level_percentage = $summary['total_commission'] > 0 ? ($level['total'] / $summary['total_commission']) * 100 : 0;
                                                ?>
                                                <div class="progress-bar bg-<?php 
                                                    if ($level['level'] == 1) echo 'warning';
                                                    elseif ($level['level'] == 2) echo 'info';
                                                    elseif ($level['level'] == 3) echo 'success';
                                                    elseif ($level['level'] == 4) echo 'primary';
                                                    else echo 'danger';
                                                ?>" style="width: <?php echo $level_percentage; ?>%"></div>
                                            </div>
                                        </div>
                                        <div class="d-flex justify-content-between small text-muted">
                                            <span><?php echo $level['count']; ?> transactions</span>
                                            <span><?php echo round($level_percentage, 1); ?>% of total</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Top Earners Table -->
                <?php if (!empty($top_earners)): ?>
                <div class="table-container">
                    <h5 class="mb-4"><i class="fas fa-crown me-2"></i>Top Commission Earners</h5>
                    
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Rank</th>
                                    <th>User</th>
                                    <th>Contact</th>
                                    <th>Transactions</th>
                                    <th>Level Commission</th>
                                    <th>Referral Bonus</th>
                                    <th>Total Commission</th>
                                    <th>Share</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $rank = 1;
                                foreach ($top_earners as $earner): 
                                    $share = $summary['total_commission'] > 0 ? ($earner['total_commission'] / $summary['total_commission']) * 100 : 0;
                                ?>
                                    <tr>
                                        <td>
                                            <?php if ($rank == 1): ?>
                                                <span class="badge bg-warning text-dark"><i class="fas fa-crown me-1"></i>#1</span>
                                            <?php elseif ($rank == 2): ?>
                                                <span class="badge bg-secondary">#2</span>
                                            <?php elseif ($rank == 3): ?>
                                                <span class="badge bg-danger">#3</span>
                                            <?php else: ?>
                                                #<?php echo $rank; ?>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="fw-bold"><?php echo htmlspecialchars($earner['name'] ?: 'N/A'); ?></div>
                                            <small class="text-muted">ID: <?php echo $earner['user_id']; ?></small>
                                        </td>
                                        <td><?php echo $earner['mobile'] ?: 'N/A'; ?></td>
                                        <td><?php echo $earner['transaction_count']; ?></td>
                                        <td class="text-warning">₹<?php echo number_format($earner['level_commission'], 2); ?></td>
                                        <td class="text-success">₹<?php echo number_format($earner['referral_commission'], 2); ?></td>
                                        <td class="fw-bold">₹<?php echo number_format($earner['total_commission'], 2); ?></td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="progress flex-grow-1 me-2" style="height: 5px;">
                                                    <div class="progress-bar bg-success" style="width: <?php echo $share; ?>%"></div>
                                                </div>
                                                <small><?php echo round($share, 1); ?>%</small>
                                            </div>
                                        </td>
                                    </tr>
                                <?php 
                                    $rank++;
                                endforeach; 
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Recent Commission Transactions -->
                <div class="table-container">
                    <h5 class="mb-4"><i class="fas fa-history me-2"></i>Recent Commission Transactions</h5>
                    
                    <div class="table-responsive">
                        <table class="table table-hover datatable">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>User</th>
                                    <th>Commission Type</th>
                                    <th>Level</th>
                                    <th>Description</th>
                                    <th>Amount</th>
                                    <th>Transaction ID</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $recent_query = "SELECT ih.*, u.name as user_name 
                                                FROM income_history ih
                                                LEFT JOIN users u ON ih.user_id = u.user_id
                                                WHERE ih.income_type IN (" . implode(',', array_map(function($t) use ($conn) { return "'" . $conn->real_escape_string($t) . "'"; }, $available_types)) . ")
                                                ORDER BY ih.id DESC
                                                LIMIT 50";
                                $recent_result = mysqli_query($conn, $recent_query);
                                
                                if ($recent_result && mysqli_num_rows($recent_result) > 0):
                                    while ($row = mysqli_fetch_assoc($recent_result)):
                                ?>
                                <tr>
                                    <td>
                                        <div><?php echo date('d M Y', strtotime($row['created_at'])); ?></div>
                                        <small class="text-muted"><?php echo date('h:i A', strtotime($row['created_at'])); ?></small>
                                    </td>
                                    <td>
                                        <div class="fw-bold"><?php echo htmlspecialchars($row['user_name'] ?: 'N/A'); ?></div>
                                        <small class="text-muted">ID: <?php echo $row['user_id']; ?></small>
                                    </td>
                                    <td>
                                        <?php
                                        $badge_class = 'level';
                                        $icon = 'layer-group';
                                        if ($row['income_type'] == 'referral_bonus') {
                                            $badge_class = 'referral';
                                            $icon = 'user-plus';
                                        } elseif ($row['income_type'] == 'pair_matching') {
                                            $badge_class = 'pair';
                                            $icon = 'handshake';
                                        } elseif ($row['income_type'] == 'spill_income') {
                                            $badge_class = 'spill';
                                            $icon = 'arrow-down';
                                        } elseif ($row['income_type'] == 'direct_commission') {
                                            $badge_class = 'direct';
                                            $icon = 'user-check';
                                        }
                                        ?>
                                        <span class="commission-badge <?php echo $badge_class; ?>">
                                            <i class="fas fa-<?php echo $icon; ?> me-1"></i>
                                            <?php echo ucwords(str_replace('_', ' ', $row['income_type'])); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($row['level']): ?>
                                            <span class="level-box level-<?php echo $row['level']; ?>">L<?php echo $row['level']; ?></span>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($row['description']); ?></td>
                                    <td class="fw-bold text-success">+ ₹<?php echo number_format($row['amount'], 2); ?></td>
                                    <td><span class="badge bg-light text-dark"><?php echo $row['transaction_id'] ?: 'N/A'; ?></span></td>
                                </tr>
                                <?php 
                                    endwhile;
                                else:
                                ?>
                                <tr>
                                    <td colspan="7" class="text-center py-4">No recent transactions found.</td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>
        </section>
    </main>
    
    <!-- Floating Export Button -->
    <button class="export-btn" onclick="toggleExportMenu()">
        <i class="fas fa-download"></i>
    </button>
    
    <div class="export-menu" id="exportMenu">
        <a href="#" onclick="exportReport('pdf'); return false;">
            <i class="fas fa-file-pdf me-2 text-danger"></i>Export as PDF
        </a>
        <a href="#" onclick="exportReport('excel'); return false;">
            <i class="fas fa-file-excel me-2 text-success"></i>Export as Excel
        </a>
        <a href="#" onclick="exportReport('csv'); return false;">
            <i class="fas fa-file-csv me-2 text-primary"></i>Export as CSV
        </a>
        <a href="#" onclick="window.print(); return false;">
            <i class="fas fa-print me-2 text-secondary"></i>Print Report
        </a>
    </div>

    <?php include 'includes/footer.php'; ?>

    <!-- Vendor JS Files -->
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>
    <script src="assets/js/main.js"></script>
    
    <!-- jQuery and Plugins -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
    // Initialize Select2
    $(document).ready(function() {
        $('.user-select').select2({
            theme: 'bootstrap-5',
            placeholder: 'Search for a user...',
            allowClear: true,
            width: '100%'
        });
    });
    
    // Toggle custom date inputs
    function toggleCustomDates(value) {
        var customDates = document.querySelectorAll('.custom-date');
        if (value === 'custom') {
            customDates.forEach(el => el.style.display = 'block');
        } else {
            customDates.forEach(el => el.style.display = 'none');
        }
    }
    
    // Toggle export menu
    function toggleExportMenu() {
        document.getElementById('exportMenu').classList.toggle('show');
    }
    
    // Close export menu when clicking outside
    document.addEventListener('click', function(event) {
        var exportBtn = document.querySelector('.export-btn');
        var exportMenu = document.getElementById('exportMenu');
        if (!exportBtn.contains(event.target) && !exportMenu.contains(event.target)) {
            exportMenu.classList.remove('show');
        }
    });
    
    // Export function
    function exportReport(format) {
        var url = 'export-report.php?type=commission&format=' + format + '&<?php echo $_SERVER['QUERY_STRING']; ?>';
        window.open(url, '_blank');
        document.getElementById('exportMenu').classList.remove('show');
    }
    
    // Commission Trend Chart
    <?php if (!empty($daily_trend)): ?>
    const trendCtx = document.getElementById('commissionTrendChart').getContext('2d');
    const trendData = <?php echo json_encode($daily_trend); ?>;
    
    new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: trendData.map(item => {
                const date = new Date(item.date);
                return date.toLocaleDateString('en-IN', { day: 'numeric', month: 'short' });
            }),
            datasets: [
                {
                    label: 'Level Rewards',
                    data: trendData.map(item => item.level_amount),
                    borderColor: '#ffc107',
                    backgroundColor: 'rgba(255, 193, 7, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'Referral Bonus',
                    data: trendData.map(item => item.referral_amount),
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'Pair Matching',
                    data: trendData.map(item => item.pair_amount),
                    borderColor: '#17a2b8',
                    backgroundColor: 'rgba(23, 162, 184, 0.1)',
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '₹' + value.toLocaleString();
                        }
                    }
                }
            }
        }
    });
    <?php endif; ?>
    
    // Commission Pie Chart
    <?php if (!empty($type_stats)): ?>
    const pieCtx = document.getElementById('commissionPieChart').getContext('2d');
    const pieData = <?php echo json_encode($type_stats); ?>;
    
    new Chart(pieCtx, {
        type: 'doughnut',
        data: {
            labels: pieData.map(item => {
                return item.income_type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
            }),
            datasets: [{
                data: pieData.map(item => item.total_amount),
                backgroundColor: [
                    '#ffc107',
                    '#28a745',
                    '#17a2b8',
                    '#6f42c1',
                    '#fd7e14'
                ],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.label || '';
                            let value = context.raw || 0;
                            let total = context.dataset.data.reduce((a, b) => a + b, 0);
                            let percentage = ((value / total) * 100).toFixed(1);
                            return label + ': ₹' + value.toLocaleString() + ' (' + percentage + '%)';
                        }
                    }
                }
            }
        }
    });
    <?php endif; ?>
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>