<?php
/**
 * Employee Statements
 * Generate statements 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'];
$member_id = $_GET['member_id'] ?? '';
$period_start = $_GET['period_start'] ?? date('Y-m-01', strtotime('-1 year'));
$period_end = $_GET['period_end'] ?? date('Y-m-t');

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

$statement_data = null;
if ($member_id && $_GET['action'] === 'generate') {
    $member = $conn->query("SELECT m.*, ps.scheme_name, ps.scheme_code
                           FROM members m
                           LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id
                           WHERE m.member_id = $member_id AND m.employer_id = $employer_id")->fetch_assoc();
    
    if ($member) {
        $account = $conn->query("SELECT * FROM member_accounts WHERE member_id = $member_id")->fetch_assoc();
        $contributions = $conn->query("SELECT * FROM contributions 
                                      WHERE member_id = $member_id 
                                      AND DATE(contribution_period) BETWEEN '$period_start' AND '$period_end'
                                      ORDER BY contribution_period DESC")->fetch_all(MYSQLI_ASSOC);
        
        $statement_data = [
            'member' => $member,
            'account' => $account,
            'contributions' => $contributions
        ];
    }
}

$pageTitle = 'Employee Statements';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Employee Statements')); ?>
    <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>Employee Statements</h2>
                                <p>Generate pension statements for your employees</p>
                            </div>
                        </div>
                    </div>

                    <?php if (!$statement_data): ?>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Generate Statement</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="GET">
                                            <input type="hidden" name="action" value="generate">
                                            <div class="mb-3">
                                                <label class="form-label">Employee</label>
                                                <select name="member_id" class="form-select" required>
                                                    <option value="">Select Employee</option>
                                                    <?php foreach ($employees as $emp): ?>
                                                        <option value="<?php echo $emp['member_id']; ?>">
                                                            <?php echo htmlspecialchars($emp['member_number'] . ' - ' . $emp['first_name'] . ' ' . $emp['last_name']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Period Start</label>
                                                    <input type="date" name="period_start" class="form-control" value="<?php echo $period_start; ?>">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Period End</label>
                                                    <input type="date" name="period_end" class="form-control" value="<?php echo $period_end; ?>">
                                                </div>
                                            </div>
                                            
                                            <button type="submit" class="btn btn-primary w-100">
                                                <i class="ri-file-chart-line me-2"></i>Generate Statement
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row mb-3">
                            <div class="col-12">
                                <a href="employee_statements.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-2"></i>Back
                                </a>
                                <button onclick="window.print()" class="btn btn-success">
                                    <i class="ri-printer-line me-2"></i>Print
                                </button>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Pension Statement - <?php echo htmlspecialchars($statement_data['member']['member_number']); ?></h4>
                                    </div>
                                    <div class="page-card-body">
                                        <div class="mb-4">
                                            <h5>Member Information</h5>
                                            <table class="table table-borderless">
                                                <tr>
                                                    <td><strong>Member Number:</strong></td>
                                                    <td><?php echo htmlspecialchars($statement_data['member']['member_number']); ?></td>
                                                    <td><strong>Scheme:</strong></td>
                                                    <td><?php echo htmlspecialchars($statement_data['member']['scheme_name'] ?? 'N/A'); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Name:</strong></td>
                                                    <td><?php echo htmlspecialchars($statement_data['member']['first_name'] . ' ' . $statement_data['member']['last_name']); ?></td>
                                                    <td><strong>Statement Period:</strong></td>
                                                    <td><?php echo date('d M Y', strtotime($period_start)); ?> to <?php echo date('d M Y', strtotime($period_end)); ?></td>
                                                </tr>
                                            </table>
                                        </div>
                                        
                                        <div class="mb-4">
                                            <h5>Account Summary</h5>
                                            <table class="table table-bordered">
                                                <tr>
                                                    <td><strong>Employee Contributions:</strong></td>
                                                    <td class="text-end">KES <?php echo number_format($statement_data['account']['total_employee_contributions'] ?? 0, 2); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Employer Contributions:</strong></td>
                                                    <td class="text-end">KES <?php echo number_format($statement_data['account']['total_employer_contributions'] ?? 0, 2); ?></td>
                                                </tr>
                                                <tr>
                                                    <td><strong>Investment Returns:</strong></td>
                                                    <td class="text-end">KES <?php echo number_format($statement_data['account']['allocated_investment_returns'] ?? 0, 2); ?></td>
                                                </tr>
                                                <tr class="table-primary">
                                                    <td><strong>Available Balance:</strong></td>
                                                    <td class="text-end"><strong>KES <?php echo number_format($statement_data['account']['available_balance'] ?? 0, 2); ?></strong></td>
                                                </tr>
                                            </table>
                                        </div>
                                        
                                        <div class="mb-4">
                                            <h5>Contributions</h5>
                                            <div class="table-responsive">
                                                <table class="data-table">
                                                    <thead>
                                                        <tr>
                                                            <th>Period</th>
                                                            <th>Type</th>
                                                            <th>Amount (KES)</th>
                                                            <th>Status</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php if (empty($statement_data['contributions'])): ?>
                                                            <tr><td colspan="4" class="text-center">No contributions in this period</td></tr>
                                                        <?php else: ?>
                                                            <?php foreach ($statement_data['contributions'] as $contrib): ?>
                                                                <tr>
                                                                    <td><?php echo date('M Y', strtotime($contrib['contribution_period'])); ?></td>
                                                                    <td><?php echo htmlspecialchars($contrib['contribution_type']); ?></td>
                                                                    <td>KES <?php echo number_format($contrib['contribution_amount'], 2); ?></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>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
