<?php
/**
 * Compliance Reporting Service
 * Automated RBA compliance report generation
 * Kenyan Pension & Life Insurance Management System
 */

require_once __DIR__ . '/../includes/dbconn.php';

class ComplianceReporter {
    private $conn;
    
    public function __construct($db_connection) {
        $this->conn = $db_connection;
    }
    
    /**
     * Generate RBA quarterly report
     */
    public function generateRBAQuarterlyReport($quarter, $year) {
        $startDate = $this->getQuarterStartDate($quarter, $year);
        $endDate = $this->getQuarterEndDate($quarter, $year);
        
        $report = [
            'period' => "Q$quarter $year",
            'start_date' => $startDate,
            'end_date' => $endDate,
            'generated_at' => date('Y-m-d H:i:s'),
            'schemes' => [],
            'summary' => []
        ];
        
        // Get all active schemes
        $schemes = $this->conn->query("SELECT * FROM pension_schemes WHERE is_active = 1")->fetch_all(MYSQLI_ASSOC);
        
        foreach ($schemes as $scheme) {
            $schemeData = $this->getSchemeComplianceData($scheme['scheme_id'], $startDate, $endDate);
            $report['schemes'][] = $schemeData;
        }
        
        // Generate summary
        $report['summary'] = $this->generateSummary($report['schemes']);
        
        return $report;
    }
    
    /**
     * Get scheme compliance data
     */
    private function getSchemeComplianceData($scheme_id, $startDate, $endDate) {
        $scheme = $this->conn->query("SELECT * FROM pension_schemes WHERE scheme_id = $scheme_id")->fetch_assoc();
        
        // Member statistics
        $memberStats = $this->conn->query("SELECT 
            COUNT(*) as total_members,
            COUNT(CASE WHEN employment_status = 'ACTIVE' THEN 1 END) as active_members,
            COUNT(CASE WHEN employment_status = 'RETIRED' THEN 1 END) as retired_members
            FROM members WHERE scheme_id = $scheme_id AND is_active = 1")->fetch_assoc();
        
        // Contribution statistics
        $contributionStats = $this->conn->query("SELECT 
            SUM(CASE WHEN contribution_type = 'EMPLOYEE' THEN contribution_amount ELSE 0 END) as employee_contributions,
            SUM(CASE WHEN contribution_type = 'EMPLOYER' THEN contribution_amount ELSE 0 END) as employer_contributions,
            COUNT(*) as contribution_count
            FROM contributions 
            WHERE scheme_id = $scheme_id 
            AND status = 'PROCESSED'
            AND DATE(contribution_period) BETWEEN '$startDate' AND '$endDate'")->fetch_assoc();
        
        // Withdrawal statistics
        $withdrawalStats = $this->conn->query("SELECT 
            COUNT(*) as withdrawal_count,
            SUM(calculated_amount) as total_withdrawn,
            COUNT(CASE WHEN withdrawal_type = 'RETIREMENT' THEN 1 END) as retirement_count,
            COUNT(CASE WHEN withdrawal_type = 'EARLY_EXIT' THEN 1 END) as early_exit_count
            FROM withdrawal_requests 
            WHERE scheme_id = $scheme_id 
            AND status = 'PROCESSED'
            AND DATE(requested_date) BETWEEN '$startDate' AND '$endDate'")->fetch_assoc();
        
        // Fund balance
        $fundBalance = $this->conn->query("SELECT 
            SUM(accrued_benefits) as total_accrued,
            SUM(available_balance) as total_available,
            SUM(allocated_investment_returns) as total_returns
            FROM member_accounts ma
            INNER JOIN members m ON ma.member_id = m.member_id
            WHERE m.scheme_id = $scheme_id")->fetch_assoc();
        
        return [
            'scheme_id' => $scheme_id,
            'scheme_name' => $scheme['scheme_name'],
            'scheme_code' => $scheme['scheme_code'],
            'scheme_type' => $scheme['scheme_type'],
            'member_statistics' => $memberStats,
            'contribution_statistics' => $contributionStats,
            'withdrawal_statistics' => $withdrawalStats,
            'fund_balance' => $fundBalance
        ];
    }
    
    /**
     * Generate summary statistics
     */
    private function generateSummary($schemes) {
        $summary = [
            'total_schemes' => count($schemes),
            'total_members' => 0,
            'total_contributions' => 0,
            'total_withdrawals' => 0,
            'total_fund_value' => 0
        ];
        
        foreach ($schemes as $scheme) {
            $summary['total_members'] += $scheme['member_statistics']['total_members'] ?? 0;
            $summary['total_contributions'] += ($scheme['contribution_statistics']['employee_contributions'] ?? 0) + 
                                               ($scheme['contribution_statistics']['employer_contributions'] ?? 0);
            $summary['total_withdrawals'] += $scheme['withdrawal_statistics']['total_withdrawn'] ?? 0;
            $summary['total_fund_value'] += $scheme['fund_balance']['total_accrued'] ?? 0;
        }
        
        return $summary;
    }
    
    /**
     * Get quarter start date
     */
    private function getQuarterStartDate($quarter, $year) {
        $months = [1 => '01-01', 2 => '04-01', 3 => '07-01', 4 => '10-01'];
        return "$year-{$months[$quarter]}";
    }
    
    /**
     * Get quarter end date
     */
    private function getQuarterEndDate($quarter, $year) {
        $months = [1 => '03-31', 2 => '06-30', 3 => '09-30', 4 => '12-31'];
        return "$year-{$months[$quarter]}";
    }
    
    /**
     * Export report to PDF
     */
    public function exportToPDF($report) {
        // This would use a PDF library like FPDF or TCPDF
        // For now, return JSON structure
        return json_encode($report, JSON_PRETTY_PRINT);
    }
    
    /**
     * Schedule automated report generation
     */
    public function scheduleReport($reportType, $frequency, $recipients) {
        $sql = "INSERT INTO scheduled_reports (
                   report_type, frequency, recipients, is_active, created_at
               ) VALUES (?, ?, ?, 1, NOW())";
        
        $recipientsJson = json_encode($recipients);
        
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param("sss", $reportType, $frequency, $recipientsJson);
        
        if ($stmt->execute()) {
            return [
                'success' => true,
                'schedule_id' => $this->conn->insert_id
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Failed to schedule report'
        ];
    }
}
