<?php
require_once '../../config/database.php';
require_once '../../includes/auth.php';

header('Content-Type: application/json');

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

try {
    // Clear existing assessments
    $pdo->exec("DELETE FROM ai_risk_assessments WHERE assessment_date = CURDATE()");
    
    // Get all active students
    $students_sql = "
        SELECT 
            s.id,
            s.student_id,
            s.first_name,
            s.last_name,
            s.class_id,
            s.session
        FROM students s
        WHERE s.status = 'active'
        ORDER BY s.id
    ";
    
    $stmt = $pdo->query($students_sql);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $assessments_generated = 0;
    
    foreach ($students as $student) {
        $risk_data = assessStudentRisk($student);
        
        if ($risk_data) {
            $insert_sql = "
                INSERT INTO ai_risk_assessments 
                (student_id, risk_level, risk_factors, overall_score, assessment_date, next_review_date)
                VALUES (?, ?, ?, ?, CURDATE(), DATE_ADD(CURDATE(), INTERVAL 30 DAY))
            ";
            
            $stmt = $pdo->prepare($insert_sql);
            $stmt->execute([
                $student['id'],
                $risk_data['risk_level'],
                json_encode($risk_data['risk_factors']),
                $risk_data['overall_score']
            ]);
            
            $assessments_generated++;
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Completed risk assessment for {$assessments_generated} students",
        'assessments_count' => $assessments_generated
    ]);

} catch (Exception $e) {
    error_log("Risk Assessment Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error running risk assessment: ' . $e->getMessage()
    ]);
}

/**
 * Comprehensive student risk assessment
 */
function assessStudentRisk($student) {
    global $pdo;
    
    $risk_factors = [];
    $total_score = 0;
    $factor_count = 0;
    
    // 1. Academic Performance Factor (40% weight)
    $academic_score = assessAcademicPerformance($student['id']);
    $risk_factors['academic_performance'] = [
        'score' => $academic_score,
        'weight' => 0.4,
        'details' => getAcademicDetails($student['id'])
    ];
    $total_score += $academic_score * 0.4;
    $factor_count++;
    
    // 2. Attendance Factor (25% weight)
    $attendance_score = assessAttendance($student['id']);
    $risk_factors['attendance'] = [
        'score' => $attendance_score,
        'weight' => 0.25,
        'details' => getAttendanceDetails($student['id'])
    ];
    $total_score += $attendance_score * 0.25;
    $factor_count++;
    
    // 3. Consistency Factor (20% weight)
    $consistency_score = assessConsistency($student['id']);
    $risk_factors['consistency'] = [
        'score' => $consistency_score,
        'weight' => 0.2,
        'details' => getConsistencyDetails($student['id'])
    ];
    $total_score += $consistency_score * 0.2;
    $factor_count++;
    
    // 4. Improvement Trend Factor (15% weight)
    $trend_score = assessImprovementTrend($student['id']);
    $risk_factors['improvement_trend'] = [
        'score' => $trend_score,
        'weight' => 0.15,
        'details' => getTrendDetails($student['id'])
    ];
    $total_score += $trend_score * 0.15;
    $factor_count++;
    
    // Normalize score (0-1 scale where 1 is highest risk)
    $normalized_score = $total_score / $factor_count;
    
    // Determine risk level
    $risk_level = determineRiskLevel($normalized_score);
    
    return [
        'risk_level' => $risk_level,
        'overall_score' => round($normalized_score, 2),
        'risk_factors' => $risk_factors
    ];
}

/**
 * Assess academic performance risk
 */
function assessAcademicPerformance($student_id) {
    global $pdo;
    
    $sql = "
        SELECT 
            AVG(r.marks_obtained) as avg_marks,
            COUNT(CASE WHEN r.marks_obtained < 40 THEN 1 END) as fail_count,
            COUNT(CASE WHEN r.marks_obtained < 50 THEN 1 END) as low_count,
            COUNT(*) as total_exams
        FROM results r
        WHERE r.student_id = ?
        AND r.exam_type IN ('midterm', 'final')
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$data || $data['total_exams'] == 0) {
        return 0.7; // High risk if no data
    }
    
    $score = 0;
    
    // Base score on average marks
    $avg_marks = $data['avg_marks'];
    if ($avg_marks < 33) {
        $score += 1.0; // Very high risk
    } elseif ($avg_marks < 40) {
        $score += 0.8; // High risk
    } elseif ($avg_marks < 50) {
        $score += 0.6; // Medium risk
    } elseif ($avg_marks < 60) {
        $score += 0.4; // Low-medium risk
    } elseif ($avg_marks < 70) {
        $score += 0.2; // Low risk
    } else {
        $score += 0.0; // Very low risk
    }
    
    // Penalty for failing subjects
    if ($data['fail_count'] > 0) {
        $score += min(0.5, $data['fail_count'] * 0.2);
    }
    
    // Penalty for consistently low performance
    if ($data['low_count'] > ($data['total_exams'] * 0.7)) {
        $score += 0.3;
    }
    
    return min(1.0, $score);
}

/**
 * Assess attendance risk
 */
