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

try {
    echo "Debugging Merit Position with GPA 0.00\n\n";

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

    // Get all students in class 10 with results
    $stmt = $pdo->prepare("
        SELECT DISTINCT s.id, s.first_name, s.last_name, s.roll_number
        FROM students s
        JOIN results r ON s.id = r.student_id
        WHERE s.class_id = ? AND s.status = 'active' AND r.session = ? AND r.exam_type = ?
        ORDER BY s.roll_number
        LIMIT 10
    ");
    $stmt->execute([$class_id, $session, $exam_type]);
    $students = $stmt->fetchAll();

    echo "Students with results 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";

    // Simulate the merit data calculation
    $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;
        }

        // Get student subjects to determine fourth subjects
        $stmt_subject = $pdo->prepare(
            "SELECT ss.subject_id, s.name as subject_name, s.code as subject_code, ss.is_fourth_subject
            FROM student_subjects ss
            JOIN subjects s ON ss.subject_id = s.id
            WHERE ss.student_id = ?
            ORDER BY s.name"
        );
        $stmt_subject->execute([$sid]);
        $student_subjects = $stmt_subject->fetchAll();

        // Create subject info map
        $student_subject_info_map = [];
        foreach ($student_subjects as $subject) {
            $student_subject_info_map[$subject['subject_id']] = $subject;
        }

        // Simplified processing
        $processed_results = $student_results;

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

        // Calculate GPA
        $student_gpa = 0.00;
        $student_total_grade_points = 0;
        $student_gpa_subjects = 0;
        $student_fourth_subject_found = false;

        // Check if student failed in any non-4th subject
        $student_failed_in_non_fourth = false;
        foreach ($processed_results as $result) {
            $subject_id = $result['subject_id'];
            if (isset($student_subject_info_map[$subject_id])) {
                $subject_info = $student_subject_info_map[$subject_id];
                // If failed in non-4th subject, GPA should be 0
                if ($result['grade'] == 'F' && !$subject_info['is_fourth_subject']) {
                    $student_failed_in_non_fourth = true;
                    break;
                }
            }
        }

        if ($student_failed_in_non_fourth) {
            $student_gpa = 0.00;
        } else {
            foreach ($processed_results as $result) {
                $subject_id = $result['subject_id'];
                if (isset($student_subject_info_map[$subject_id])) {
                    $subject_info = $student_subject_info_map[$subject_id];
                    if ($result['grade'] != 'F') {
                        $grade_point = getGradePoint($result['grade']);
                        $student_total_grade_points += $grade_point;
                        $student_gpa_subjects++;

                        if ($subject_info['is_fourth_subject']) {
                            $student_fourth_subject_found = true;
                        }
                    }
                }
            }

            if ($student_gpa_subjects > 0) {
                if ($student_fourth_subject_found) {
                    $student_gpa = round($student_total_grade_points / ($student_gpa_subjects - 1), 2);
                } else {
                    $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,
            'failed_non_fourth' => $student_failed_in_non_fourth
        ];

        echo "Student: {$student['first_name']} {$student['last_name']} (Roll: {$student['roll_number']})\n";
        echo "  GPA: {$student_gpa} (type: " . gettype($student_gpa) . ")\n";
        echo "  GPA > 0.00: " . ($student_gpa > 0.00 ? 'true' : 'false') . "\n";
        echo "  GPA == 0.00: " . ($student_gpa == 0.00 ? 'true' : 'false') . "\n";
        echo "  Failed in non-4th: " . ($student_failed_in_non_fourth ? 'Yes' : 'No') . "\n";
        echo "  Total marks: {$student_total_obtained}\n";
        echo "  Will get merit position: " . ($student_gpa > 0.00 ? 'Yes' : 'No') . "\n\n";
    }

    // Sort and create merit order
    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'];
    });

    $merit_order = [];
    $position = 1;
    foreach ($student_merit_data as $sid => $data) {
        if ($data['gpa'] > 0.00) {
            $merit_order[$sid] = $position++;
        }
    }

    echo "Final Merit Positions:\n";
    echo "Position | Roll | Name | GPA | Failed Non-4th\n";
    echo "---------|------|------|-----|---------------\n";

    foreach ($student_merit_data as $sid => $data) {
        $student = $data['student'];
        $merit_pos = isset($merit_order[$sid]) ? $merit_order[$sid] : 'N/A';
        $failed = $data['failed_non_fourth'] ? 'Yes' : 'No';

        printf("%-8s | %-4d | %-20s | %-3.2f | %-10s\n",
            $merit_pos,
            $student['roll_number'],
            substr($student['first_name'] . ' ' . $student['last_name'], 0, 20),
            $data['gpa'],
            $failed
        );
    }

} 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;
    }
}
?>
