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

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

// Handle mark as paid
if (isset($_POST['mark_paid'])) {
    $reward_id = intval($_POST['reward_id']);
    $user_id = intval($_POST['user_id']);
    $level = intval($_POST['level']);
    $amount = floatval($_POST['amount']);
    
    $paid_at = date('Y-m-d H:i:s');
    
    mysqli_begin_transaction($conn);
    
    try {
        // Update level reward as paid
        $stmt = mysqli_prepare($conn, "UPDATE level_rewards SET paid = 1, paid_at = ? WHERE id = ?");
        mysqli_stmt_bind_param($stmt, "si", $paid_at, $reward_id);
        
        if (!mysqli_stmt_execute($stmt)) {
            throw new Exception("Failed to update reward status: " . mysqli_error($conn));
        }
        mysqli_stmt_close($stmt);
        
        // Add to income history
        $description = "Level $level completion reward";
        $trans_id = 'LVL' . time() . rand(100, 999);
        $credit_debit = 1;
        
        $stmt = mysqli_prepare($conn, "INSERT INTO income_history 
            (user_id, amount, description, credit_debit, income_type, transaction_id, created_at, level) 
            VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)");
        
        mysqli_stmt_bind_param($stmt, "idsissi", $user_id, $amount, $description, $credit_debit, $income_type = 'level_reward', $trans_id, $level);
        
        if (!mysqli_stmt_execute($stmt)) {
            throw new Exception("Failed to add to income history: " . mysqli_error($conn));
        }
        mysqli_stmt_close($stmt);
        
        // Update user's wallet
        $stmt = mysqli_prepare($conn, "UPDATE users SET wallet = wallet + ? WHERE user_id = ?");
        mysqli_stmt_bind_param($stmt, "di", $amount, $user_id);
        
        if (!mysqli_stmt_execute($stmt)) {
            throw new Exception("Failed to update user wallet: " . mysqli_error($conn));
        }
        mysqli_stmt_close($stmt);
        
        mysqli_commit($conn);
        
        $_SESSION['flash_message'] = "Level $level reward of ₹$amount marked as paid for User $user_id!";
        $_SESSION['flash_type'] = "success";
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $_SESSION['flash_message'] = "Error: " . $e->getMessage();
        $_SESSION['flash_type'] = "danger";
    }
    
    header("Location: level-rewards.php");
    exit();
}

// Handle mark multiple as paid
if (isset($_POST['bulk_mark_paid'])) {
    $selected_rewards = isset($_POST['selected_rewards']) ? $_POST['selected_rewards'] : [];
    
    if (empty($selected_rewards)) {
        $_SESSION['flash_message'] = "No rewards selected!";
        $_SESSION['flash_type'] = "warning";
        header("Location: level-rewards.php");
        exit();
    }
    
    $reward_ids = implode(',', array_map('intval', $selected_rewards));
    $paid_at = date('Y-m-d H:i:s');
    
    mysqli_begin_transaction($conn);
    
    try {
        // Get rewards details first
        $rewards_query = mysqli_query($conn, "SELECT * FROM level_rewards WHERE id IN ($reward_ids) AND paid = 0");
        
        while ($reward = mysqli_fetch_assoc($rewards_query)) {
            // Update each reward
            $stmt = mysqli_prepare($conn, "UPDATE level_rewards SET paid = 1, paid_at = ? WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "si", $paid_at, $reward['id']);
            
            if (!mysqli_stmt_execute($stmt)) {
                throw new Exception("Failed to update reward ID: " . $reward['id']);
            }
            mysqli_stmt_close($stmt);
            
            // Add to income history
            $description = "Level " . $reward['level'] . " completion reward";
            $trans_id = 'LVL' . time() . rand(100, 999) . $reward['id'];
            $credit_debit = 1;
            
            $stmt = mysqli_prepare($conn, "INSERT INTO income_history 
                (user_id, amount, description, credit_debit, income_type, transaction_id, created_at, level) 
                VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)");
            
            mysqli_stmt_bind_param($stmt, "idsissi", $reward['user_id'], $reward['amount'], $description, $credit_debit, $income_type = 'level_reward', $trans_id, $reward['level']);
            
            if (!mysqli_stmt_execute($stmt)) {
                throw new Exception("Failed to add to income history for reward ID: " . $reward['id']);
            }
            mysqli_stmt_close($stmt);
            
            // Update user's wallet
            $stmt = mysqli_prepare($conn, "UPDATE users SET wallet = wallet + ? WHERE user_id = ?");
            mysqli_stmt_bind_param($stmt, "di", $reward['amount'], $reward['user_id']);
            
            if (!mysqli_stmt_execute($stmt)) {
                throw new Exception("Failed to update wallet for user: " . $reward['user_id']);
            }
            mysqli_stmt_close($stmt);
        }
        
        mysqli_commit($conn);
        
        $_SESSION['flash_message'] = "Selected rewards marked as paid successfully!";
        $_SESSION['flash_type'] = "success";
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $_SESSION['flash_message'] = "Error: " . $e->getMessage();
        $_SESSION['flash_type'] = "danger";
    }
    
    header("Location: level-rewards.php");
    exit();
}

// Check for flash messages
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $message_type = $_SESSION['flash_type'];
    unset($_SESSION['flash_message']);
    unset($_SESSION['flash_type']);
}

