<?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 and is admin
if (!isset($_SESSION['user_id'])) {
    header('Location: login.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();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Check if user is admin
if ($role_name !== 'Administrator') {
    header('Location: index.php');
    exit();
}

// Get system-wide statistics
$system_stats_query = "SELECT 
    (SELECT COUNT(*) FROM funds WHERE is_active = 1) as total_funds,
    (SELECT COUNT(*) FROM contributors WHERE is_active = 1) as total_contributors,
    (SELECT COUNT(*) FROM users WHERE status = 'ACTIVE') as total_users,
    (SELECT COUNT(*) FROM fund_transactions WHERE status = 'COMPLETED') as total_transactions,
    (SELECT SUM(current_balance) FROM funds WHERE is_active = 1) as total_system_balance,
    (SELECT SUM(total_contributions) FROM funds WHERE is_active = 1) as total_contributions,
    (SELECT SUM(total_withdrawals) FROM funds WHERE is_active = 1) as total_withdrawals,
    (SELECT COUNT(*) FROM fund_transactions WHERE status = 'COMPLETED' AND transaction_date >= CURDATE()) as today_transactions,
    (SELECT SUM(amount) FROM fund_transactions WHERE status = 'COMPLETED' AND transaction_type = 'CONTRIBUTION' AND transaction_date >= CURDATE()) as today_contributions,
    (SELECT COUNT(DISTINCT contributor_id) FROM fund_transactions WHERE status = 'COMPLETED' AND transaction_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)) as active_contributors_30d";
$system_stats = $conn->query($system_stats_query)->fetch_assoc();

// Get fund distribution by status
$fund_status_query = "SELECT status, COUNT(*) as count FROM funds WHERE is_active = 1 GROUP BY status";
$fund_status_result = $conn->query($fund_status_query);
$fund_status_data = [];
while ($row = $fund_status_result->fetch_assoc()) {
    $fund_status_data[$row['status']] = $row['count'];
}

// Get transaction volume trends (last 12 months)
$transaction_trends_query = "SELECT 
    DATE_FORMAT(transaction_date, '%Y-%m') as month,
    COUNT(*) as transaction_count,
    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,
    COUNT(DISTINCT contributor_id) as unique_contributors
    FROM fund_transactions 
    WHERE status = 'COMPLETED' 
    AND transaction_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(transaction_date, '%Y-%m')
    ORDER BY month DESC
    LIMIT 12";
$transaction_trends = $conn->query($transaction_trends_query);

// Get contributor growth trends
$contributor_growth_query = "SELECT 
    DATE_FORMAT(created_at, '%Y-%m') as month,
    COUNT(*) as new_contributors
    FROM contributors 
    WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(created_at, '%Y-%m')
    ORDER BY month DESC
    LIMIT 12";
$contributor_growth = $conn->query($contributor_growth_query);

// Get fund performance by category
$category_performance_query = "SELECT 
    fc.category_name,
    fc.color_code,
    COUNT(f.fund_id) as fund_count,
    SUM(f.current_balance) as total_balance,
    SUM(f.total_contributions) as total_contributions,
    AVG(f.current_balance) as avg_balance,
    COUNT(DISTINCT ft.contributor_id) as unique_contributors
    FROM fund_categories fc
    LEFT JOIN funds f ON fc.category_id = f.category_id AND f.is_active = 1
    LEFT JOIN fund_transactions ft ON f.fund_id = ft.fund_id AND ft.status = 'COMPLETED'
    WHERE fc.is_active = 1
    GROUP BY fc.category_id, fc.category_name, fc.color_code
    ORDER BY total_balance DESC";
$category_performance = $conn->query($category_performance_query);

// Get top contributors by total contribution
$top_contributors_query = "SELECT 
    c.contributor_number,
    CONCAT(c.first_name, ' ', c.last_name) as full_name,
    c.relationship,
    c.total_contributed,
    c.total_withdrawn,
    c.current_balance,
    COUNT(DISTINCT ft.fund_id) as funds_involved,
    COUNT(ft.transaction_id) as total_transactions,
    MAX(ft.transaction_date) as last_transaction_date
    FROM contributors c
    LEFT JOIN fund_transactions ft ON c.contributor_id = ft.contributor_id AND ft.status = 'COMPLETED'
    WHERE c.is_active = 1
    GROUP BY c.contributor_id
    ORDER BY c.total_contributed DESC
    LIMIT 10";
$top_contributors = $conn->query($top_contributors_query);

// Get user activity summary
$user_activity_query = "SELECT 
    ur.role_name,
    COUNT(u.user_id) as user_count,
    COUNT(CASE WHEN u.last_login >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) THEN 1 END) as active_week,
    COUNT(CASE WHEN u.last_login >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) THEN 1 END) as active_month
    FROM users u
    JOIN user_roles ur ON u.role_id = ur.role_id
    WHERE u.status = 'ACTIVE'
    GROUP BY ur.role_id, ur.role_name
    ORDER BY user_count DESC";
