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

try {
    echo "Testing GPA Calculation with Non-4th Subject Failure Check\n\n";

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

    // Get a few students for testing
    $stmt = $pdo->prepare("SELECT id, first_name, last_name, roll_number FROM students WHERE class_id = ? AND status = 'active' ORDER BY roll_number LIMIT 5");
    $stmt->execute([$class_id]);
    $students = $stmt->fetchAll();

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

    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)) {
            echo "Student {$student['first_name']} {$student['last_name']}: No results found\n";
            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 (no complex grouping for test)
        $processed_results = $student_results;

        // Check if student failed in any non-4th subject
        $failed_in_non_fourth = false;
        $has_fourth_subject = false;

        echo "Student: {$student['first_name']} {$student['last_name']}\n";
        foreach ($processed_results as $result) {
            $subject_id = $result['subject_id'];
            $grade = $result['grade'];
            $is_fourth = false;

            if (isset($student_subject_info_map[$subject_id])) {
                $subject_info = $student_subject_info_map[$subject_id];
                $is_fourth = $subject_info['is_fourth_subject'];
                if ($is_fourth) {
                    $has_fourth_subject = true;
                }
            }

            $subject_name = $result['subject_name'] ?? 'Unknown';
            echo "  - {$subject_name}: {$grade} " . ($is_fourth ? '(4th subject)' : '(regular)') . "\n";

            // Check for failure in non-4th subject
            if ($grade == 'F' && !$is_fourth) {
                $failed_in_non_fourth = true;
            }
        }

        // Determine GPA
        if ($failed_in_non_fourth) {
            $final_gpa = 0.00;
            echo "  → Failed in non-4th subject → GPA: 0.00\n";
        } else {
            // Calculate GPA (simplified)
            $total_grade_points = 0;
            $gpa_subjects = 0;

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

            if ($gpa_subjects > 0) {
                if ($has_fourth_subject) {
                    $final_gpa = round($total_grade_points / ($gpa_subjects - 1), 2);
                } else {
                    $final_gpa = round($total_grade_points / $gpa_subjects, 2);
                }
                if ($final_gpa > 5.00) {
                    $final_gpa = 5.00;
                }
                echo "  → GPA: {$final_gpa}\n";
            } else {
                $final_gpa = 0.00;
                echo "  → No valid subjects for GPA → GPA: 0.00\n";
            }
        }

        echo "\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;
    }
}
?>
