<?php
/**
 * Contribution Schedule
 * View contribution schedule for employer's employees
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
if (!isEmployer()) {
    header('Location: access_denied.php');
    exit();
}

$employer_id = $_SESSION['employer_id'] ?? $_SESSION['user_id'];
$period = $_GET['period'] ?? date('Y-m');

// Get employees (members) for this employer
$employees = $conn->query("SELECT m.*, ps.scheme_name, ma.accrued_benefits
                          FROM members m
                          LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id
                          LEFT JOIN member_accounts ma ON m.member_id = ma.member_id
                          WHERE m.employer_id = $employer_id AND m.is_active = 1
                          ORDER BY m.member_number")->fetch_all(MYSQLI_ASSOC);

// Get contributions for the period
$contributions = [];
if (!empty($employees)) {
    $member_ids = array_column($employees, 'member_id');
    $placeholders = implode(',', array_fill(0, count($member_ids), '?'));
    $sql = "SELECT * FROM contributions 
            WHERE member_id IN ($placeholders) 
            AND DATE_FORMAT(contribution_period, '%Y-%m') = ?";
    $stmt = $conn->prepare($sql);
    $params = array_merge($member_ids, [$period]);
    $types = str_repeat('i', count($member_ids)) . 's';
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $contributions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
    // Index by member_id and type
    $contributions_indexed = [];
    foreach ($contributions as $contrib) {
        $key = $contrib['member_id'] . '_' . $contrib['contribution_type'];
        $contributions_indexed[$key] = $contrib;
    }
}

$pageTitle = 'Contribution Schedule';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Contribution Schedule')); ?>
    <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>Contribution Schedule</h2>
                                <p>View contribution schedule for your employees</p>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <form method="GET" class="d-inline-flex gap-2">
                                <input type="month" name="period" class="form-control" style="width: auto;" value="<?php echo $period; ?>">
                                <button type="submit" class="btn btn-primary">View Schedule</button>
                                <a href="contributions.php?action=create" class="btn btn-success">
                                    <i class="ri-file-add-line me-2"></i>Post Contributions
                                </a>
                            </form>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Contribution Schedule - <?php echo date('F Y', strtotime($period . '-01')); ?></h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Member Number</th>
                                                    <th>Name</th>
                                                    <th>Scheme</th>
                                                    <th>Employee Contribution</th>
                                                    <th>Employer Contribution</th>
                                                    <th>Total</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($employees)): ?>
                                                    <tr><td colspan="7" class="text-center">No employees found</td></tr>
                                                <?php else: ?>
                                                    <?php 
                                                    $total_employee = 0;
                                                    $total_employer = 0;
                                                    foreach ($employees as $employee): 
                                                        $emp_key = $employee['member_id'] . '_EMPLOYEE';
                                                        $emp_contrib = $contributions_indexed[$emp_key] ?? null;
                                                        $emp_amount = $emp_contrib ? $emp_contrib['contribution_amount'] : 0;
                                                        
                                                        $emp_key2 = $employee['member_id'] . '_EMPLOYER';
                                                        $emp_contrib2 = $contributions_indexed[$emp_key2] ?? null;
                                                        $emp_amount2 = $emp_contrib2 ? $emp_contrib2['contribution_amount'] : 0;
                                                        
                                                        $total_employee += $emp_amount;
                                                        $total_employer += $emp_amount2;
                                                    ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($employee['member_number']); ?></td>
                                                            <td><?php echo htmlspecialchars($employee['first_name'] . ' ' . $employee['last_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($employee['scheme_name'] ?? 'N/A'); ?></td>
                                                            <td>KES <?php echo number_format($emp_amount, 2); ?></td>
                                                            <td>KES <?php echo number_format($emp_amount2, 2); ?></td>
                                                            <td><strong>KES <?php echo number_format($emp_amount + $emp_amount2, 2); ?></strong></td>
                                                            <td>
                                                                <?php if ($emp_contrib || $emp_contrib2): ?>
                                                                    <span class="status-badge status-processed">Posted</span>
                                                                <?php else: ?>
                                                                    <span class="status-badge status-pending">Pending</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                    <tr class="table-primary">
                                                        <td colspan="3"><strong>Total</strong></td>
                                                        <td><strong>KES <?php echo number_format($total_employee, 2); ?></strong></td>
                                                        <td><strong>KES <?php echo number_format($total_employer, 2); ?></strong></td>
                                                        <td><strong>KES <?php echo number_format($total_employee + $total_employer, 2); ?></strong></td>
                                                        <td></td>
                                                    </tr>
                                                <?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>
