<?php
/**
 * Contribution Reports
 * Generate contribution reports for employer
 * 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'];
$date_from = $_GET['date_from'] ?? date('Y-m-01', strtotime('-6 months'));
$date_to = $_GET['date_to'] ?? date('Y-m-t');
$scheme_id = $_GET['scheme_id'] ?? '';

$where = ["c.employer_id = $employer_id"];
$params = [];
$types = '';

$where[] = "DATE(c.contribution_period) BETWEEN ? AND ?";
$params[] = $date_from;
$params[] = $date_to;
$types .= 'ss';

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

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

$sql = "SELECT c.*, m.member_number, m.first_name, m.last_name, ps.scheme_name
        FROM contributions c
        INNER JOIN members m ON c.member_id = m.member_id
        LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id
        WHERE $whereClause
        ORDER BY c.contribution_period DESC, m.member_number";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$contributions = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Calculate totals
$total_employee = 0;
$total_employer = 0;
foreach ($contributions as $contrib) {
    if ($contrib['contribution_type'] === 'EMPLOYEE') {
        $total_employee += $contrib['contribution_amount'];
    } elseif ($contrib['contribution_type'] === 'EMPLOYER') {
        $total_employer += $contrib['contribution_amount'];
    }
}

$schemes = $conn->query("SELECT DISTINCT ps.scheme_id, ps.scheme_name 
                        FROM pension_schemes ps
                        INNER JOIN members m ON ps.scheme_id = m.scheme_id
                        WHERE m.employer_id = $employer_id")->fetch_all(MYSQLI_ASSOC);

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Contribution Reports')); ?>
    <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 Reports</h2>
                                <p>Generate and view contribution reports</p>
                            </div>
                        </div>
                    </div>

                    <div class="metrics-row">
                        <div class="metric-card contributions">
                            <div class="metric-header">
                                <h6 class="metric-title">Employee Contributions</h6>
                                <span class="metric-icon"><i class="ri-user-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_employee, 0); ?></div>
                        </div>

                        <div class="metric-card balances">
                            <div class="metric-header">
                                <h6 class="metric-title">Employer Contributions</h6>
                                <span class="metric-icon"><i class="ri-building-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_employer, 0); ?></div>
                        </div>

                        <div class="metric-card withdrawals">
                            <div class="metric-header">
                                <h6 class="metric-title">Total Contributions</h6>
                                <span class="metric-icon"><i class="ri-file-add-line"></i></span>
                            </div>
                            <div class="metric-value">KES <?php echo number_format($total_employee + $total_employer, 0); ?></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 ($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>
                                <input type="date" name="date_from" class="form-control" style="width: auto;" value="<?php echo $date_from; ?>">
                                <input type="date" name="date_to" class="form-control" style="width: auto;" value="<?php echo $date_to; ?>">
                                <button type="submit" class="btn btn-primary">Filter</button>
                                <button type="button" onclick="window.print()" class="btn btn-success">
                                    <i class="ri-printer-line me-2"></i>Print
                                </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">Contribution Details</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Period</th>
                                                    <th>Member</th>
                                                    <th>Scheme</th>
                                                    <th>Type</th>
                                                    <th>Amount (KES)</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($contributions)): ?>
                                                    <tr><td colspan="6" class="text-center">No contributions found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($contributions as $contrib): ?>
                                                        <tr>
                                                            <td><?php echo date('M Y', strtotime($contrib['contribution_period'])); ?></td>
                                                            <td><?php echo htmlspecialchars($contrib['member_number'] . ' - ' . $contrib['first_name'] . ' ' . $contrib['last_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($contrib['scheme_name'] ?? 'N/A'); ?></td>
                                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($contrib['contribution_type']); ?></span></td>
                                                            <td><strong>KES <?php echo number_format($contrib['contribution_amount'], 2); ?></strong></td>
                                                            <td><span class="status-badge status-<?php echo strtolower($contrib['status']); ?>"><?php echo htmlspecialchars($contrib['status']); ?></span></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>