function assessAttendance($student_id) {
    global $pdo;
    
    // This would typically check actual attendance records
    // For now, we'll simulate based on available data
    // In a real implementation, you'd check attendance tables
    
    // Simulate attendance data (would normally come from attendance table)
    $sql = "
        SELECT COUNT(*) as total_classes,
               COUNT(CASE WHEN r.marks_obtained IS NOT NULL THEN 1 END) as attended_classes
        FROM results r
        WHERE r.student_id = ?
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id]);
    $attendance_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$attendance_data || $attendance_data['total_classes'] == 0) {
        return 0.6; // Medium-high risk if no data
    }
    
    $attendance_rate = $attendance_data['attended_classes'] / $attendance_data['total_classes'];
    
    if ($attendance_rate < 0.6) {
        return 1.0; // Very high risk
    } elseif ($attendance_rate < 0.7) {
        return 0.8; // High risk
    } elseif ($attendance_rate < 0.8) {
        return 0.6; // Medium risk
    } elseif ($attendance_rate < 0.9) {
        return 0.3; // Low risk
    } else {
        return 0.1; // Very low risk
    }
}

/**
 * Assess consistency risk
 */
function assessConsistency($student_id) {
    global $pdo;
    
    $sql = "
        SELECT r.marks_obtained
        FROM results r
        WHERE r.student_id = ?
        AND r.exam_type IN ('midterm', 'final')
        ORDER BY r.session, r.exam_type
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id]);
    $marks = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    if (count($marks) < 3) {
        return 0.5; // Medium risk due to insufficient data
    }
    
    // Calculate standard deviation
    $mean = array_sum($marks) / count($marks);
    $variance = array_sum(array_map(function($mark) use ($mean) {
        return pow($mark - $mean, 2);
    }, $marks)) / count($marks);
    $std_dev = sqrt($variance);
    
    // Higher standard deviation = higher inconsistency = higher risk
    if ($std_dev > 20) {
        return 1.0; // Very high risk
    } elseif ($std_dev > 15) {
        return 0.8; // High risk
    } elseif ($std_dev > 10) {
        return 0.6; // Medium risk
    } elseif ($std_dev > 5) {
        return 0.3; // Low risk
    } else {
        return 0.1; // Very low risk
    }
}

/**
 * Assess improvement trend risk
 */
function assessImprovementTrend($student_id) {
    global $pdo;
    
    $sql = "
        SELECT r.marks_obtained, r.session, r.exam_type
        FROM results r
        WHERE r.student_id = ?
        AND r.exam_type IN ('midterm', 'final')
        ORDER BY r.session, 
                 CASE r.exam_type 
                     WHEN 'midterm' THEN 1 
                     WHEN 'final' THEN 2 
                 END
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (count($results) < 4) {
        return 0.5; // Medium risk due to insufficient data
    }
    
    // Calculate trend using linear regression slope
    $n = count($results);
    $sum_x = $sum_y = $sum_xy = $sum_xx = 0;
    
    for ($i = 0; $i < $n; $i++) {
        $x = $i + 1;
        $y = $results[$i]['marks_obtained'];
        $sum_x += $x;
        $sum_y += $y;
        $sum_xy += $x * $y;
        $sum_xx += $x * $x;
    }
    
    $denominator = $n * $sum_xx - $sum_x * $sum_x;
    if ($denominator == 0) {
        return 0.5; // Neutral risk
    }
    
    $slope = ($n * $sum_xy - $sum_x * $sum_y) / $denominator;
    
    // Negative slope = declining performance = higher risk
    if ($slope < -5) {
        return 1.0; // Very high risk
    } elseif ($slope < -2) {
        return 0.8; // High risk
    } elseif ($slope < 0) {
        return 0.6; // Medium risk
    } elseif ($slope < 2) {
        return 0.3; // Low risk
    } else {
        return 0.1; // Very low risk (improving)
    }
}

/**
 * Determine overall risk level
 */
function determineRiskLevel($score) {
    if ($score >= 0.8) return 'critical';
    if ($score >= 0.6) return 'high';
    if ($score >= 0.4) return 'medium';
    return 'low';
}

/**
 * Get detailed academic information
 */
function getAcademicDetails($student_id) {
    global $pdo;
    
    $sql = "
        SELECT 
            sub.name as subject,
            AVG(r.marks_obtained) as avg_marks,
            COUNT(CASE WHEN r.marks_obtained < 40 THEN 1 END) as fail_count
        FROM results r
        JOIN subjects sub ON r.subject_id = sub.id
        WHERE r.student_id = ?
        GROUP BY r.subject_id, sub.name
        ORDER BY avg_marks ASC
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

/**
 * Get attendance details (placeholder)
 */
function getAttendanceDetails($student_id) {
    return [
        'total_classes' => 'N/A',
        'attended_classes' => 'N/A',
        'attendance_rate' => 'N/A'
    ];
}

/**
 * Get consistency details
 */
function getConsistencyDetails($student_id) {
    global $pdo;
    
    $sql = "
        SELECT r.marks_obtained, sub.name as subject
        FROM results r
        JOIN subjects sub ON r.subject_id = sub.id
        WHERE r.student_id = ?
        ORDER BY r.session, r.exam_type
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

/**
 * Get trend details
 */
function getTrendDetails($student_id) {
    global $pdo;
    
    $sql = "
        SELECT 
            r.session,
            r.exam_type,
            r.marks_obtained,
            sub.name as subject
        FROM results r
        JOIN subjects sub ON r.subject_id = sub.id
        WHERE r.student_id = ?
        ORDER BY r.session, 
                 CASE r.exam_type 
                     WHEN 'midterm' THEN 1 
                     WHEN 'final' THEN 2 
                 END
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>