<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get contributor ID
$contributor_id = $_GET['id'] ?? '';
if (!$contributor_id) {
    header('Location: list_contributors.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

// Fetch contributor details
$contributor_query = "SELECT c.*, 
                     (SELECT COUNT(*) FROM fund_transactions ft WHERE ft.contributor_id = c.contributor_id) as total_transactions,
                     (SELECT COUNT(DISTINCT ft.fund_id) FROM fund_transactions ft WHERE ft.contributor_id = c.contributor_id) as funds_involved,
                     (SELECT MAX(transaction_date) FROM fund_transactions ft WHERE ft.contributor_id = c.contributor_id) as last_transaction_date,
                     (SELECT COUNT(*) FROM fund_transactions ft WHERE ft.contributor_id = c.contributor_id AND ft.transaction_type = 'CONTRIBUTION') as total_contributions_count,
                     (SELECT COUNT(*) FROM fund_transactions ft WHERE ft.contributor_id = c.contributor_id AND ft.transaction_type = 'WITHDRAWAL') as total_withdrawals_count
                     FROM contributors c 
                     WHERE c.contributor_id = ?";
$stmt = $conn->prepare($contributor_query);
$stmt->bind_param("i", $contributor_id);
$stmt->execute();
$contributor = $stmt->get_result()->fetch_assoc();

if (!$contributor) {
    header('Location: list_contributors.php?error=contributor_not_found');
    exit();
}

// Get transaction history
$transactions_query = "SELECT ft.*, f.fund_name, u.full_name as processed_by_name
                      FROM fund_transactions ft
                      LEFT JOIN funds f ON ft.fund_id = f.fund_id
                      LEFT JOIN users u ON ft.processed_by = u.user_id
                      WHERE ft.contributor_id = ?
                      ORDER BY ft.transaction_date DESC, ft.created_at DESC
                      LIMIT 50";
$stmt_trans = $conn->prepare($transactions_query);
$stmt_trans->bind_param("i", $contributor_id);
$stmt_trans->execute();
$transactions = $stmt_trans->get_result();

// Get fund participation summary
$fund_summary_query = "SELECT f.fund_name, f.fund_id,
                      SUM(CASE WHEN ft.transaction_type = 'CONTRIBUTION' THEN ft.amount ELSE 0 END) as total_contributed,
                      SUM(CASE WHEN ft.transaction_type = 'WITHDRAWAL' THEN ft.amount ELSE 0 END) as total_withdrawn,
                      COUNT(*) as transaction_count,
                      MAX(ft.transaction_date) as last_transaction
                      FROM fund_transactions ft
                      JOIN funds f ON ft.fund_id = f.fund_id
                      WHERE ft.contributor_id = ?
                      GROUP BY f.fund_id, f.fund_name
                      ORDER BY total_contributed DESC";
$stmt_funds = $conn->prepare($fund_summary_query);
$stmt_funds->bind_param("i", $contributor_id);
$stmt_funds->execute();
$fund_participations = $stmt_funds->get_result();

// Calculate monthly activity for chart
$monthly_activity_query = "SELECT 
                          DATE_FORMAT(transaction_date, '%Y-%m') as month,
                          SUM(CASE WHEN transaction_type = 'CONTRIBUTION' THEN amount ELSE 0 END) as contributions,
                          SUM(CASE WHEN transaction_type = 'WITHDRAWAL' THEN amount ELSE 0 END) as withdrawals
                          FROM fund_transactions 
                          WHERE contributor_id = ? 
                          AND transaction_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
                          GROUP BY DATE_FORMAT(transaction_date, '%Y-%m')
                          ORDER BY month";
$stmt_monthly = $conn->prepare($monthly_activity_query);
$stmt_monthly->bind_param("i", $contributor_id);
$stmt_monthly->execute();
$monthly_activity = $stmt_monthly->get_result();

// Get available funds for withdrawal
$available_funds_query = "SELECT f.fund_id, f.fund_name, f.current_balance 
                         FROM funds f 
                         WHERE f.is_active = 1 AND f.current_balance > 0
                         ORDER BY f.fund_name";
$available_funds = $conn->query($available_funds_query);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Contributor Profile - Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .profile-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .contributor-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: #059669;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 1.5rem;
            margin-right: 1.5rem;
        }
        
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-completed { background: #dcfce7; color: #166534; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        .status-failed { background: #fee2e2; color: #991b1b; }
        
        .transaction-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .transaction-contribution { background: #dcfce7; color: #166534; }
        .transaction-withdrawal { background: #fee2e2; color: #991b1b; }
        .transaction-transfer-in { background: #ddd6fe; color: #5b21b6; }
        .transaction-transfer-out { background: #fef3c7; color: #92400e; }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-danger {
            background: #dc2626;
            color: white;
        }
        
        .btn-danger:hover {
            background: #b91c1c;
            color: white;
        }
        
        .btn-success {
            background: #059669;
            color: white;
        }
        
        .btn-success:hover {
            background: #047857;
            color: white;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            color: white;
        }
        
        .btn-warning {
            background: #d97706;
            color: white;
        }
        
        .btn-warning:hover {
            background: #b45309;
            color: white;
        }
        
        .btn-outline-secondary {
            background: transparent;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .btn-outline-secondary:hover {
            background: #f8fafc;
            border-color: #64748b;
            color: #64748b;
        }
        
        .trust-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .trust-high { background: #dcfce7; color: #166534; }
        .trust-medium { background: #fef3c7; color: #92400e; }
        .trust-low { background: #fee2e2; color: #991b1b; }
        
        .quick-actions {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
            flex-wrap: wrap;
        }
        
        .chart-container {
            height: 300px;
            margin: 1rem 0;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }
        
        .info-item {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-label {
            font-weight: 500;
            color: #64748b;
        }
        
        .info-value {
            font-weight: 600;
            color: #1e293b;
        }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .quick-actions {
                flex-direction: column;
            }
            
            .contributor-avatar {
                width: 60px;
                height: 60px;
                font-size: 1.25rem;
                margin-right: 1rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex align-items-center">
                            <div class="contributor-avatar">
                                <?php echo strtoupper(substr($contributor['first_name'], 0, 1) . substr($contributor['last_name'], 0, 1)); ?>
                            </div>
                            <div>
                                <h1 class="page-title"><?php echo htmlspecialchars($contributor['first_name'] . ' ' . $contributor['last_name']); ?></h1>
                                <p class="page-subtitle">
                                    <?php echo htmlspecialchars($contributor['contributor_number']); ?> • 
                                    <?php echo ucfirst(str_replace('_', ' ', strtolower($contributor['relationship']))); ?>
                                    <?php if ($contributor['relationship_details']): ?>
                                        (<?php echo htmlspecialchars($contributor['relationship_details']); ?>)
                                    <?php endif; ?>
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="quick-actions">
                        <a href="process_withdrawal.php?contributor_id=<?php echo $contributor['contributor_id']; ?>" class="btn btn-danger">
                            <i class="ph-arrow-down-left me-2"></i>Process Withdrawal
                        </a>
                        <a href="record_contribution.php?contributor_id=<?php echo $contributor['contributor_id']; ?>" class="btn btn-success">
                            <i class="ph-arrow-up-right me-2"></i>Record Contribution
                        </a>
                        <a href="edit_contributor.php?id=<?php echo $contributor['contributor_id']; ?>" class="btn btn-warning">
                            <i class="ph-pencil me-2"></i>Edit Profile
                        </a>
                        <a href="list_contributors.php" class="btn btn-outline-secondary">
                            <i class="ph-arrow-left me-2"></i>Back to List
                        </a>
                    </div>

                    <!-- Statistics Row -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($contributor['total_contributed']); ?></div>
                            <div class="stat-label">Total Contributed</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($contributor['total_withdrawn']); ?></div>
                            <div class="stat-label">Total Withdrawn</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($contributor['current_balance']); ?></div>
                            <div class="stat-label">Current Balance</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $contributor['total_transactions']; ?></div>
                            <div class="stat-label">Total Transactions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $contributor['funds_involved']; ?></div>
                            <div class="stat-label">Funds Involved</div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Contributor Details -->
                        <div class="col-md-4">
                            <div class="profile-card">
                                <h3 class="mb-3">Contact Information</h3>
                                
                                <div class="info-item">
                                    <span class="info-label">Full Name:</span>
                                    <span class="info-value">
                                        <?php echo htmlspecialchars($contributor['first_name'] . ' ' . $contributor['middle_name'] . ' ' . $contributor['last_name']); ?>
                                    </span>
                                </div>
                                
                                <div class="info-item">
                                    <span class="info-label">Primary Phone:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($contributor['phone_primary']); ?></span>
                                </div>
                                
                                <?php if ($contributor['phone_secondary']): ?>
                                <div class="info-item">
                                    <span class="info-label">Secondary Phone:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($contributor['phone_secondary']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($contributor['email']): ?>
                                <div class="info-item">
                                    <span class="info-label">Email:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($contributor['email']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <div class="info-item">
                                    <span class="info-label">Trust Level:</span>
                                    <span class="info-value">
                                        <span class="trust-badge trust-<?php echo strtolower($contributor['trust_level']); ?>">
                                            <?php echo ucfirst(strtolower($contributor['trust_level'])); ?>
                                        </span>
                                    </span>
                                </div>
                                
                                <div class="info-item">
                                    <span class="info-label">Status:</span>
                                    <span class="info-value">
                                        <span class="status-badge <?php echo $contributor['is_active'] ? 'status-completed' : 'status-cancelled'; ?>">
                                            <?php echo $contributor['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </span>
                                </div>
                                
                                <div class="info-item">
                                    <span class="info-label">Member Since:</span>
                                    <span class="info-value"><?php echo date('M j, Y', strtotime($contributor['created_at'])); ?></span>
                                </div>
                                
                                <?php if ($contributor['last_transaction_date']): ?>
                                <div class="info-item">
                                    <span class="info-label">Last Activity:</span>
                                    <span class="info-value"><?php echo date('M j, Y', strtotime($contributor['last_transaction_date'])); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Banking Information -->
                            <?php if ($contributor['bank_name'] || $contributor['mpesa_number']): ?>
                            <div class="profile-card">
                                <h3 class="mb-3">Banking Information</h3>
                                
                                <?php if ($contributor['bank_name']): ?>
                                <div class="info-item">
                                    <span class="info-label">Bank:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($contributor['bank_name']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($contributor['bank_account']): ?>
                                <div class="info-item">
                                    <span class="info-label">Account:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($contributor['bank_account']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($contributor['mpesa_number']): ?>
                                <div class="info-item">
                                    <span class="info-label">M-Pesa:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($contributor['mpesa_number']); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </div>

                        <!-- Activity and Charts -->
                        <div class="col-md-8">
                            <!-- Monthly Activity Chart -->
                            <div class="table-card">
                                <div class="table-header">
                                    <h3 class="table-title">Monthly Activity (Last 12 Months)</h3>
                                </div>
                                <div style="padding: 1.5rem;">
                                    <div class="chart-container">
                                        <canvas id="activityChart"></canvas>
                                    </div>
                                </div>
                            </div>

                            <!-- Fund Participation Summary -->
                            <div class="table-card">
                                <div class="table-header">
                                    <h3 class="table-title">Fund Participation Summary</h3>
                                </div>
                                
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th>Fund Name</th>
                                            <th>Contributed</th>
                                            <th>Withdrawn</th>
                                            <th>Net Balance</th>
                                            <th>Transactions</th>
                                            <th>Last Activity</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($fund_participations->num_rows > 0): ?>
                                            <?php while ($fund = $fund_participations->fetch_assoc()): ?>
                                            <tr>
                                                <td>
                                                    <span style="font-weight: 600; color: #1e293b;">
                                                        <?php echo htmlspecialchars($fund['fund_name']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span style="color: #059669; font-weight: 500;">
                                                        KES <?php echo number_format($fund['total_contributed']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span style="color: #dc2626; font-weight: 500;">
                                                        KES <?php echo number_format($fund['total_withdrawn']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php $net = $fund['total_contributed'] - $fund['total_withdrawn']; ?>
                                                    <span style="color: <?php echo $net >= 0 ? '#059669' : '#dc2626'; ?>; font-weight: 600;">
                                                        KES <?php echo number_format($net); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo $fund['transaction_count']; ?></td>
                                                <td><?php echo date('M j, Y', strtotime($fund['last_transaction'])); ?></td>
                                                <td>
                                                    <a href="process_withdrawal.php?contributor_id=<?php echo $contributor['contributor_id']; ?>&fund_id=<?php echo $fund['fund_id']; ?>" 
                                                       class="btn btn-danger btn-sm">
                                                        Withdraw
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="7" class="text-center" style="padding: 2rem;">
                                                    No fund participation records found.
                                                </td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Transaction History -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Recent Transaction History</h3>
                            <a href="contributor_transactions.php?id=<?php echo $contributor['contributor_id']; ?>" class="btn btn-primary">
                                View All Transactions
                            </a>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Transaction #</th>
                                    <th>Fund</th>
                                    <th>Type</th>
                                    <th>Amount</th>
                                    <th>Payment Method</th>
                                    <th>Status</th>
                                    <th>Processed By</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($transactions->num_rows > 0): ?>
                                    <?php while ($transaction = $transactions->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo date('M j, Y', strtotime($transaction['transaction_date'])); ?></td>
                                        <td>
                                            <span style="font-family: monospace; font-weight: 600;">
                                                <?php echo htmlspecialchars($transaction['transaction_number']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($transaction['fund_name']); ?></td>
                                        <td>
                                            <?php 
                                            $type_class = match($transaction['transaction_type']) {
                                                'CONTRIBUTION' => 'transaction-contribution',
                                                'WITHDRAWAL' => 'transaction-withdrawal',
                                                'TRANSFER_IN' => 'transaction-transfer-in',
                                                'TRANSFER_OUT' => 'transaction-transfer-out',
                                                default => 'transaction-contribution'
                                            };
                                            ?>
                                            <span class="transaction-badge <?php echo $type_class; ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', strtolower($transaction['transaction_type']))); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span style="font-weight: 600; color: <?php echo $transaction['transaction_type'] == 'WITHDRAWAL' ? '#dc2626' : '#059669'; ?>;">
                                                <?php echo $transaction['transaction_type'] == 'WITHDRAWAL' ? '-' : '+'; ?>KES <?php echo number_format($transaction['amount']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo ucfirst(str_replace('_', ' ', strtolower($transaction['payment_method']))); ?></td>
                                        <td>
                                            <?php 
                                            $status_class = match($transaction['status']) {
                                                'COMPLETED' => 'status-completed',
                                                'PENDING' => 'status-pending',
                                                'CANCELLED' => 'status-cancelled',
                                                'FAILED' => 'status-failed',
                                                default => 'status-pending'
                                            };
                                            ?>
                                            <span class="status-badge <?php echo $status_class; ?>">
                                                <?php echo ucfirst(strtolower($transaction['status'])); ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($transaction['processed_by_name'] ?? 'System'); ?></td>
                                    </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="8" class="text-center" style="padding: 3rem;">
                                            <div style="color: #64748b;">
                                                <i class="ph-currency-circle-dollar" style="font-size: 3rem; margin-bottom: 1rem; display: block;"></i>
                                                <h4>No transactions found</h4>
                                                <p>This contributor hasn't made any transactions yet.</p>
                                                <a href="record_contribution.php?contributor_id=<?php echo $contributor['contributor_id']; ?>" class="btn btn-success mt-2">
                                                    Record First Contribution
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        // Prepare chart data
        const monthlyData = <?php 
            $monthly_activity->data_seek(0);
            $chartData = [];
            while ($row = $monthly_activity->fetch_assoc()) {
                $chartData[] = [
                    'month' => $row['month'],
                    'contributions' => floatval($row['contributions']),
                    'withdrawals' => floatval($row['withdrawals'])
                ];
            }
            echo json_encode($chartData);
        ?>;

        // Create activity chart
        const ctx = document.getElementById('activityChart').getContext('2d');
        const activityChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: monthlyData.map(d => {
                    const date = new Date(d.month + '-01');
                    return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
                }),
                datasets: [{
                    label: 'Contributions',
                    data: monthlyData.map(d => d.contributions),
                    borderColor: '#059669',
                    backgroundColor: 'rgba(5, 150, 105, 0.1)',
                    tension: 0.4,
                    fill: true
                }, {
                    label: 'Withdrawals',
                    data: monthlyData.map(d => d.withdrawals),
                    borderColor: '#dc2626',
                    backgroundColor: 'rgba(220, 38, 38, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'KES ' + value.toLocaleString();
                            }
                        }
                    }
                },
                elements: {
                    point: {
                        radius: 4,
                        hoverRadius: 6
                    }
                }
            }
        });

        $(document).ready(function() {
            // Add confirmation for withdrawal buttons
            $('.btn-danger').on('click', function(e) {
                if ($(this).text().trim().includes('Withdraw')) {
                    const fundName = $(this).closest('tr').find('td:first').text().trim();
                    if (!confirm(`Are you sure you want to process a withdrawal from ${fundName}?`)) {
                        e.preventDefault();
                    }
                }
            });
        });
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>