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

try {
    echo "Testing Merit Position Calculation\n\n";

    // Test with a class
    $class_id = 10;
    $session = '2025';
    $exam_type = 'final';

    // Get all students in class 10
    $stmt = $pdo->prepare("SELECT id, first_name, last_name, roll_number FROM students WHERE class_id = ? AND status = 'active' ORDER BY roll_number");
    $stmt->execute([$class_id]);
    $students = $stmt->fetchAll();

    echo "Students in Class 10:\n";
    foreach ($students as $student) {
        echo "- Roll {$student['roll_number']}: {$student['first_name']} {$student['last_name']} (ID: {$student['id']})\n";
    }
    echo "\n";

    // Calculate merit data for all students (similar to the logic in bulk_print_marksheets.php)
    $student_merit_data = [];

    foreach ($students as $student) {
        $sid = $student['id'];

        // Get student results
        $stmt = $pdo->prepare("
            SELECT r.*, sub.name as subject_name, sub.code as subject_code
            FROM results r
            LEFT JOIN subjects sub ON r.subject_id = sub.id
            WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
            AND r.id IN (
                SELECT MAX(id)
                FROM results
                WHERE student_id = ? AND session = ? AND exam_type = ?
                GROUP BY subject_id
            )
            ORDER BY sub.name
        ");
        $stmt->execute([$sid, $session, $exam_type, $sid, $session, $exam_type]);
        $student_results = $stmt->fetchAll();

        if (empty($student_results)) {
            $student_merit_data[$sid] = ['gpa' => 0.00, 'total_marks' => 0, 'student' => $student];
            continue;
        }

        // Group subjects (simplified version)
        $processed_results = $student_results; // For simplicity, skip complex grouping

        // Calculate total marks
        $student_total_obtained = 0;
        foreach ($processed_results as $result) {
            $student_total_obtained += $result['marks_obtained'];
        }

        // Calculate GPA (simplified version)
        $student_gpa = 0.00;
        $student_total_grade_points = 0;
        $student_gpa_subjects = 0;

        foreach ($processed_results as $result) {
            if ($result['grade'] != 'F') {
                $grade_point = getGradePoint($result['grade']);
                $student_total_grade_points += $grade_point;
                $student_gpa_subjects++;
            }
        }

        if ($student_gpa_subjects > 0) {
            $student_gpa = round($student_total_grade_points / $student_gpa_subjects, 2);
            if ($student_gpa > 5.00) {
                $student_gpa = 5.00;
            }
        }

        $student_merit_data[$sid] = [
            'gpa' => $student_gpa,
            'total_marks' => $student_total_obtained,
            'student' => $student
        ];
    }

    // Sort by GPA first, then by total marks
    uasort($student_merit_data, function($a, $b) {
        $gpa_compare = $b['gpa'] <=> $a['gpa'];
        if ($gpa_compare !== 0) {
            return $gpa_compare;
        }
        return $b['total_marks'] <=> $a['total_marks'];
    });

    // Display results
    echo "Merit Position Results (sorted by GPA, then total marks):\n";
    echo "Position | Roll | Name | GPA | Total Marks\n";
    echo "---------|------|------|-----|------------\n";

    $position = 1;
    foreach ($student_merit_data as $sid => $data) {
        $student = $data['student'];
        printf("%-8d | %-4d | %-20s | %-3.2f | %-10d\n",
            $position,
            $student['roll_number'],
            $student['first_name'] . ' ' . $student['last_name'],
            $data['gpa'],
            $data['total_marks']
        );
        $position++;
    }

} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage() . "\n";
}

function getGradePoint($grade) {
    switch ($grade) {
        case 'A+': return 5.00;
        case 'A': return 4.00;
        case 'A-': return 3.50;
        case 'B': return 3.00;
        case 'C': return 2.00;
        case 'D': return 1.00;
        default: return 0.00;
    }
}
?>