$user_activity = $conn->query($user_activity_query);

// Get system health indicators
$system_health = [
    'database_size' => 0, // You would calculate this based on your database
    'avg_response_time' => 0.5, // Mock data - you'd implement actual monitoring
    'uptime_percentage' => 99.8, // Mock data
    'error_rate' => 0.1 // Mock data
];

// Get daily activity for the last 30 days
$daily_activity_query = "SELECT 
    DATE(transaction_date) as activity_date,
    COUNT(*) as daily_transactions,
    SUM(amount) as daily_volume,
    COUNT(DISTINCT contributor_id) as daily_contributors
    FROM fund_transactions 
    WHERE status = 'COMPLETED' 
    AND transaction_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY DATE(transaction_date)
    ORDER BY activity_date DESC";
$daily_activity = $conn->query($daily_activity_query);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'System Analytics - Personal Fund Tracker')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        /* Use the same styling from previous pages */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Stats Cards */
        .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;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #6366f1, #8b5cf6);
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .stat-change {
            font-size: 0.75rem;
            margin-top: 0.5rem;
        }
        
        .stat-change.positive { color: #059669; }
        .stat-change.negative { color: #dc2626; }
        
        /* Chart Cards */
        .chart-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;
        }
        
        .chart-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .chart-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .chart-body {
            padding: 1.5rem;
        }
        
        /* Health Indicators */
        .health-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .health-card {
            background: white;
            border-radius: 8px;
            padding: 1rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .health-value {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 0.25rem;
        }
        
        .health-value.good { color: #059669; }
        .health-value.warning { color: #d97706; }
        .health-value.danger { color: #dc2626; }
        
        .health-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
        }
        
        /* Table Card */
        .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;
        }
        
        /* Grid Layouts */
        .grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
        }
        
        .grid-3 {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 2rem;
        }
        
        /* Badges */
        .relationship-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
            text-transform: uppercase;
        }
        
        .relationship-family { background: #dcfce7; color: #166534; }
        .relationship-friend { background: #ddd6fe; color: #5b21b6; }
        .relationship-business { background: #fef3c7; color: #92400e; }
        .relationship-other { background: #f1f5f9; color: #64748b; }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .stats-row, .health-grid {
                grid-template-columns: 1fr;
            }
            
            .grid-2, .grid-3 {
                grid-template-columns: 1fr;
            }
            
            .chart-header {
                flex-direction: column;
                gap: 1rem;
                align-items: stretch;
            }
        }
        
        /* Footer spacing fix */
        .main-content {
            padding-bottom: 2rem;
        }
        
        .page-content {
            margin-bottom: 3rem;
        }
    </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">
                        <h1 class="page-title">System-wide Analytics</h1>
                        <p class="page-subtitle">Comprehensive system performance and health monitoring</p>
                    </div>

                    <!-- System Overview Stats -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($system_stats['total_funds']); ?></div>
                            <div class="stat-label">Active Funds</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($system_stats['total_contributors']); ?></div>
                            <div class="stat-label">Total Contributors</div>
                            <div class="stat-change positive">
                                <?php echo number_format($system_stats['active_contributors_30d']); ?> active this month
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($system_stats['total_system_balance']); ?></div>
                            <div class="stat-label">Total System Balance</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($system_stats['total_transactions']); ?></div>
                            <div class="stat-label">Total Transactions</div>
                            <div class="stat-change positive">
                                <?php echo number_format($system_stats['today_transactions']); ?> today
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($system_stats['total_users']); ?></div>
                            <div class="stat-label">System Users</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">KES <?php echo number_format($system_stats['today_contributions'] ?? 0); ?></div>
                            <div class="stat-label">Today's Contributions</div>
                        </div>
                    </div>

                    <!-- System Health Indicators -->
                    <div class="chart-card">
                        <div class="chart-header">
                            <h3 class="chart-title">System Health Indicators</h3>
                        </div>
                        <div class="chart-body">
                            <div class="health-grid">
                                <div class="health-card">
                                    <div class="health-value good"><?php echo $system_health['uptime_percentage']; ?>%</div>
                                    <div class="health-label">System Uptime</div>
                                </div>
                                <div class="health-card">
                                    <div class="health-value good"><?php echo $system_health['avg_response_time']; ?>s</div>
                                    <div class="health-label">Avg Response Time</div>
                                </div>
                                <div class="health-card">
                                    <div class="health-value good"><?php echo $system_health['error_rate']; ?>%</div>
                                    <div class="health-label">Error Rate</div>
                                </div>
                                <div class="health-card">
                                    <div class="health-value good"><?php echo number_format(($system_stats['total_contributions'] - $system_stats['total_withdrawals']) / max($system_stats['total_contributions'], 1) * 100, 1); ?>%</div>
                                    <div class="health-label">Fund Retention</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Charts Section -->
                    <div class="grid-3">
                        <!-- Transaction Volume Trends -->
                        <div class="chart-card">
                            <div class="chart-header">
                                <h3 class="chart-title">Transaction Volume Trends</h3>
                            </div>
                            <div class="chart-body">
                                <canvas id="transactionTrendsChart" height="300"></canvas>
                            </div>
                        </div>

                        <!-- Fund Status Distribution -->
                        <div class="chart-card">
                            <div class="chart-header">
                                <h3 class="chart-title">Fund Status Distribution</h3>
                            </div>
                            <div class="chart-body">
                                <canvas id="fundStatusChart" height="300"></canvas>
                            </div>
                        </div>
                    </div>

                    <!-- Performance Tables -->
                    <div class="grid-2">
                        <!-- Top Contributors -->
                        <div class="table-card">
                            <div class="table-header">
                                <h3 class="table-title">Top Contributors</h3>
                            </div>
                            
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Contributor</th>
                                        <th>Relationship</th>
                                        <th>Total Contributed</th>
                                        <th>Funds</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($contributor = $top_contributors->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <div style="font-weight: 600; color: #1e293b;">
                                                <?php echo htmlspecialchars($contributor['full_name']); ?>
                                            </div>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                <?php echo htmlspecialchars($contributor['contributor_number']); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php 
                                            $relationship_class = match(strtolower($contributor['relationship'])) {
                                                'family' => 'relationship-family',
                                                'friend' => 'relationship-friend',
                                                'business_partner' => 'relationship-business',
                                                default => 'relationship-other'
                                            };
                                            ?>
                                            <span class="relationship-badge <?php echo $relationship_class; ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', strtolower($contributor['relationship']))); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div style="font-weight: 600; color: #059669;">
                                                KES <?php echo number_format($contributor['total_contributed']); ?>
                                            </div>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                Balance: KES <?php echo number_format($contributor['current_balance']); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div style="font-weight: 500; color: #1e293b;">
                                                <?php echo $contributor['funds_involved']; ?> funds
                                            </div>
                                            <div style="color: #64748b; font-size: 0.75rem;">
                                                <?php echo $contributor['total_transactions']; ?> transactions
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- User Activity Summary -->
                        <div class="table-card">
                            <div class="table-header">
                                <h3 class="table-title">User Activity by Role</h3>
                            </div>
                            
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Role</th>
                                        <th>Total Users</th>
                                        <th>Active (7d)</th>
                                        <th>Active (30d)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($activity = $user_activity->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <div style="font-weight: 600; color: #1e293b;">
                                                <?php echo htmlspecialchars($activity['role_name']); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div style="font-weight: 500; color: #1e293b;">
                                                <?php echo $activity['user_count']; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div style="color: #059669;">
                                                <?php echo $activity['active_week']; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div style="color: #3b82f6;">
                                                <?php echo $activity['active_month']; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Category Performance Overview -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Performance by Fund Category</h3>
                        </div>
                        
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Category</th>
                                    <th>Funds</th>
                                    <th>Total Balance</th>
                                    <th>Total Contributions</th>
                                    <th>Average Fund Size</th>
                                    <th>Contributors</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($category = $category_performance->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center gap-2">
                                            <div style="width: 12px; height: 12px; border-radius: 2px; background-color: <?php echo $category['color_code']; ?>;"></div>
                                            <div style="font-weight: 600; color: #1e293b;">
                                                <?php echo htmlspecialchars($category['category_name']); ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight: 500; color: #1e293b;">
                                            <?php echo $category['fund_count']; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight: 600; color: #1e293b;">
                                            KES <?php echo number_format($category['total_balance'] ?? 0); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="color: #059669;">
                                            KES <?php echo number_format($category['total_contributions'] ?? 0); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="color: #64748b;">
                                            KES <?php echo number_format($category['avg_balance'] ?? 0); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <div style="font-weight: 500; color: #1e293b;">
                                            <?php echo $category['unique_contributors'] ?? 0; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </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>
        // Transaction Trends Chart
        const transactionCtx = document.getElementById('transactionTrendsChart').getContext('2d');
        
        // Prepare transaction trends data
        <?php 
        $months = [];
        $contributions = [];
        $withdrawals = [];
        $transaction_counts = [];
        $transaction_trends->data_seek(0);
        while ($trend = $transaction_trends->fetch_assoc()) {
            $months[] = $trend['month'];
            $contributions[] = $trend['contributions'];
            $withdrawals[] = $trend['withdrawals'];
            $transaction_counts[] = $trend['transaction_count'];
        }
        ?>
        
        const transactionTrendsChart = new Chart(transactionCtx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode(array_reverse($months)); ?>,
                datasets: [
                    {
                        label: 'Contributions',
                        data: <?php echo json_encode(array_reverse($contributions)); ?>,
                        backgroundColor: 'rgba(5, 150, 105, 0.8)',
                        borderColor: '#059669',
                        borderWidth: 1
                    },
                    {
                        label: 'Withdrawals',
                        data: <?php echo json_encode(array_reverse($withdrawals)); ?>,
                        backgroundColor: 'rgba(220, 38, 38, 0.8)',
                        borderColor: '#dc2626',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': KES ' + context.parsed.y.toLocaleString();
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        stacked: false,
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'KES ' + value.toLocaleString();
                            }
                        }
                    }
                }
            }
        });

        // Fund Status Chart
        const statusCtx = document.getElementById('fundStatusChart').getContext('2d');
        
        // Prepare fund status data
        const statusData = {
            'ACTIVE': <?php echo $fund_status_data['ACTIVE'] ?? 0; ?>,
            'CLOSED': <?php echo $fund_status_data['CLOSED'] ?? 0; ?>,
            'SUSPENDED': <?php echo $fund_status_data['SUSPENDED'] ?? 0; ?>,
            'COMPLETED': <?php echo $fund_status_data['COMPLETED'] ?? 0; ?>
        };
        
        const fundStatusChart = new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: Object.keys(statusData),
                datasets: [{
                    data: Object.values(statusData),
                    backgroundColor: [
                        '#059669', // Active - Green
                        '#dc2626', // Closed - Red
                        '#d97706', // Suspended - Orange
                        '#8b5cf6'  // Completed - Purple
                    ],
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            usePointStyle: true
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = context.parsed;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                                return label + ': ' + value + ' (' + percentage + '%)';
                            }
                        }
                    }
                }
            }
        });

        // Auto-refresh system stats every 5 minutes
        setInterval(function() {
            // You can implement AJAX refresh here if needed
            console.log('Auto-refresh system stats...');
        }, 300000); // 5 minutes
    </script>

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

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