<?php
/**
 * Lapse Prediction Service
 * AI-driven policy lapse prediction
 * Kenyan Pension & Life Insurance Management System
 */

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

class LapsePredictionService {
    private $conn;
    private $apiKey;
    
    public function __construct($db_connection) {
        $this->conn = $db_connection;
        $this->apiKey = getenv('OPENAI_API_KEY');
    }
    
    /**
     * Predict lapse risk for a policy
     * Returns risk score (0-100) and recommendations
     */
    public function predictLapseRisk($policy_id) {
        // Get policy and payment history
        $policy = $this->conn->query("SELECT lp.*, m.member_number, m.first_name, m.last_name,
                                     m.employment_status, lip.product_name
                                     FROM life_policies lp
                                     INNER JOIN members m ON lp.member_id = m.member_id
                                     LEFT JOIN life_insurance_products lip ON lp.product_id = lip.product_id
                                     WHERE lp.policy_id = $policy_id")->fetch_assoc();
        
        if (!$policy) {
            return ['success' => false, 'message' => 'Policy not found'];
        }
        
        // Get payment history
        $premiums = $this->conn->query("SELECT * FROM premiums 
                                       WHERE policy_id = $policy_id 
                                       ORDER BY premium_due_date DESC 
                                       LIMIT 12")->fetch_all(MYSQLI_ASSOC);
        
        // Calculate metrics
        $total_premiums = count($premiums);
        $paid_premiums = count(array_filter($premiums, function($p) { return $p['payment_status'] === 'PAID'; }));
        $overdue_premiums = count(array_filter($premiums, function($p) { return $p['payment_status'] === 'OVERDUE'; }));
        $payment_rate = $total_premiums > 0 ? ($paid_premiums / $total_premiums) * 100 : 0;
        
        // Build AI prompt for risk assessment
        $prompt = "Assess the lapse risk for this life insurance policy:\n\n";
        $prompt .= "Policy Details:\n";
        $prompt .= "- Product: {$policy['product_name']}\n";
        $prompt .= "- Premium: KES " . number_format($policy['premium_amount'], 2) . "\n";
        $prompt .= "- Sum Assured: KES " . number_format($policy['sum_assured'], 2) . "\n";
        $prompt .= "- Status: {$policy['policy_status']}\n";
        $prompt .= "- Member Employment: {$policy['employment_status']}\n\n";
        $prompt .= "Payment History:\n";
        $prompt .= "- Total Premiums: $total_premiums\n";
        $prompt .= "- Paid: $paid_premiums\n";
        $prompt .= "- Overdue: $overdue_premiums\n";
        $prompt .= "- Payment Rate: " . number_format($payment_rate, 1) . "%\n\n";
        $prompt .= "Provide:\n";
        $prompt .= "1. Risk Score (0-100, where 0=low risk, 100=high risk)\n";
        $prompt .= "2. Risk Level (LOW, MEDIUM, HIGH)\n";
        $prompt .= "3. Key Risk Factors\n";
        $prompt .= "4. Recommendations to prevent lapse\n";
        $prompt .= "Format as JSON: {\"risk_score\": number, \"risk_level\": \"string\", \"risk_factors\": [\"...\"], \"recommendations\": [\"...\"]}";
        
        // Call AI (simplified - would use actual API)
        // For now, return calculated risk
        $risk_score = $this->calculateRiskScore($payment_rate, $overdue_premiums, $policy);
        
        return [
            'success' => true,
            'policy_id' => $policy_id,
            'risk_score' => $risk_score,
            'risk_level' => $this->getRiskLevel($risk_score),
            'risk_factors' => $this->identifyRiskFactors($payment_rate, $overdue_premiums, $policy),
            'recommendations' => $this->getRecommendations($risk_score, $overdue_premiums)
        ];
    }
    
    private function calculateRiskScore($payment_rate, $overdue_count, $policy) {
        $score = 0;
        
        // Payment rate factor (0-50 points)
        if ($payment_rate < 50) $score += 50;
        elseif ($payment_rate < 70) $score += 30;
        elseif ($payment_rate < 85) $score += 15;
        
        // Overdue premiums factor (0-30 points)
        $score += min($overdue_count * 10, 30);
        
        // Employment status factor (0-20 points)
        if ($policy['employment_status'] === 'TERMINATED') $score += 20;
        elseif ($policy['employment_status'] === 'RETIRED') $score += 10;
        
        return min($score, 100);
    }
    
    private function getRiskLevel($score) {
        if ($score < 30) return 'LOW';
        if ($score < 70) return 'MEDIUM';
        return 'HIGH';
    }
    
    private function identifyRiskFactors($payment_rate, $overdue_count, $policy) {
        $factors = [];
        
        if ($payment_rate < 70) {
            $factors[] = 'Low payment rate (' . number_format($payment_rate, 1) . '%)';
        }
        
        if ($overdue_count > 0) {
            $factors[] = "$overdue_count overdue premium(s)";
        }
        
        if ($policy['employment_status'] === 'TERMINATED') {
            $factors[] = 'Member employment terminated';
        }
        
        return $factors;
    }
    
    private function getRecommendations($risk_score, $overdue_count) {
        $recommendations = [];
        
        if ($overdue_count > 0) {
            $recommendations[] = 'Contact member to resolve overdue premiums immediately';
            $recommendations[] = 'Offer payment plan for outstanding amounts';
        }
        
        if ($risk_score > 70) {
            $recommendations[] = 'Schedule proactive outreach call';
            $recommendations[] = 'Consider premium reduction or policy modification';
        }
        
        if ($risk_score > 50) {
            $recommendations[] = 'Send payment reminders via SMS/Email';
            $recommendations[] = 'Review policy terms and benefits with member';
        }
        
        return $recommendations;
    }
    
    /**
     * Get policies at high risk of lapsing
     */
    public function getHighRiskPolicies($limit = 50) {
        $policies = $this->conn->query("SELECT lp.policy_id FROM life_policies lp 
                                       WHERE lp.policy_status = 'ACTIVE'
                                       ORDER BY lp.created_at DESC
                                       LIMIT $limit")->fetch_all(MYSQLI_ASSOC);
        
        $risky_policies = [];
        foreach ($policies as $policy) {
            $prediction = $this->predictLapseRisk($policy['policy_id']);
            if ($prediction['success'] && $prediction['risk_score'] >= 50) {
                $risky_policies[] = $prediction;
            }
        }
        
        // Sort by risk score descending
        usort($risky_policies, function($a, $b) {
            return $b['risk_score'] <=> $a['risk_score'];
        });
        
        return $risky_policies;
    }
}
