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

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

// Handle filters
$user_id_filter = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$income_type_filter = isset($_GET['income_type']) ? sanitize($conn, $_GET['income_type']) : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$credit_debit_filter = isset($_GET['credit_debit']) ? intval($_GET['credit_debit']) : -1;
$search = isset($_GET['search']) ? sanitize($conn, $_GET['search']) : '';

// Build WHERE clause
$where = [];

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

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

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

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

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

if ($search) {
    $where[] = "(ih.description LIKE '%$search%' OR ih.transaction_id LIKE '%$search%' OR u.name LIKE '%$search%' OR u.user_id LIKE '%$search%')";
}

$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 income_history ih 
                                     LEFT JOIN users u ON ih.user_id = u.user_id 
                                     $where_clause");
$total = mysqli_fetch_assoc($total_result)['total'];
$total_pages = ceil($total / $limit);

// Get income history with user details
$query = "SELECT ih.*, 
                 u.name as user_name, 
                 u.mobile as user_mobile,
                 fu.name as from_user_name,
                 tu.name as to_user_name
          FROM income_history ih
          LEFT JOIN users u ON ih.user_id = u.user_id
          LEFT JOIN users fu ON ih.from_user_id = fu.user_id
          LEFT JOIN users tu ON ih.to_user_id = tu.user_id
          $where_clause
          ORDER BY ih.id DESC
          LIMIT $offset, $limit";

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

// Get summary statistics
$stats = [];

// Total income (credit)
$result = mysqli_query($conn, "SELECT SUM(amount) as total FROM income_history WHERE credit_debit = 1");
$stats['total_income'] = mysqli_fetch_assoc($result)['total'] ?? 0;

// Total withdrawals (debit)
$result = mysqli_query($conn, "SELECT SUM(amount) as total FROM income_history WHERE credit_debit = 0");
$stats['total_withdrawals'] = mysqli_fetch_assoc($result)['total'] ?? 0;

// Net balance
$stats['net_balance'] = $stats['total_income'] - $stats['total_withdrawals'];

