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

try {
    echo "Testing Marksheet Generation for GPA 0.00 Student\n\n";

    // Test student who failed in non-4th subject
    $student_id = 6269; // MST. AMENA AKTER TULI
    $session = '2025';
    $exam_type = 'final';
    $class_id = 10;

    // Simulate the merit position calculation from bulk_print_marksheets.php
    $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
    $stmt->execute([$class_id]);
    $all_student_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

    // Calculate GPA and total marks for each student (same logic as in marksheet)
    $student_merit_data = [];

    foreach ($all_student_ids as $sid) {
        // 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];
            continue;
        }

        // Get student 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();

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

        $processed_results = $student_results;

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

        // Check if failed in 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 ($result['grade'] == 'F' && !$subject_info['is_fourth_subject']) {
                    $student_failed_in_non_fourth = true;
                    break;
                }
            }
        }

        // Calculate GPA
        $student_gpa = 0.00;
        if (!$student_failed_in_non_fourth) {
            $student_total_grade_points = 0;
            $student_gpa_subjects = 0;
            $student_fourth_subject_found = 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 ($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
        ];
    }

    // 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'];
    });

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

    // Check merit position for our test student
    $merit_position = isset($merit_order[$student_id]) ? $merit_order[$student_id] : null;

    echo "Test Student: ID $student_id\n";
    echo "GPA: " . $student_merit_data[$student_id]['gpa'] . "\n";
    echo "Merit Position: " . ($merit_position ?? 'NULL (blank)') . "\n";
    echo "Will merit position be displayed: " . ($merit_position ? 'YES' : 'NO') . "\n\n";

    // Test the display condition
    echo "Testing PHP condition: if (\$merit_position)\n";
    if ($merit_position) {
        echo "→ Condition is TRUE - merit position will be displayed\n";
    } else {
        echo "→ Condition is FALSE - merit position will be blank\n";
    }

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