<?php
/**
 * Member Balances
 * View member account balances
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_member_balances');

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

$where = ["ma.account_status = 'ACTIVE'"];
$params = [];
$types = '';

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

if ($search) {
    $where[] = "(m.member_number LIKE ? OR m.first_name LIKE ? OR m.last_name LIKE ?)";
    $searchTerm = '%' . $search . '%';
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $types .= 'sss';
}

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

$sql = "SELECT ma.*, m.member_number, m.first_name, m.last_name, ps.scheme_name
        FROM member_accounts ma
        INNER JOIN members m ON ma.member_id = m.member_id
        LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id
        WHERE $whereClause
        ORDER BY ma.accrued_benefits DESC
        LIMIT 100";

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

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

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Member 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>Member Balances</h2>
                                <p>View member pension account balances</p>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Account Balances</h4>
                                </div>
                                <div class="page-card-body">
                                    <form method="GET" class="mb-3">
                                        <div class="row">
                                            <div class="col-md-4 mb-2">
                                                <input type="text" name="search" class="form-control" placeholder="Search member..." value="<?php echo htmlspecialchars($search); ?>">
                                            </div>
                                            <div class="col-md-3 mb-2">
                                                <select name="scheme_id" class="form-select">
                                                    <option value="">All Schemes</option>
                                                    <?php foreach ($schemes as $scheme): ?>
                                                        <option value="<?php echo $scheme['scheme_id']; ?>" <?php echo $scheme_id == $scheme['scheme_id'] ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($scheme['scheme_name']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-2 mb-2">
                                                <button type="submit" class="btn btn-primary w-100">Filter</button>
                                            </div>
                                        </div>
                                    </form>
                                    
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Member</th>
                                                    <th>Scheme</th>
                                                    <th>Employee Contributions</th>
                                                    <th>Employer Contributions</th>
                                                    <th>Investment Returns</th>
                                                    <th>Accrued Benefits</th>
                                                    <th>Available Balance</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($balances)): ?>
                                                    <tr><td colspan="8" class="text-center">No balances found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($balances as $balance): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($balance['member_number'] . ' - ' . $balance['first_name'] . ' ' . $balance['last_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($balance['scheme_name'] ?? 'N/A'); ?></td>
                                                            <td>KES <?php echo number_format($balance['total_employee_contributions'], 2); ?></td>
                                                            <td>KES <?php echo number_format($balance['total_employer_contributions'], 2); ?></td>
                                                            <td>KES <?php echo number_format($balance['allocated_investment_returns'], 2); ?></td>
                                                            <td><strong>KES <?php echo number_format($balance['accrued_benefits'], 2); ?></strong></td>
                                                            <td><strong style="color: #10b981;">KES <?php echo number_format($balance['available_balance'], 2); ?></strong></td>
                                                            <td>
                                                                <a href="member_statements.php?member_id=<?php echo $balance['member_id']; ?>&action=generate" class="btn btn-sm btn-info">
                                                                    <i class="ri-file-text-line"></i>
                                                                </a>
                                                            </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>
