<?php
class MemberRiskProfile {
    private $conn;
    private $member_no;
    
    // Risk score weights
    private const WEIGHTS = [
        'age' => 0.15,
        'bmi' => 0.15,
        'chronic_conditions' => 0.25,
        'lifestyle' => 0.20,
        'family_history' => 0.15,
        'claims_history' => 0.10
    ];

    public function __construct($conn, $member_no) {
        $this->conn = $conn;
        $this->member_no = $member_no;
    }

    public function calculateHealthRiskScore() {
        $scores = [
            'age_score' => $this->calculateAgeRisk(),
            'bmi_score' => $this->calculateBMIRisk(),
            'chronic_score' => $this->calculateChronicConditionRisk(),
            'lifestyle_score' => $this->calculateLifestyleRisk(),
            'family_score' => $this->calculateFamilyHistoryRisk(),
            'claims_score' => $this->calculateClaimsHistoryRisk()
        ];

        $total_score = 0;
        foreach ($scores as $key => $score) {
            $risk_factor = str_replace('_score', '', $key);
            $total_score += $score * self::WEIGHTS[$risk_factor];
        }

        // Store risk score in database
        $sql = "INSERT INTO member_risk_scores (
                    member_no, 
                    total_score,
                    age_score,
                    bmi_score, 
                    chronic_score,
                    lifestyle_score,
                    family_score,
                    claims_score,
                    assessment_date
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('sddddddd',
            $this->member_no,
            $total_score,
            $scores['age_score'],
            $scores['bmi_score'],
            $scores['chronic_score'], 
            $scores['lifestyle_score'],
            $scores['family_score'],
            $scores['claims_score']
        );
        $stmt->execute();

        return [
            'total_score' => $total_score,
            'risk_level' => $this->getRiskLevel($total_score),
            'detailed_scores' => $scores
        ];
    }

    private function calculateAgeRisk() {
        $sql = "SELECT TIMESTAMPDIFF(YEAR, dob, CURDATE()) as age 
                FROM member_info WHERE member_no = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $this->member_no);
        $stmt->execute();
        $result = $stmt->get_result();
        $age = $result->fetch_assoc()['age'];