// Filters
$user_id_filter = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$level_filter = isset($_GET['level']) ? intval($_GET['level']) : 0;
$paid_filter = isset($_GET['paid']) ? intval($_GET['paid']) : -1;
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build WHERE clause
$where = [];

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

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

if ($paid_filter >= 0) {
    $where[] = "lr.paid = $paid_filter";
}

if ($date_from) {
    $where[] = "DATE(lr.paid_at) >= '$date_from'";
}

if ($date_to) {
    $where[] = "DATE(lr.paid_at) <= '$date_to'";
}

$where_clause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// Pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 50;
$offset = ($page - 1) * $limit;

// Get total count
$total_result = mysqli_query($conn, "SELECT COUNT(*) as total FROM level_rewards lr $where_clause");
$total = mysqli_fetch_assoc($total_result)['total'];
$total_pages = ceil($total / $limit);

// Get level rewards with user details
$query = "SELECT lr.*, 
                 u.name as user_name, 
                 u.mobile as user_mobile,
                 u.email as user_email,
                 u.wallet as user_wallet,
                 u.rank as user_rank
          FROM level_rewards lr
          LEFT JOIN users u ON lr.user_id = u.user_id
          $where_clause
          ORDER BY lr.paid ASC, lr.id DESC
          LIMIT $offset, $limit";

$rewards = mysqli_query($conn, $query);

// Get statistics
$stats = [];

// Total rewards amount
$result = mysqli_query($conn, "SELECT SUM(amount) as total FROM level_rewards");
$stats['total_rewards'] = mysqli_fetch_assoc($result)['total'] ?? 0;

// Paid vs Unpaid
$result = mysqli_query($conn, "SELECT paid, COUNT(*) as count, SUM(amount) as total FROM level_rewards GROUP BY paid");
while ($row = mysqli_fetch_assoc($result)) {
    if ($row['paid'] == 1) {
        $stats['paid_count'] = $row['count'];
        $stats['paid_total'] = $row['total'];
    } else {
        $stats['unpaid_count'] = $row['count'];
        $stats['unpaid_total'] = $row['total'];
    }
}
$stats['paid_count'] = $stats['paid_count'] ?? 0;
$stats['paid_total'] = $stats['paid_total'] ?? 0;
$stats['unpaid_count'] = $stats['unpaid_count'] ?? 0;
$stats['unpaid_total'] = $stats['unpaid_total'] ?? 0;

// Level wise breakdown
$level_stats = [];
$result = mysqli_query($conn, "SELECT level, COUNT(*) as count, SUM(amount) as total, SUM(CASE WHEN paid = 1 THEN amount ELSE 0 END) as paid_total FROM level_rewards GROUP BY level ORDER BY level");
while ($row = mysqli_fetch_assoc($result)) {
    $level_stats[] = $row;
}

