<?php
/**
 * RBA Reports
 * Generate Retirement Benefits Authority (RBA) compliance reports
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_rba_reports');

$scheme_id = $_GET['scheme_id'] ?? null;
$report_type = $_GET['report_type'] ?? 'monthly';
$report_period = $_GET['report_period'] ?? date('Y-m');

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

$report_data = null;
if ($scheme_id && $_GET['action'] === 'generate') {
    $scheme = $conn->query("SELECT * FROM pension_schemes WHERE scheme_id = $scheme_id")->fetch_assoc();
    
    // Get period dates
    $period_start = $report_period . '-01';
    $period_end = date('Y-m-t', strtotime($period_start));
    
    // RBA Monthly Report Data
    if ($report_type === 'monthly') {
        // Total active members
        $total_members = $conn->query("SELECT COUNT(*) as count FROM members WHERE scheme_id = $scheme_id AND is_active = 1")->fetch_assoc()['count'];
        
        // New members in period
        $new_members = $conn->query("SELECT COUNT(*) as count FROM members WHERE scheme_id = $scheme_id AND DATE(created_at) BETWEEN '$period_start' AND '$period_end'")->fetch_assoc()['count'];
        
        // Total contributions
        $total_contributions = $conn->query("SELECT COALESCE(SUM(contribution_amount), 0) as total 
                                            FROM contributions c
                                            INNER JOIN members m ON c.member_id = m.member_id
                                            WHERE m.scheme_id = $scheme_id AND DATE(c.contribution_period) BETWEEN '$period_start' AND '$period_end'")->fetch_assoc()['total'];
        
        // Employee contributions
        $employee_contributions = $conn->query("SELECT COALESCE(SUM(contribution_amount), 0) as total 
                                                FROM contributions c
                                                INNER JOIN members m ON c.member_id = m.member_id
                                                WHERE m.scheme_id = $scheme_id AND c.contribution_type = 'EMPLOYEE' AND DATE(c.contribution_period) BETWEEN '$period_start' AND '$period_end'")->fetch_assoc()['total'];
        
        // Employer contributions
        $employer_contributions = $conn->query("SELECT COALESCE(SUM(contribution_amount), 0) as total 
                                                FROM contributions c
                                                INNER JOIN members m ON c.member_id = m.member_id
                                                WHERE m.scheme_id = $scheme_id AND c.contribution_type = 'EMPLOYER' AND DATE(c.contribution_period) BETWEEN '$period_start' AND '$period_end'")->fetch_assoc()['total'];
        
        // Total withdrawals
        $total_withdrawals = $conn->query("SELECT COALESCE(SUM(calculated_amount), 0) as total 
                                           FROM withdrawal_requests 
                                           WHERE scheme_id = $scheme_id AND DATE(requested_date) BETWEEN '$period_start' AND '$period_end' AND status = 'PROCESSED'")->fetch_assoc()['total'];
        
        // Total fund value
        $total_fund_value = $conn->query("SELECT COALESCE(SUM(accrued_benefits), 0) as total 
                                         FROM member_accounts ma
                                         INNER JOIN members m ON ma.member_id = m.member_id
                                         WHERE m.scheme_id = $scheme_id AND ma.account_status = 'ACTIVE'")->fetch_assoc()['total'];
        
        $report_data = [
            'scheme' => $scheme,
            'report_type' => 'Monthly RBA Report',
            'period' => $report_period,
            'period_start' => $period_start,
            'period_end' => $period_end,
            'total_members' => $total_members,
            'new_members' => $new_members,
            'total_contributions' => $total_contributions,
            'employee_contributions' => $employee_contributions,
            'employer_contributions' => $employer_contributions,
            'total_withdrawals' => $total_withdrawals,
            'total_fund_value' => $total_fund_value
        ];
    }
}

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'RBA 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">
                    <!-- Page Header -->
                    <div class="welcome-header" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>RBA Compliance Reports</h2>
                                <p>Generate Retirement Benefits Authority statutory reports</p>
                            </div>
                        </div>
                    </div>

                    <?php if (!$report_data): ?>
                        <!-- Report Generator Form -->
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Generate RBA Report</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">Scheme <span class="text-danger">*</span></label>
                                                    <select name="scheme_id" class="form-select" required>
                                                        <option value="">Select Scheme</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'] . ' (' . ($scheme['rba_registration_number'] ?? 'No RBA #') . ')'); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Report Type</label>
                                                    <select name="report_type" class="form-select">
                                                        <option value="monthly" <?php echo $report_type === 'monthly' ? 'selected' : ''; ?>>Monthly</option>
                                                        <option value="quarterly" <?php echo $report_type === 'quarterly' ? 'selected' : ''; ?>>Quarterly</option>
                                                        <option value="annual" <?php echo $report_type === 'annual' ? 'selected' : ''; ?>>Annual</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label">Report Period</label>
                                                    <input type="month" name="report_period" class="form-control" value="<?php echo $report_period; ?>" required>
                                                </div>
                                            </div>
                                            <div class="alert alert-info">
                                                <i class="ri-information-line me-2"></i>
                                                <strong>Note:</strong> RBA reports must be submitted monthly to the Retirement Benefits Authority as per Kenyan regulations.
                                            </div>
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-file-chart-line me-2"></i>Generate RBA Report
                                            </button>
                                            <a href="rba_reports.php" class="btn btn-secondary">Reset</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <!-- Report Display -->
                        <div class="row mb-3">
                            <div class="col-12">
                                <a href="rba_reports.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 Report
                                </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="rba-report-content">
                                    <div class="page-card-body">
                                        <!-- RBA Report Header -->
                                        <div class="text-center mb-4" style="border-bottom: 3px solid #f59e0b; padding-bottom: 1rem;">
                                            <h3 style="color: #f59e0b; font-weight: 700;">RETIREMENT BENEFITS AUTHORITY</h3>
                                            <h4 style="color: #1e293b;">MONTHLY STATUTORY REPORT</h4>
                                            <p class="mb-0" style="color: #64748b;">Period: <?php echo date('F Y', strtotime($report_data['period'] . '-01')); ?></p>
                                        </div>
                                        
                                        <!-- Scheme Information -->
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <h5 style="color: #1e293b; margin-bottom: 1rem;">Scheme Information</h5>
                                                <table class="table table-borderless">
                                                    <tr>
                                                        <td><strong>Scheme Name:</strong></td>
                                                        <td><?php echo htmlspecialchars($report_data['scheme']['scheme_name']); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td><strong>RBA Registration Number:</strong></td>
                                                        <td><?php echo htmlspecialchars($report_data['scheme']['rba_registration_number'] ?? 'N/A'); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td><strong>Scheme Type:</strong></td>
                                                        <td><?php echo htmlspecialchars($report_data['scheme']['scheme_type']); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td><strong>Report Period:</strong></td>
                                                        <td><?php echo date('F Y', strtotime($report_data['period'] . '-01')); ?></td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                        
                                        <!-- Key Statistics -->
                                        <div class="metrics-row mb-4">
                                            <div class="metric-card members">
                                                <div class="metric-header">
                                                    <h6 class="metric-title">Total Active Members</h6>
                                                    <span class="metric-icon"><i class="ri-user-line"></i></span>
                                                </div>
                                                <div class="metric-value"><?php echo number_format($report_data['total_members']); ?></div>
                                                <div class="metric-change">New in period: <?php echo $report_data['new_members']; ?></div>
                                            </div>
                                            
                                            <div class="metric-card contributions">
                                                <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($report_data['total_contributions'], 0); ?></div>
                                                <div class="metric-change">Employee: KES <?php echo number_format($report_data['employee_contributions'], 0); ?> | Employer: KES <?php echo number_format($report_data['employer_contributions'], 0); ?></div>
                                            </div>
                                            
                                            <div class="metric-card withdrawals">
                                                <div class="metric-header">
                                                    <h6 class="metric-title">Total Withdrawals</h6>
                                                    <span class="metric-icon"><i class="ri-money-dollar-circle-line"></i></span>
                                                </div>
                                                <div class="metric-value">KES <?php echo number_format($report_data['total_withdrawals'], 0); ?></div>
                                            </div>
                                            
                                            <div class="metric-card balances">
                                                <div class="metric-header">
                                                    <h6 class="metric-title">Total Fund Value</h6>
                                                    <span class="metric-icon"><i class="ri-wallet-line"></i></span>
                                                </div>
                                                <div class="metric-value">KES <?php echo number_format($report_data['total_fund_value'], 0); ?></div>
                                            </div>
                                        </div>
                                        
                                        <!-- Detailed Breakdown -->
                                        <div class="mb-4">
                                            <h5 style="color: #1e293b; margin-bottom: 1rem;">Contribution Breakdown</h5>
                                            <div class="table-responsive">
                                                <table class="data-table">
                                                    <thead>
                                                        <tr>
                                                            <th>Category</th>
                                                            <th class="text-end">Amount (KES)</th>
                                                            <th class="text-end">Percentage</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr>
                                                            <td>Employee Contributions</td>
                                                            <td class="text-end">KES <?php echo number_format($report_data['employee_contributions'], 2); ?></td>
                                                            <td class="text-end"><?php echo $report_data['total_contributions'] > 0 ? number_format(($report_data['employee_contributions'] / $report_data['total_contributions']) * 100, 2) : 0; ?>%</td>
                                                        </tr>
                                                        <tr>
                                                            <td>Employer Contributions</td>
                                                            <td class="text-end">KES <?php echo number_format($report_data['employer_contributions'], 2); ?></td>
                                                            <td class="text-end"><?php echo $report_data['total_contributions'] > 0 ? number_format(($report_data['employer_contributions'] / $report_data['total_contributions']) * 100, 2) : 0; ?>%</td>
                                                        </tr>
                                                        <tr style="border-top: 2px solid #e2e8f0; font-weight: 600;">
                                                            <td>Total Contributions</td>
                                                            <td class="text-end">KES <?php echo number_format($report_data['total_contributions'], 2); ?></td>
                                                            <td class="text-end">100.00%</td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                        
                                        <!-- Compliance Statement -->
                                        <div class="alert alert-success mb-4">
                                            <h6><i class="ri-checkbox-circle-line me-2"></i>Compliance Status</h6>
                                            <p class="mb-0">This report confirms compliance with Retirement Benefits Authority regulations for the reporting period.</p>
                                        </div>
                                        
                                        <!-- Footer -->
                                        <div class="text-center mt-4" style="border-top: 2px solid #e2e8f0; padding-top: 1rem; color: #64748b; font-size: 0.875rem;">
                                            <p><strong>Report Generated:</strong> <?php echo date('d M Y, h:i A'); ?></p>
                                            <p>This report is prepared in accordance with the Retirement Benefits Act and RBA regulations.</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() {
        alert('PDF export functionality will be implemented');
    }
    </script>
</body>
</html>