        // Age risk scoring
        if ($age < 30) return 1;
        if ($age < 40) return 2;
        if ($age < 50) return 3;
        if ($age < 60) return 4;
        return 5;
    }

    private function calculateBMIRisk() {
        $sql = "SELECT weight, height FROM member_health_data 
                WHERE member_no = ? ORDER BY date_recorded DESC LIMIT 1";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $this->member_no);
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_assoc();

        if (!$data) return 3; // Default moderate risk if no data

        $bmi = $data['weight'] / (($data['height']/100) * ($data['height']/100));

        // BMI risk scoring
        if ($bmi < 18.5) return 3; // Underweight
        if ($bmi < 25) return 1;   // Normal
        if ($bmi < 30) return 3;   // Overweight
        if ($bmi < 35) return 4;   // Obese Class I
        return 5;                  // Obese Class II+
    }

    private function calculateChronicConditionRisk() {
        $sql = "SELECT COUNT(*) as condition_count 
                FROM member_conditions 
                WHERE member_no = ? AND is_chronic = 1";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $this->member_no);
        $stmt->execute();
        $result = $stmt->get_result();
        $count = $result->fetch_assoc()['condition_count'];

        // Chronic condition risk scoring
        if ($count == 0) return 1;
        if ($count == 1) return 3;
        if ($count == 2) return 4;
        return 5;
    }

    private function calculateLifestyleRisk() {
        $sql = "SELECT * FROM member_lifestyle 
                WHERE member_no = ? ORDER BY assessment_date DESC LIMIT 1";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $this->member_no);
        $stmt->execute();
        $result = $stmt->get_result();
        $lifestyle = $result->fetch_assoc();

        if (!$lifestyle) return 3; // Default moderate risk if no data

        $risk_score = 1;

        // Smoking
        if ($lifestyle['smoking_status'] == 'current') $risk_score += 2;
        else if ($lifestyle['smoking_status'] == 'former') $risk_score += 1;

        // Exercise
        if ($lifestyle['exercise_frequency'] < 1) $risk_score += 2;
        else if ($lifestyle['exercise_frequency'] < 3) $risk_score += 1;

        // Alcohol
        if ($lifestyle['alcohol_units_weekly'] > 14) $risk_score += 1;

        return min($risk_score, 5);
    }

    private function calculateFamilyHistoryRisk() {
        $sql = "SELECT COUNT(*) as condition_count 
                FROM member_family_history 
                WHERE member_no = ? AND is_hereditary = 1";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $this->member_no);
        $stmt->execute();
        $result = $stmt->get_result();
        $count = $result->fetch_assoc()['condition_count'];

        // Family history risk scoring
        if ($count == 0) return 1;
        if ($count == 1) return 2;
        if ($count == 2) return 3;
        if ($count == 3) return 4;
        return 5;
    }

    private function calculateClaimsHistoryRisk() {
        $sql = "SELECT COUNT(*) as claim_count 
                FROM bills b 
                WHERE member_no = ? 
                AND invoice_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $this->member_no);
        $stmt->execute();
        $result = $stmt->get_result();
        $count = $result->fetch_assoc()['claim_count'];

        // Claims history risk scoring
        if ($count < 2) return 1;
        if ($count < 4) return 2;
        if ($count < 6) return 3;
        if ($count < 8) return 4;
        return 5;
    }

    private function getRiskLevel($score) {
        if ($score < 2) return 'LOW';
        if ($score < 3) return 'MODERATE-LOW';
        if ($score < 4) return 'MODERATE';
        if ($score < 4.5) return 'MODERATE-HIGH';
        return 'HIGH';
    }

    public function getInterventionRecommendations() {
        $risk_data = $this->calculateHealthRiskScore();
        $recommendations = [];

        // Get detailed scores
        $scores = $risk_data['detailed_scores'];

        // Check BMI risk
        if ($scores['bmi_score'] >= 4) {
            $recommendations[] = [
                'type' => 'LIFESTYLE',
                'priority' => 'HIGH',
                'description' => 'Weight management program recommended',
                'action' => 'Refer to dietitian and physical activity program'
            ];
        }

        // Check chronic conditions
        if ($scores['chronic_score'] >= 3) {
            $sql = "SELECT condition_name FROM member_conditions 
                    WHERE member_no = ? AND is_chronic = 1";
            $stmt = $this->conn->prepare($sql);
            $stmt->bind_param('s', $this->member_no);
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($condition = $result->fetch_assoc()) {
                $recommendations[] = [
                    'type' => 'CLINICAL',
                    'priority' => 'HIGH',
                    'description' => "Regular monitoring for {$condition['condition_name']}",
                    'action' => 'Schedule quarterly check-ups'
                ];
            }
        }

        // Check lifestyle risks
        if ($scores['lifestyle_score'] >= 3) {
            $sql = "SELECT * FROM member_lifestyle 
                    WHERE member_no = ? ORDER BY assessment_date DESC LIMIT 1";
            $stmt = $this->conn->prepare($sql);
            $stmt->bind_param('s', $this->member_no);
            $stmt->execute();
            $result = $stmt->get_result();
            $lifestyle = $result->fetch_assoc();

            if ($lifestyle['smoking_status'] == 'current') {
                $recommendations[] = [
                    'type' => 'LIFESTYLE',
                    'priority' => 'HIGH',
                    'description' => 'Smoking cessation support',
                    'action' => 'Enroll in smoking cessation program'
                ];
            }

            if ($lifestyle['exercise_frequency'] < 3) {
                $recommendations[] = [
                    'type' => 'LIFESTYLE',
                    'priority' => 'MEDIUM',
                    'description' => 'Increase physical activity',
                    'action' => 'Join wellness program for guided exercise'
                ];
            }
        }

        // Store recommendations
        foreach ($recommendations as $rec) {
            $sql = "INSERT INTO member_interventions (
                        member_no,
                        intervention_type,
                        priority,
                        description,
                        recommended_action,
                        status,
                        created_at
                    ) VALUES (?, ?, ?, ?, ?, 'PENDING', NOW())";
            
            $stmt = $this->conn->prepare($sql);
            $stmt->bind_param('sssss',
                $this->member_no,
                $rec['type'],
                $rec['priority'],
                $rec['description'],
                $rec['action']
            );
            $stmt->execute();
        }

        return $recommendations;
    }

    public function monitorChronicConditions() {
        $sql = "SELECT c.*, 
                    DATEDIFF(NOW(), last_checkup_date) as days_since_checkup,
                    DATEDIFF(NOW(), last_prescription_date) as days_since_prescription
                FROM member_conditions c
                WHERE member_no = ? AND is_chronic = 1";
                
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $this->member_no);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $monitoring_data = [];
        
        while ($condition = $result->fetch_assoc()) {
            $alerts = [];
            
            // Check for overdue checkups
            if ($condition['days_since_checkup'] > 90) {
                $alerts[] = [
                    'type' => 'CHECKUP_OVERDUE',
                    'message' => 'Regular checkup overdue',
                    'days_overdue' => $condition['days_since_checkup'] - 90
                ];
            }
            
            // Check for prescription renewals
            if ($condition['days_since_prescription'] > 30) {
                $alerts[] = [
                    'type' => 'PRESCRIPTION_RENEWAL',
                    'message' => 'Prescription renewal may be needed',
                    'days_overdue' => $condition['days_since_prescription'] - 30
                ];
            }
            
            // Get recent vitals
            $sql = "SELECT * FROM member_vitals 
                    WHERE member_no = ? 
                    ORDER BY reading_date DESC LIMIT 5";
            $stmt = $this->conn->prepare($sql);
            $stmt->bind_param('s', $this->member_no);
            $stmt->execute();
            $vitals = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            
            $monitoring_data[] = [
                'condition' => $condition['condition_name'],
                'diagnosis_date' => $condition['diagnosis_date'],
                'last_checkup' => $condition['last_checkup_date'],
                'next_checkup_due' => date('Y-m-d', strtotime($condition['last_checkup_date'] . ' + 90 days')),
                'alerts' => $alerts,
                'recent_vitals' => $vitals
            ];
        }
        
        return $monitoring_data;
    }
}
?>