<?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 {
    // Get filter parameters
    $session = isset($_POST['session']) ? trim($_POST['session']) : '';
    $class_id = isset($_POST['class_id']) ? (int)$_POST['class_id'] : 0;
    $subject_id = isset($_POST['subject_id']) ? (int)$_POST['subject_id'] : 0;
    $exam_type = isset($_POST['exam_type']) ? trim($_POST['exam_type']) : '';

    // Build WHERE clause for filters
    $where_conditions = [];
    $params = [];

    if (!empty($session)) {
        $where_conditions[] = "s.session = ?";
        $params[] = $session;
    }

    if ($class_id > 0) {
        $where_conditions[] = "s.class_id = ?";
        $params[] = $class_id;
    }

    if ($subject_id > 0) {
        $where_conditions[] = "r.subject_id = ?";
        $params[] = $subject_id;
    }

    if (!empty($exam_type)) {
        $where_conditions[] = "r.exam_type = ?";
        $params[] = $exam_type;
    }

    $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

    // Get overall analytics
    $analytics_sql = "
        SELECT 
            AVG(r.marks_obtained) as average_performance,
            COUNT(CASE WHEN r.grade != 'F' THEN 1 END) * 100.0 / COUNT(*) as pass_rate,
            COUNT(CASE WHEN r.marks_obtained < 40 THEN 1 END) as at_risk_count,
            COUNT(CASE WHEN r.marks_obtained >= 80 THEN 1 END) as top_performers,
            COUNT(*) as total_students
        FROM results r
        JOIN students s ON r.student_id = s.id
        JOIN subjects sub ON r.subject_id = sub.id
        $where_clause
    ";

    $stmt = $pdo->prepare($analytics_sql);
    $stmt->execute($params);
    $analytics = $stmt->fetch(PDO::FETCH_ASSOC);

    // Format the analytics data
    $analytics['average_performance'] = round($analytics['average_performance'] ?? 0, 1);
    $analytics['pass_rate'] = round($analytics['pass_rate'] ?? 0, 1);
    $analytics['at_risk_count'] = (int)($analytics['at_risk_count'] ?? 0);
    $analytics['top_performers'] = (int)($analytics['top_performers'] ?? 0);
    $analytics['total_students'] = (int)($analytics['total_students'] ?? 0);

    // Determine trend direction (simplified version)
    $analytics['trend_direction'] = 'stable'; // This would be calculated from historical data

    // Get performance trends over time (last 5 exams/sessions)
    $trends_sql = "
        SELECT 
            COALESCE(r.session, 'Unknown') as period,
            AVG(r.marks_obtained) as average_marks,
            COUNT(CASE WHEN r.grade != 'F' THEN 1 END) * 100.0 / COUNT(*) as pass_rate
        FROM results r
        JOIN students s ON r.student_id = s.id
        JOIN subjects sub ON r.subject_id = sub.id
        $where_clause
        GROUP BY r.session
        ORDER BY r.session DESC
        LIMIT 5
    ";

    $stmt = $pdo->prepare($trends_sql);
    $stmt->execute($params);
    $trends_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Prepare trend data for chart
    $labels = [];
    $average_marks = [];
    $pass_rates = [];

    // Reverse the data to show chronological order
    $trends_data = array_reverse($trends_data);

    foreach ($trends_data as $trend) {
        $labels[] = $trend['period'];
        $average_marks[] = round($trend['average_marks'], 1);
        $pass_rates[] = round($trend['pass_rate'], 1);
    }

    $trends = [
        'labels' => $labels,
        'average_marks' => $average_marks,
        'pass_rates' => $pass_rates
    ];

    // Get subject-wise analysis
    $subject_sql = "
        SELECT 
            sub.id,
            sub.name,
            sub.code,
            AVG(r.marks_obtained) as average_marks,
            COUNT(CASE WHEN r.grade != 'F' THEN 1 END) * 100.0 / COUNT(*) as pass_rate,
            COUNT(DISTINCT r.student_id) as student_count
        FROM results r
        JOIN students s ON r.student_id = s.id
        JOIN subjects sub ON r.subject_id = sub.id
        $where_clause
        GROUP BY sub.id, sub.name, sub.code
        ORDER BY average_marks DESC
    ";

    $stmt = $pdo->prepare($subject_sql);
    $stmt->execute($params);
    $subject_analysis = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Format subject analysis data
    foreach ($subject_analysis as &$subject) {
        $subject['average_marks'] = round($subject['average_marks'], 1);
        $subject['pass_rate'] = round($subject['pass_rate'], 1);
        $subject['student_count'] = (int)$subject['student_count'];
    }

    // Return success response
    echo json_encode([
        'success' => true,
        'analytics' => $analytics,
        'trends' => $trends,
        'subject_analysis' => $subject_analysis
    ]);

} catch (Exception $e) {
    error_log("AI Analytics Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error loading analytics data: ' . $e->getMessage()
    ]);
}
?>