<?php
/**
 * Member Statements
 * Generate and view member pension statements
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_member_statements');

$member_id = $_GET['member_id'] ?? null;
$scheme_id = $_GET['scheme_id'] ?? null;
$period_start = $_GET['period_start'] ?? date('Y-m-01');
$period_end = $_GET['period_end'] ?? date('Y-m-t');

// Get members for filter
$members = $conn->query("SELECT member_id, member_number, first_name, last_name FROM members WHERE is_active = 1 ORDER BY member_number")->fetch_all(MYSQLI_ASSOC);
$schemes = $conn->query("SELECT scheme_id, scheme_name FROM pension_schemes WHERE is_active = 1")->fetch_all(MYSQLI_ASSOC);

$statement_data = null;
if ($member_id && $_GET['action'] === 'generate') {
    // Get member account
    $account = $conn->query("SELECT * FROM member_accounts WHERE member_id = $member_id")->fetch_assoc();
    
    // Get contributions in period
    $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);
    
    // Get withdrawals in period
    $withdrawals = $conn->query("SELECT * FROM withdrawal_requests WHERE member_id = $member_id AND DATE(requested_date) BETWEEN '$period_start' AND '$period_end' ORDER BY requested_date DESC")->fetch_all(MYSQLI_ASSOC);
    
    // Get fund returns allocated in period
    $fund_returns = $conn->query("SELECT mfr.*, fr.return_period_start, fr.return_period_end, fr.return_percentage 
                                  FROM member_fund_returns mfr
                                  INNER JOIN fund_returns fr ON mfr.return_id = fr.return_id
                                  WHERE mfr.member_id = $member_id AND fr.allocation_date BETWEEN '$period_start' AND '$period_end'
                                  ORDER BY fr.allocation_date DESC")->fetch_all(MYSQLI_ASSOC);
    
    $member = $conn->query("SELECT m.*, ps.scheme_name FROM members m LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id WHERE m.member_id = $member_id")->fetch_assoc();
    
    $statement_data = [
        'member' => $member,
        'account' => $account,
        'contributions' => $contributions,
        'withdrawals' => $withdrawals,
        'fund_returns' => $fund_returns,
        'period_start' => $period_start,
        'period_end' => $period_end
    ];
}

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Member 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">
                    <!-- Page Header -->
                    <div class="welcome-header" style="background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Member Statements</h2>
                                <p>Generate and view pension account statements</p>
                            </div>
                        </div>
                    </div>

                    <?php if (!$statement_data): ?>
                        <!-- Statement Generator Form -->
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Generate Member Statement</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="GET">
                                            <input type="hidden" name="action" value="generate">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Member <span class="text-danger">*</span></label>
                                                    <select name="member_id" class="form-select" required>
                                                        <option value="">Select Member</option>
                                                        <?php foreach ($members as $m): ?>
                                                            <option value="<?php echo $m['member_id']; ?>" <?php echo $member_id == $m['member_id'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($m['member_number'] . ' - ' . $m['first_name'] . ' ' . $m['last_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Period Start</label>
                                                    <input type="date" name="period_start" class="form-control" value="<?php echo $period_start; ?>" required>
                                                </div>
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Period End</label>
                                                    <input type="date" name="period_end" class="form-control" value="<?php echo $period_end; ?>" required>
                                                </div>
                                            </div>
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-file-text-line me-2"></i>Generate Statement
                                            </button>
                                            <a href="member_statements.php" class="btn btn-secondary">Reset</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <!-- Statement Display -->
                        <div class="row mb-3">
                            <div class="col-12">
                                <a href="member_statements.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-2"></i>Back to Generator
                                </a>
                                <button onclick="window.print()" class="btn btn-primary">
                                    <i class="ri-printer-line me-2"></i>Print Statement
                                </button>
                                <button onclick="exportPDF()" class="btn btn-success">
                                    <i class="ri-file-pdf-line me-2"></i>Export PDF
                                </button>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card" id="statement-content">
                                    <div class="page-card-body">
                                        <!-- Statement Header -->
                                        <div class="text-center mb-4" style="border-bottom: 2px solid #e2e8f0; padding-bottom: 1rem;">
                                            <h3 style="color: #2563eb; font-weight: 700;">PENSION ACCOUNT STATEMENT</h3>
                                            <p class="mb-0" style="color: #64748b;">Period: <?php echo date('d M Y', strtotime($period_start)); ?> to <?php echo date('d M Y', strtotime($period_end)); ?></p>
                                        </div>
                                        
                                        <!-- Member Information -->
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <h5 style="color: #1e293b; margin-bottom: 1rem;">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>
                                                    </tr>
                                                    <tr>
                                                        <td><strong>Name:</strong></td>
                                                        <td><?php echo htmlspecialchars($statement_data['member']['first_name'] . ' ' . $statement_data['member']['last_name']); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td><strong>Scheme:</strong></td>
                                                        <td><?php echo htmlspecialchars($statement_data['member']['scheme_name'] ?? 'N/A'); ?></td>
                                                    </tr>
                                                </table>
                                            </div>
                                            <div class="col-md-6">
                                                <h5 style="color: #1e293b; margin-bottom: 1rem;">Account Summary</h5>
                                                <table class="table table-borderless">
                                                    <tr>
                                                        <td><strong>Total 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>Total 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>Allocated Investment Returns:</strong></td>
                                                        <td class="text-end">KES <?php echo number_format($statement_data['account']['allocated_investment_returns'] ?? 0, 2); ?></td>
                                                    </tr>
                                                    <tr style="border-top: 2px solid #e2e8f0;">
                                                        <td><strong>Accrued Benefits:</strong></td>
                                                        <td class="text-end"><strong>KES <?php echo number_format($statement_data['account']['accrued_benefits'] ?? 0, 2); ?></strong></td>
                                                    </tr>
                                                    <tr>
                                                        <td><strong>Available Balance:</strong></td>
                                                        <td class="text-end"><strong style="color: #10b981;">KES <?php echo number_format($statement_data['account']['available_balance'] ?? 0, 2); ?></strong></td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                        
                                        <!-- Contributions -->
                                        <div class="mb-4">
                                            <h5 style="color: #1e293b; margin-bottom: 1rem;">Contributions (<?php echo count($statement_data['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>
                                                            <th>Date</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php if (empty($statement_data['contributions'])): ?>
                                                            <tr><td colspan="5" 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>
                                                                    <td><?php echo date('d M Y', strtotime($contrib['created_at'])); ?></td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                        
                                        <!-- Fund Returns -->
                                        <?php if (!empty($statement_data['fund_returns'])): ?>
                                        <div class="mb-4">
                                            <h5 style="color: #1e293b; margin-bottom: 1rem;">Investment Returns Allocated (<?php echo count($statement_data['fund_returns']); ?>)</h5>
                                            <div class="table-responsive">
                                                <table class="data-table">
                                                    <thead>
                                                        <tr>
                                                            <th>Period</th>
                                                            <th>Return %</th>
                                                            <th>Allocation Amount (KES)</th>
                                                            <th>Date</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($statement_data['fund_returns'] as $return): ?>
                                                            <tr>
                                                                <td><?php echo date('M Y', strtotime($return['return_period_start'])); ?> - <?php echo date('M Y', strtotime($return['return_period_end'])); ?></td>
                                                                <td><?php echo number_format($return['return_percentage'], 2); ?>%</td>
                                                                <td>KES <?php echo number_format($return['allocation_amount'], 2); ?></td>
                                                                <td><?php echo date('d M Y', strtotime($return['return_period_start'])); ?></td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Withdrawals -->
                                        <?php if (!empty($statement_data['withdrawals'])): ?>
                                        <div class="mb-4">
                                            <h5 style="color: #1e293b; margin-bottom: 1rem;">Withdrawals (<?php echo count($statement_data['withdrawals']); ?>)</h5>
                                            <div class="table-responsive">
                                                <table class="data-table">
                                                    <thead>
                                                        <tr>
                                                            <th>Date</th>
                                                            <th>Type</th>
                                                            <th>Amount (KES)</th>
                                                            <th>Status</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($statement_data['withdrawals'] as $withdrawal): ?>
                                                            <tr>
                                                                <td><?php echo date('d M Y', strtotime($withdrawal['requested_date'])); ?></td>
                                                                <td><?php echo htmlspecialchars($withdrawal['withdrawal_type']); ?></td>
                                                                <td>KES <?php echo number_format($withdrawal['calculated_amount'] ?? $withdrawal['requested_amount'], 2); ?></td>
                                                                <td><span class="status-badge status-<?php echo strtolower($withdrawal['status']); ?>"><?php echo htmlspecialchars($withdrawal['status']); ?></span></td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Footer -->
                                        <div class="text-center mt-4" style="border-top: 2px solid #e2e8f0; padding-top: 1rem; color: #64748b; font-size: 0.875rem;">
                                            <p>This statement is generated on <?php echo date('d M Y, h:i A'); ?></p>
                                            <p>For inquiries, please contact your scheme administrator</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
    function exportPDF() {
        // TODO: Implement PDF export using jsPDF or server-side PDF generation
        alert('PDF export functionality will be implemented');
    }
    </script>
</body>
</html>
