<?php
/**
 * Scheme Balances
 * View scheme-level fund balances
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';

requireLogin();
requirePermission('view_scheme_balances');

$scheme_id = $_GET['scheme_id'] ?? '';

$where = ["ps.is_active = 1"];
$params = [];
$types = '';

if ($scheme_id) {
    $where[] = "ps.scheme_id = ?";
    $params[] = $scheme_id;
    $types .= 'i';
}

$whereClause = implode(' AND ', $where);

$sql = "SELECT ps.scheme_id, ps.scheme_name, ps.scheme_code,
               COUNT(DISTINCT m.member_id) as total_members,
               COUNT(DISTINCT ma.account_id) as active_accounts,
               COALESCE(SUM(ma.accrued_benefits), 0) as total_accrued_benefits,
               COALESCE(SUM(ma.available_balance), 0) as total_available_balance,
               COALESCE(SUM(ma.total_employee_contributions), 0) as total_employee_contributions,
               COALESCE(SUM(ma.total_employer_contributions), 0) as total_employer_contributions,
               COALESCE(SUM(ma.allocated_investment_returns), 0) as total_investment_returns
        FROM pension_schemes ps
        LEFT JOIN members m ON ps.scheme_id = m.scheme_id AND m.is_active = 1
        LEFT JOIN member_accounts ma ON m.member_id = ma.member_id AND ma.account_status = 'ACTIVE'
        WHERE $whereClause
        GROUP BY ps.scheme_id, ps.scheme_name, ps.scheme_code
        ORDER BY ps.scheme_name";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$schemes = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$all_schemes = $conn->query("SELECT scheme_id, scheme_name FROM pension_schemes WHERE is_active = 1")->fetch_all(MYSQLI_ASSOC);

$pageTitle = 'Scheme Balances';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Scheme Balances')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="welcome-header" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Scheme Balances</h2>
                                <p>View scheme-level fund balances and statistics</p>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <form method="GET" class="d-inline-flex gap-2">
                                <select name="scheme_id" class="form-select" style="width: auto;">
                                    <option value="">All Schemes</option>
                                    <?php foreach ($all_schemes as $sch): ?>
                                        <option value="<?php echo $sch['scheme_id']; ?>" <?php echo $scheme_id == $sch['scheme_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($sch['scheme_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="submit" class="btn btn-primary">Filter</button>
                            </form>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Scheme Fund Balances</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Scheme</th>
                                                    <th>Code</th>
                                                    <th>Members</th>
                                                    <th>Employee Contributions</th>
                                                    <th>Employer Contributions</th>
                                                    <th>Investment Returns</th>
                                                    <th>Total Accrued Benefits</th>
                                                    <th>Available Balance</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($schemes)): ?>
                                                    <tr><td colspan="8" class="text-center">No schemes found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($schemes as $scheme): ?>
                                                        <tr>
                                                            <td><strong><?php echo htmlspecialchars($scheme['scheme_name']); ?></strong></td>
                                                            <td><?php echo htmlspecialchars($scheme['scheme_code']); ?></td>
                                                            <td><?php echo $scheme['total_members']; ?></td>
                                                            <td>KES <?php echo number_format($scheme['total_employee_contributions'], 2); ?></td>
                                                            <td>KES <?php echo number_format($scheme['total_employer_contributions'], 2); ?></td>
                                                            <td>KES <?php echo number_format($scheme['total_investment_returns'], 2); ?></td>
                                                            <td><strong>KES <?php echo number_format($scheme['total_accrued_benefits'], 2); ?></strong></td>
                                                            <td><strong style="color: #10b981;">KES <?php echo number_format($scheme['total_available_balance'], 2); ?></strong></td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
