<?php
/**
 * Financial Reports
 * Comprehensive financial reporting
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('view_financial_reports');

$report_type = $_GET['report_type'] ?? 'summary';
$period_start = $_GET['period_start'] ?? date('Y-m-01');
$period_end = $_GET['period_end'] ?? date('Y-m-t');

$report_data = null;
if ($_GET['action'] === 'generate') {
    // Get financial summary
    $total_contributions = $conn->query("SELECT COALESCE(SUM(contribution_amount), 0) as total 
                                         FROM contributions 
                                         WHERE DATE(contribution_period) BETWEEN '$period_start' AND '$period_end' 
                                         AND status = 'PROCESSED'")->fetch_assoc()['total'];
    
    $total_withdrawals = $conn->query("SELECT COALESCE(SUM(calculated_amount), 0) as total 
                                      FROM withdrawal_requests 
                                      WHERE DATE(requested_date) BETWEEN '$period_start' AND '$period_end' 
                                      AND status = 'PROCESSED'")->fetch_assoc()['total'];
    
    $total_premiums = $conn->query("SELECT COALESCE(SUM(premium_amount), 0) as total 
                                    FROM premiums 
                                    WHERE DATE(premium_due_date) BETWEEN '$period_start' AND '$period_end' 
                                    AND payment_status = 'PAID'")->fetch_assoc()['total'];
    
    $total_claims = $conn->query("SELECT COALESCE(SUM(claim_amount), 0) as total 
                                  FROM life_claims 
                                  WHERE DATE(submitted_date) BETWEEN '$period_start' AND '$period_end' 
                                  AND claim_status = 'PAID'")->fetch_assoc()['total'];
    
    $total_fund_value = $conn->query("SELECT COALESCE(SUM(accrued_benefits), 0) as total 
                                      FROM member_accounts 
                                      WHERE account_status = 'ACTIVE'")->fetch_assoc()['total'];
    
    $report_data = [
        'period_start' => $period_start,
        'period_end' => $period_end,
        'total_contributions' => $total_contributions,
        'total_withdrawals' => $total_withdrawals,
        'total_premiums' => $total_premiums,
        'total_claims' => $total_claims,
        'total_fund_value' => $total_fund_value
    ];
}

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Financial 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, #8b5cf6 0%, #7c3aed 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Financial Reports</h2>
                                <p>Comprehensive financial reporting and analytics</p>
                            </div>
                        </div>
                    </div>

                    <?php if (!$report_data): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Generate Financial 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-4 mb-3">
                                                    <label class="form-label">Report Type</label>
                                                    <select name="report_type" class="form-select">
                                                        <option value="summary" <?php echo $report_type === 'summary' ? 'selected' : ''; ?>>Summary</option>
                                                        <option value="detailed" <?php echo $report_type === 'detailed' ? 'selected' : ''; ?>>Detailed</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-4 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-4 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-chart-line me-2"></i>Generate Report
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row mb-3">
                            <div class="col-12">
                                <a href="financial_reports.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-2"></i>Back
                                </a>
                                <button onclick="window.print()" class="btn btn-primary">
                                    <i class="ri-printer-line me-2"></i>Print
                                </button>
                            </div>
                        </div>
                        
                        <div class="metrics-row">
                            <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>
                            
                            <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 premiums">
                                <div class="metric-header">
                                    <h6 class="metric-title">Total Premiums</h6>
                                    <span class="metric-icon"><i class="ri-bank-card-line"></i></span>
                                </div>
                                <div class="metric-value">KES <?php echo number_format($report_data['total_premiums'], 0); ?></div>
                            </div>
                            
                            <div class="metric-card claims">
                                <div class="metric-header">
                                    <h6 class="metric-title">Total Claims Paid</h6>
                                    <span class="metric-icon"><i class="ri-file-list-3-line"></i></span>
                                </div>
                                <div class="metric-value">KES <?php echo number_format($report_data['total_claims'], 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>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