// Count by income type
$type_stats = [];
$result = mysqli_query($conn, "SELECT income_type, COUNT(*) as count, SUM(amount) as total 
                                FROM income_history 
                                GROUP BY income_type 
                                ORDER BY total DESC");
while ($row = mysqli_fetch_assoc($result)) {
    $type_stats[] = $row;
}

// Get distinct income types for filter
$income_types = mysqli_query($conn, "SELECT DISTINCT income_type FROM income_history WHERE income_type IS NOT NULL ORDER BY income_type");

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

// Get recent activity for chart
$chart_data = [];
$chart_result = mysqli_query($conn, "SELECT DATE(created_at) as date, 
                                      SUM(CASE WHEN credit_debit = 1 THEN amount ELSE 0 END) as credit,
                                      SUM(CASE WHEN credit_debit = 0 THEN amount ELSE 0 END) as debit
                                      FROM income_history 
                                      WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
                                      GROUP BY DATE(created_at)
                                      ORDER BY date ASC");
while ($row = mysqli_fetch_assoc($chart_result)) {
    $chart_data[] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Income History - 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" />
    
    <!-- Date Range Picker -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
    
    <!-- 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.income::before { background: linear-gradient(180deg, #28a745, #20c997); }
        .stat-card.withdrawal::before { background: linear-gradient(180deg, #dc3545, #fd7e14); }
        .stat-card.net::before { background: linear-gradient(180deg, #4154f1, #6f42c1); }
        
        .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.income { background: rgba(40, 167, 69, 0.1); color: #28a745; }
        .stat-icon.withdrawal { background: rgba(220, 53, 69, 0.1); color: #dc3545; }
        .stat-icon.net { background: rgba(65, 84, 241, 0.1); color: #4154f1; }
        
        .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;
        }
        
        .badge-income {
            padding: 6px 12px;
            border-radius: 30px;
            font-weight: 500;
            font-size: 12px;
        }
        
        .badge-income.credit {
            background: rgba(40, 167, 69, 0.15);
            color: #28a745;
        }
        
        .badge-income.debit {
            background: rgba(220, 53, 69, 0.15);
            color: #dc3545;
        }
        
        .badge-type {
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 500;
            background: #f8f9fa;
            color: #495057;
        }
        
        .amount-positive {
            color: #28a745;
            font-weight: 600;
        }
        
        .amount-negative {
            color: #dc3545;
            font-weight: 600;
        }
        
        .transaction-id {
            font-family: monospace;
            font-size: 12px;
            background: #f8f9fa;
            padding: 4px 8px;
            border-radius: 4px;
            display: inline-block;
        }
        
        .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;
        }
        
        .type-chart-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;
        }
        
        .type-item {
            display: flex;
            align-items: center;
            padding: 12px;
            border-bottom: 1px solid #f0f0f0;
            transition: all 0.2s;
        }
        
        .type-item:hover {
            background: #f8f9fa;
        }
        
        .type-item:last-child {
            border-bottom: none;
        }
        
        .type-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
        }
        
        .type-icon.level { background: rgba(65, 84, 241, 0.1); color: #4154f1; }
        .type-icon.referral { background: rgba(40, 167, 69, 0.1); color: #28a745; }
        .type-icon.withdrawal { background: rgba(220, 53, 69, 0.1); color: #dc3545; }
        .type-icon.pair { background: rgba(255, 193, 7, 0.1); color: #ffc107; }
        .type-icon.pin { background: rgba(111, 66, 193, 0.1); color: #6f42c1; }
        
        .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;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    <?php include 'includes/sidebar.php'; ?>

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

        <section class="section">
            <!-- Statistics Cards -->
            <div class="stats-grid">
                <div class="stat-card income">
                    <div class="stat-icon income">
                        <i class="fas fa-arrow-down"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($stats['total_income'], 2); ?></div>
                    <div class="stat-label">Total Income (Credits)</div>
                </div>
                
                <div class="stat-card withdrawal">
                    <div class="stat-icon withdrawal">
                        <i class="fas fa-arrow-up"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($stats['total_withdrawals'], 2); ?></div>
                    <div class="stat-label">Total Withdrawals (Debits)</div>
                </div>
                
                <div class="stat-card net">
                    <div class="stat-icon net">
                        <i class="fas fa-wallet"></i>
                    </div>
                    <div class="stat-value">₹<?php echo number_format($stats['net_balance'], 2); ?></div>
                    <div class="stat-label">Net Balance</div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon" style="background: rgba(23, 162, 184, 0.1); color: #17a2b8;">
                        <i class="fas fa-exchange-alt"></i>
                    </div>
                    <div class="stat-value"><?php echo number_format($total); ?></div>
                    <div class="stat-label">Total Transactions</div>
                </div>
            </div>
            
            <!-- Filter Card -->
            <div class="filter-card">
                <h5 class="mb-4"><i class="fas fa-filter me-2"></i>Filter Transactions</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">Type</label>
                        <select name="credit_debit" class="form-select">
                            <option value="-1">All Types</option>
                            <option value="1" <?php echo $credit_debit_filter == 1 ? 'selected' : ''; ?>>Credit (Income)</option>
                            <option value="0" <?php echo $credit_debit_filter == 0 ? 'selected' : ''; ?>>Debit (Withdrawal)</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">Income Type</label>
                        <select name="income_type" class="form-select">
                            <option value="">All Income Types</option>
                            <?php while ($type = mysqli_fetch_assoc($income_types)): ?>
                                <option value="<?php echo $type['income_type']; ?>" <?php echo $income_type_filter == $type['income_type'] ? 'selected' : ''; ?>>
                                    <?php echo ucwords(str_replace('_', ' ', $type['income_type'])); ?>
                                </option>
                            <?php endwhile; ?>
                        </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-4">
                        <input type="text" class="form-control" placeholder="Search in description or transaction ID" 
                               value="<?php echo htmlspecialchars($search); ?>" 
                               onchange="window.location.href='?search=' + encodeURIComponent(this.value) + '&user_id=<?php echo $user_id_filter; ?>&credit_debit=<?php echo $credit_debit_filter; ?>&income_type=<?php echo $income_type_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>'">
                    </div>
                    <div class="col-md-8 text-end">
                        <a href="income-history.php" class="btn btn-secondary">
                            <i class="fas fa-undo me-2"></i>Reset Filters
                        </a>
                        <a href="export-income.php?<?php echo $_SERVER['QUERY_STRING']; ?>" class="btn btn-success">
                            <i class="fas fa-download me-2"></i>Export
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- Income Chart -->
            <div class="type-chart-card">
                <h5 class="mb-3"><i class="fas fa-chart-line me-2"></i>Last 30 Days Activity</h5>
                <div class="chart-container">
                    <canvas id="incomeChart"></canvas>
                </div>
            </div>
            
            <!-- Income History Table -->
            <div class="table-container">
                <h5 class="mb-4"><i class="fas fa-history me-2"></i>Transaction History</h5>
                
                <?php if ($income_history && mysqli_num_rows($income_history) > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Date & Time</th>
                                    <th>User</th>
                                    <th>Type</th>
                                    <th>Description</th>
                                    <th>Amount</th>
                                    <th>Transaction ID</th>
                                    <th>Reference</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($row = mysqli_fetch_assoc($income_history)): ?>
                                <tr>
                                    <td>
                                        <span class="fw-bold">#<?php echo $row['id']; ?></span>
                                    </td>
                                    <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 if ($row['credit_debit'] == 1): ?>
                                            <span class="badge-income credit">Credit</span>
                                        <?php else: ?>
                                            <span class="badge-income debit">Debit</span>
                                        <?php endif; ?>
                                        <br>
                                        <span class="badge-type mt-1"><?php echo ucwords(str_replace('_', ' ', $row['income_type'] ?: 'N/A')); ?></span>
                                    </td>
                                    <td>
                                        <div><?php echo htmlspecialchars($row['description']); ?></div>
                                        <?php if ($row['level']): ?>
                                            <small class="text-muted">Level <?php echo $row['level']; ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($row['credit_debit'] == 1): ?>
                                            <span class="amount-positive">+ ₹<?php echo number_format($row['amount'], 2); ?></span>
                                        <?php else: ?>
                                            <span class="amount-negative">- ₹<?php echo number_format($row['amount'], 2); ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="transaction-id"><?php echo $row['transaction_id'] ?: 'N/A'; ?></span>
                                    </td>
                                    <td>
                                        <?php if ($row['from_user_id']): ?>
                                            <div><small>From:</small> <?php echo $row['from_user_id']; ?></div>
                                            <small class="text-muted"><?php echo htmlspecialchars($row['from_user_name']); ?></small>
                                        <?php elseif ($row['to_user_id']): ?>
                                            <div><small>To:</small> <?php echo $row['to_user_id']; ?></div>
                                            <small class="text-muted"><?php echo htmlspecialchars($row['to_user_name']); ?></small>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 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; ?>&credit_debit=<?php echo $credit_debit_filter; ?>&income_type=<?php echo $income_type_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
                                    <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; ?>&credit_debit=<?php echo $credit_debit_filter; ?>&income_type=<?php echo $income_type_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
                                        <?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; ?>&credit_debit=<?php echo $credit_debit_filter; ?>&income_type=<?php echo $income_type_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            </li>
                        </ul>
                    </nav>
                    <?php endif; ?>
                    
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-receipt"></i>
                        <h5>No Transactions Found</h5>
                        <p class="text-muted">No income history matches your criteria.</p>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Income Type Breakdown -->
            <div class="type-chart-card">
                <h5 class="mb-3"><i class="fas fa-chart-pie me-2"></i>Income Type Breakdown</h5>
                
                <div class="row">
                    <div class="col-md-8">
                        <div class="chart-container" style="height: 250px;">
                            <canvas id="typeChart"></canvas>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <?php foreach ($type_stats as $type): ?>
                            <div class="type-item">
                                <div class="type-icon <?php 
                                    $icon_class = 'level';
                                    if (strpos($type['income_type'], 'referral') !== false) $icon_class = 'referral';
                                    elseif (strpos($type['income_type'], 'withdrawal') !== false) $icon_class = 'withdrawal';
                                    elseif (strpos($type['income_type'], 'pair') !== false) $icon_class = 'pair';
                                    elseif (strpos($type['income_type'], 'pin') !== false) $icon_class = 'pin';
                                    echo $icon_class;
                                ?>">
                                    <i class="fas fa-<?php 
                                        if ($icon_class == 'level') echo 'layers';
                                        elseif ($icon_class == 'referral') echo 'users';
                                        elseif ($icon_class == 'withdrawal') echo 'hand-holding-usd';
                                        elseif ($icon_class == 'pair') echo 'handshake';
                                        elseif ($icon_class == 'pin') echo 'key';
                                        else echo 'circle';
                                    ?>"></i>
                                </div>
                                <div class="flex-grow-1">
                                    <div class="fw-bold"><?php echo ucwords(str_replace('_', ' ', $type['income_type'])); ?></div>
                                    <small class="text-muted"><?php echo $type['count']; ?> transactions</small>
                                </div>
                                <div class="text-end">
                                    <div class="fw-bold">₹<?php echo number_format($type['total'], 2); ?></div>
                                </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 src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    
    <script>
    // Initialize Select2
    $(document).ready(function() {
        $('.user-select').select2({
            theme: 'bootstrap-5',
            placeholder: 'Search for a user...',
            allowClear: true,
            width: '100%'
        });
    });
    
    // Income Chart
    const ctx = document.getElementById('incomeChart').getContext('2d');
    const chartData = <?php echo json_encode($chart_data); ?>;
    
    const labels = chartData.map(item => moment(item.date).format('MMM DD'));
    const creditData = chartData.map(item => item.credit || 0);
    const debitData = chartData.map(item => item.debit || 0);
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Credits (Income)',
                    data: creditData,
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'Debits (Withdrawals)',
                    data: debitData,
                    borderColor: '#dc3545',
                    backgroundColor: 'rgba(220, 53, 69, 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();
                        }
                    }
                }
            }
        }
    });
    
    // Type Chart
    const typeCtx = document.getElementById('typeChart').getContext('2d');
    const typeStats = <?php echo json_encode($type_stats); ?>;
    
    new Chart(typeCtx, {
        type: 'doughnut',
        data: {
            labels: typeStats.map(item => item.income_type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())),
            datasets: [{
                data: typeStats.map(item => item.total),
                backgroundColor: [
                    '#4154f1',
                    '#28a745',
                    '#ffc107',
                    '#dc3545',
                    '#6f42c1',
                    '#fd7e14',
                    '#20c997',
                    '#17a2b8'
                ],
                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); ?>