// Top earners
$top_earners = mysqli_query($conn, "SELECT lr.user_id, u.name, SUM(lr.amount) as total_earned, COUNT(*) as rewards_count 
                                     FROM level_rewards lr 
                                     LEFT JOIN users u ON lr.user_id = u.user_id 
                                     WHERE lr.paid = 1 
                                     GROUP BY lr.user_id 
                                     ORDER BY total_earned DESC 
                                     LIMIT 10");

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

// Get monthly trend data
$monthly_data = [];
$result = mysqli_query($conn, "SELECT DATE_FORMAT(paid_at, '%Y-%m') as month, 
                                COUNT(*) as count, 
                                SUM(amount) as total 
                                FROM level_rewards 
                                WHERE paid = 1 AND paid_at IS NOT NULL
                                GROUP BY DATE_FORMAT(paid_at, '%Y-%m') 
                                ORDER BY month DESC 
                                LIMIT 12");
while ($row = mysqli_fetch_assoc($result)) {
    $monthly_data[] = $row;
}
$monthly_data = array_reverse($monthly_data);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Level Rewards - 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;
        }
        
        .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.paid::before { background: linear-gradient(180deg, #28a745, #20c997); }
        .stat-card.unpaid::before { background: linear-gradient(180deg, #dc3545, #fd7e14); }
        .stat-card.avg::before { background: linear-gradient(180deg, #ffc107, #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.paid { background: rgba(40, 167, 69, 0.1); color: #28a745; }
        .stat-icon.unpaid { background: rgba(220, 53, 69, 0.1); color: #dc3545; }
        .stat-icon.avg { background: rgba(255, 193, 7, 0.1); color: #ffc107; }
        
        .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;
        }
        
        .table-container {
            background: white;
            border-radius: 16px;
            padding: 25px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .reward-level {
            display: inline-block;
            width: 32px;
            height: 32px;
            line-height: 32px;
            text-align: center;
            border-radius: 8px;
            font-weight: 600;
            font-size: 14px;
        }
        
        .reward-level.level1 { background: rgba(255, 193, 7, 0.15); color: #856404; }
        .reward-level.level2 { background: rgba(23, 162, 184, 0.15); color: #0c5460; }
        .reward-level.level3 { background: rgba(40, 167, 69, 0.15); color: #155724; }
        .reward-level.level4 { background: rgba(111, 66, 193, 0.15); color: #563d7c; }
        .reward-level.level5 { background: rgba(220, 53, 69, 0.15); color: #721c24; }
        
        .badge-status {
            padding: 6px 12px;
            border-radius: 30px;
            font-weight: 500;
            font-size: 12px;
        }
        
        .badge-status.paid {
            background: rgba(40, 167, 69, 0.15);
            color: #28a745;
        }
        
        .badge-status.unpaid {
            background: rgba(220, 53, 69, 0.15);
            color: #dc3545;
        }
        
        .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin: 0 3px;
            transition: all 0.2s;
            border: none;
            background: transparent;
            color: #6c757d;
        }
        
        .action-btn:hover {
            background: #f8f9fa;
            color: #4154f1;
            transform: scale(1.1);
        }
        
        .action-btn.pay:hover { background: rgba(40, 167, 69, 0.1); color: #28a745; }
        
        .pagination .page-link {
            border: none;
            padding: 8px 16px;
            margin: 0 5px;
            border-radius: 8px;
            color: #6c757d;
            font-weight: 500;
        }
        
        .pagination .page-item.active .page-link {
            background: #4154f1;
            color: white;
        }
        
        .level-breakdown-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            margin-top: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid #f0f0f0;
        }
        
        .progress-level {
            height: 8px;
            border-radius: 4px;
            margin: 10px 0;
        }
        
        .level-item {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .level-item:last-child {
            border-bottom: none;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        
        .empty-state i {
            font-size: 60px;
            color: #dee2e6;
            margin-bottom: 20px;
        }
        
        .chart-container {
            position: relative;
            height: 300px;
            margin-top: 20px;
        }
        
        .top-earner-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .top-earner-item:last-child {
            border-bottom: none;
        }
        
        .rank-badge {
            width: 24px;
            height: 24px;
            border-radius: 12px;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 12px;
            margin-right: 10px;
        }
        
        .rank-badge.gold { background: #ffd700; color: #856404; }
        .rank-badge.silver { background: #c0c0c0; color: #495057; }
        .rank-badge.bronze { background: #cd7f32; color: #fff; }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    <?php include 'includes/sidebar.php'; ?>

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

        <section class="section">
            <!-- Statistics Cards -->
            <div class="stats-grid">
                <div class="stat-card total">
                    <div class="stat-icon total">
                        <i class="fas fa-trophy"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($stats['total_rewards'], 2); ?></div>
                    <div class="stat-label">Total Rewards</div>
                </div>
                
                <div class="stat-card paid">
                    <div class="stat-icon paid">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($stats['paid_total'], 2); ?></div>
                    <div class="stat-label">Paid (<?php echo $stats['paid_count']; ?> rewards)</div>
                </div>
                
                <div class="stat-card unpaid">
                    <div class="stat-icon unpaid">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($stats['unpaid_total'], 2); ?></div>
                    <div class="stat-label">Pending (<?php echo $stats['unpaid_count']; ?> rewards)</div>
                </div>
                
                <div class="stat-card avg">
                    <div class="stat-icon avg">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($stats['total_rewards'] / max(1, ($stats['paid_count'] + $stats['unpaid_count'])), 2); ?></div>
                    <div class="stat-label">Average Reward</div>
                </div>
            </div>
            
            <!-- Filter Card -->
            <div class="filter-card">
                <h5 class="mb-4"><i class="fas fa-filter me-2"></i>Filter Rewards</h5>
                
                <form method="GET" class="row g-3">
                    <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 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-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-2">
                        <label class="form-label">Status</label>
                        <select name="paid" class="form-select">
                            <option value="-1">All Status</option>
                            <option value="1" <?php echo $paid_filter == 1 ? 'selected' : ''; ?>>Paid</option>
                            <option value="0" <?php echo $paid_filter == 0 ? 'selected' : ''; ?>>Unpaid</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">Date From</label>
                        <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">Date To</label>
                        <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                    </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 class="row mt-3">
                    <div class="col-md-12 text-end">
                        <a href="level-rewards.php" class="btn btn-secondary">
                            <i class="fas fa-undo me-2"></i>Reset Filters
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- Charts Row -->
            <div class="row">
                <div class="col-md-8">
                    <div class="level-breakdown-card">
                        <h5 class="mb-3"><i class="fas fa-chart-bar me-2"></i>Monthly Reward Distribution</h5>
                        <div class="chart-container">
                            <canvas id="monthlyChart"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="level-breakdown-card">
                        <h5 class="mb-3"><i class="fas fa-crown me-2"></i>Top Earners</h5>
                        
                        <?php if ($top_earners && mysqli_num_rows($top_earners) > 0): ?>
                            <?php $rank = 1; ?>
                            <?php while ($earner = mysqli_fetch_assoc($top_earners)): ?>
                                <div class="top-earner-item">
                                    <div class="rank-badge <?php 
                                        if ($rank == 1) echo 'gold';
                                        elseif ($rank == 2) echo 'silver';
                                        elseif ($rank == 3) echo 'bronze';
                                    ?>"><?php echo $rank; ?></div>
                                    <div class="flex-grow-1">
                                        <div class="fw-bold"><?php echo htmlspecialchars($earner['name'] ?: 'User ' . $earner['user_id']); ?></div>
                                        <small class="text-muted">ID: <?php echo $earner['user_id']; ?></small>
                                    </div>
                                    <div class="text-end">
                                        <div class="fw-bold text-success">₹<?php echo number_format($earner['total_earned'], 2); ?></div>
                                        <small class="text-muted"><?php echo $earner['rewards_count']; ?> rewards</small>
                                    </div>
                                </div>
                                <?php $rank++; ?>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="empty-state py-4">
                                <i class="fas fa-crown"></i>
                                <p class="text-muted">No earners yet</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Bulk Actions -->
            <?php if ($stats['unpaid_count'] > 0): ?>
            <form method="POST" id="bulkActionForm" onsubmit="return confirm('Mark selected rewards as paid? This will add to income history and update wallets.')">
                <input type="hidden" name="bulk_mark_paid" value="1">
                <div class="d-flex justify-content-between align-items-center my-3">
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-check-double me-2"></i>Mark Selected as Paid
                        </button>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Rewards Table -->
            <div class="table-container">
                <h5 class="mb-4"><i class="fas fa-list-alt me-2"></i>Level Rewards List</h5>
                
                <?php if ($rewards && mysqli_num_rows($rewards) > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <?php if ($stats['unpaid_count'] > 0): ?>
                                        <th width="40">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="selectAll">
                                            </div>
                                        </th>
                                    <?php endif; ?>
                                    <th>ID</th>
                                    <th>User</th>
                                    <th>Level</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Achieved Date</th>
                                    <th>Paid Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($reward = mysqli_fetch_assoc($rewards)): ?>
                                <tr class="<?php echo $reward['paid'] == 0 ? 'table-warning' : ''; ?>">
                                    <?php if ($stats['unpaid_count'] > 0 && $reward['paid'] == 0): ?>
                                        <td>
                                            <div class="form-check">
                                                <input class="form-check-input reward-checkbox" type="checkbox" name="selected_rewards[]" value="<?php echo $reward['id']; ?>">
                                            </div>
                                        </td>
                                    <?php elseif ($stats['unpaid_count'] > 0): ?>
                                        <td></td>
                                    <?php endif; ?>
                                    
                                    <td>
                                        <span class="fw-bold">#<?php echo $reward['id']; ?></span>
                                    </td>
                                    
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div>
                                                <div class="fw-bold"><?php echo htmlspecialchars($reward['user_name'] ?: 'N/A'); ?></div>
                                                <small class="text-muted">ID: <?php echo $reward['user_id']; ?></small>
                                                <?php if ($reward['user_mobile']): ?>
                                                    <br><small class="text-muted"><?php echo $reward['user_mobile']; ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <div class="reward-level level<?php echo $reward['level']; ?>">
                                            L<?php echo $reward['level']; ?>
                                        </div>
                                    </td>
                                    
                                    <td>
                                        <span class="fw-bold text-success">₹<?php echo number_format($reward['amount'], 2); ?></span>
                                    </td>
                                    
                                    <td>
                                        <?php if ($reward['paid'] == 1): ?>
                                            <span class="badge-status paid">
                                                <i class="fas fa-check-circle me-1"></i>Paid
                                            </span>
                                        <?php else: ?>
                                            <span class="badge-status unpaid">
                                                <i class="fas fa-hourglass-half me-1"></i>Pending
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td>
                                        <?php if ($reward['paid_at'] && $reward['paid_at'] != '0000-00-00 00:00:00'): ?>
                                            <div><?php echo date('d M Y', strtotime($reward['paid_at'])); ?></div>
                                            <small class="text-muted"><?php echo date('h:i A', strtotime($reward['paid_at'])); ?></small>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td>
                                        <?php if (isset($reward['paid_at']) && $reward['paid_at'] && $reward['paid_at'] != '0000-00-00 00:00:00'): ?>
                                            <div><?php echo date('d M Y', strtotime($reward['paid_at'])); ?></div>
                                            <small class="text-muted"><?php echo date('h:i A', strtotime($reward['paid_at'])); ?></small>
                                        <?php else: ?>
                                            <span class="text-muted">Not paid</span>
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td>
                                        <?php if ($reward['paid'] == 0): ?>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Mark this reward as paid? This will add ₹<?php echo $reward['amount']; ?> to user\'s wallet.')">
                                                <input type="hidden" name="reward_id" value="<?php echo $reward['id']; ?>">
                                                <input type="hidden" name="user_id" value="<?php echo $reward['user_id']; ?>">
                                                <input type="hidden" name="level" value="<?php echo $reward['level']; ?>">
                                                <input type="hidden" name="amount" value="<?php echo $reward['amount']; ?>">
                                                <button type="submit" name="mark_paid" class="action-btn pay" title="Mark as Paid">
                                                    <i class="fas fa-check-circle"></i>
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <?php if ($stats['unpaid_count'] > 0): ?>
                        </form> <!-- Close bulk action form -->
                    <?php endif; ?>
                    
                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <nav class="mt-4">
                        <ul class="pagination justify-content-center">
                            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $page-1; ?>&user_id=<?php echo $user_id_filter; ?>&level=<?php echo $level_filter; ?>&paid=<?php echo $paid_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                    <i class="fas fa-chevron-left"></i>
                                </a>
                            </li>
                            
                            <?php 
                            $start = max(1, $page - 2);
                            $end = min($total_pages, $page + 2);
                            for ($i = $start; $i <= $end; $i++): 
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&user_id=<?php echo $user_id_filter; ?>&level=<?php echo $level_filter; ?>&paid=<?php echo $paid_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $page+1; ?>&user_id=<?php echo $user_id_filter; ?>&level=<?php echo $level_filter; ?>&paid=<?php echo $paid_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            </li>
                        </ul>
                    </nav>
                    <?php endif; ?>
                    
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-trophy"></i>
                        <h5>No Level Rewards Found</h5>
                        <p class="text-muted">No rewards match your criteria.</p>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Level Breakdown -->
            <div class="level-breakdown-card">
                <h5 class="mb-4"><i class="fas fa-chart-pie me-2"></i>Level Wise Breakdown</h5>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="chart-container" style="height: 250px;">
                            <canvas id="levelChart"></canvas>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <?php foreach ($level_stats as $level): ?>
                            <div class="level-item">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div>
                                        <span class="reward-level level<?php echo $level['level']; ?> me-2">L<?php echo $level['level']; ?></span>
                                        <span class="fw-bold">Level <?php echo $level['level']; ?> Rewards</span>
                                    </div>
                                    <div class="text-end">
                                        <span class="fw-bold text-success">₹<?php echo number_format($level['total'], 2); ?></span>
                                    </div>
                                </div>
                                
                                <div class="progress-level">
                                    <?php 
                                    $paid_percentage = $level['total'] > 0 ? ($level['paid_total'] / $level['total']) * 100 : 0;
                                    ?>
                                    <div class="progress" style="height: 8px;">
                                        <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $paid_percentage; ?>%"></div>
                                        <div class="progress-bar bg-warning" role="progressbar" style="width: <?php echo 100 - $paid_percentage; ?>%"></div>
                                    </div>
                                </div>
                                
                                <div class="d-flex justify-content-between small text-muted mt-1">
                                    <span>Paid: ₹<?php echo number_format($level['paid_total'], 2); ?> (<?php echo round($paid_percentage, 1); ?>%)</span>
                                    <span>Total: <?php echo $level['count']; ?> rewards</span>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <?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%'
        });
    });
    
    // Select All checkbox
    document.getElementById('selectAll')?.addEventListener('change', function() {
        var checkboxes = document.getElementsByClassName('reward-checkbox');
        for (var i = 0; i < checkboxes.length; i++) {
            checkboxes[i].checked = this.checked;
        }
    });
    
    // Monthly Chart
    const monthlyCtx = document.getElementById('monthlyChart').getContext('2d');
    const monthlyData = <?php echo json_encode($monthly_data); ?>;
    
    new Chart(monthlyCtx, {
        type: 'bar',
        data: {
            labels: monthlyData.map(item => {
                const [year, month] = item.month.split('-');
                return new Date(year, month - 1).toLocaleString('default', { month: 'short', year: 'numeric' });
            }),
            datasets: [
                {
                    label: 'Amount Paid',
                    data: monthlyData.map(item => item.total),
                    backgroundColor: 'rgba(40, 167, 69, 0.7)',
                    borderColor: '#28a745',
                    borderWidth: 1,
                    yAxisID: 'y'
                },
                {
                    label: 'Number of Rewards',
                    data: monthlyData.map(item => item.count),
                    backgroundColor: 'rgba(65, 84, 241, 0.7)',
                    borderColor: '#4154f1',
                    borderWidth: 1,
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    title: {
                        display: true,
                        text: 'Amount (₹)'
                    },
                    ticks: {
                        callback: function(value) {
                            return '₹' + value.toLocaleString();
                        }
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: 'Count'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                }
            }
        }
    });
    
    // Level Chart
    const levelCtx = document.getElementById('levelChart').getContext('2d');
    const levelStats = <?php echo json_encode($level_stats); ?>;
    
    new Chart(levelCtx, {
        type: 'doughnut',
        data: {
            labels: levelStats.map(item => 'Level ' + item.level),
            datasets: [{
                data: levelStats.map(item => item.total),
                backgroundColor: [
                    '#ffc107',
                    '#17a2b8',
                    '#28a745',
                    '#6f42c1',
                    '#dc3545'
                ],
                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 + '%)';
                        }
                    }
                }
            }
        }
    });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>