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

// Test GPA calculation for student 6279
$student_id = 6279;
$session = '2025';
$exam_type = 'final';

echo "=== GPA CALCULATION TEST FOR STUDENT $student_id ===\n\n";

try {
    // Get student details
    $stmt = $pdo->prepare("SELECT s.*, c.name as class_name FROM students s JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();

    if (!$student) {
        echo "Student not found!\n";
        exit;
    }

    echo "Student: {$student['first_name']} {$student['last_name']} (Class: {$student['class_name']})\n\n";

    // Get all results for this student (latest per subject) - same query as all_subjects_marksheet.php
    $stmt = $pdo->prepare("
        SELECT
            r.*,
            COALESCE(r.cq_marks, 0) as cq_marks,
            COALESCE(r.mcq_marks, 0) as mcq_marks,
            COALESCE(r.practical_marks, 0) as practical_marks,
            COALESCE(r.assignment_marks, 0) as assignment_marks,
            COALESCE(r.attendance_marks, 0) as attendance_marks,
            COALESCE(r.grade, 'F') as grade,
            COALESCE(r.remarks, '') as remarks,
            sub.name as subject_name,
            sub.code as subject_code,
            (SELECT is_fourth_subject FROM student_subjects WHERE student_id = r.student_id AND subject_id = r.subject_id LIMIT 1) as is_fourth_subject
        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([$student_id, $session, $exam_type, $student_id, $session, $exam_type]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Apply the same combining logic as all_subjects_marksheet.php
    $bangla_results = [];
    $english_results = [];

    foreach ($results as $result) {
        // Check if this is a Bangla subject (Bangla 1st/2nd Paper or Bangla Grammar, but not History subjects)
        $is_bangla = false;
        if ((stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) &&
            stripos($result['subject_name'], 'History') === false &&
            stripos($result['subject_name'], 'Introduction') === false) {
            $is_bangla = true;
        }
        if ($is_bangla) {
            $bangla_results[] = $result;
        }
        // Check if this is an English subject (English 1st/2nd Paper or English Grammar)
        else if ((stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) &&
                 stripos($result['subject_name'], 'Literature') === false) {
            $english_results[] = $result;
        }
    }

    echo "Raw Bangla subjects: " . count($bangla_results) . "\n";
    echo "Raw English subjects: " . count($english_results) . "\n";

    // Combine subjects
    $final_results = [];

    if (!empty($bangla_results)) {
        // Combine Bangla subjects
        $combined_bangla = combineBanglaSubjects($bangla_results);
        $combined_bangla['subject_name'] = 'বাংলা(একত্রে)';

        // Apply custom grading for combined Bangla
        $custom_grade = calculateBanglaGrade($combined_bangla['cq_marks_array'], $combined_bangla['mcq_marks'], $combined_bangla['full_marks'], $combined_bangla['pass_marks']);
        $combined_bangla['grade'] = $custom_grade;
        $combined_bangla['grade_point'] = getGradePoint($custom_grade);

        $final_results[] = $combined_bangla;
        echo "Combined Bangla created with grade: $custom_grade\n";
    }

    if (!empty($english_results)) {
        // Combine English subjects
        $combined_english = combineEnglishSubjects($english_results);
        $combined_english['subject_name'] = 'ইংরেজি(একত্রে)';

        // Apply custom grading for combined English
        $custom_grade = calculateEnglishGrade($combined_english['cq_marks_array'], $combined_english['full_marks'], $combined_english['pass_marks']);
        $combined_english['grade'] = $custom_grade;
        $combined_english['grade_point'] = getGradePoint($custom_grade);

        $final_results[] = $combined_english;
        echo "Combined English created with grade: $custom_grade\n";
    }

    // Add remaining subjects (excluding Bangla and English which are now combined)
    foreach ($results as $result) {
        $is_bangla = (stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) &&
                     stripos($result['subject_name'], 'History') === false &&
                     stripos($result['subject_name'], 'Introduction') === false;
        $is_english = (stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) &&
                      stripos($result['subject_name'], 'Literature') === false;

        if (!$is_bangla && !$is_english) {
            $final_results[] = $result;
        }
    }

    echo "\n=== FINAL SUBJECT RESULTS (After Combining) ===\n";
    $total_grade_points = 0;
    $gpa_subjects = 0;
    $has_failed_in_non_fourth_subject = false;
    $fourth_subject_found = false;

    foreach ($final_results as $idx => $result) {
        $is_fourth = isset($result['is_fourth_subject']) && $result['is_fourth_subject'];
        $grade = $result['grade'] ?? 'F';
        $grade_point = getGradePoint($grade);

        echo sprintf("%2d. %-30s | Grade: %s | GP: %4.2f | 4th: %s\n",
            $idx + 1,
            substr($result['subject_name'], 0, 30),
            $grade,
            $grade_point,
            $is_fourth ? 'Yes' : 'No'
        );

        // Check if student failed in this subject and it's not a fourth subject
        if ($grade == 'F' && !$is_fourth) {
            $has_failed_in_non_fourth_subject = true;
        }

        if ($grade != 'F') {
            // Handle 4th subject GPA adjustment according to Jessore Board rules
            if ($is_fourth) {
                $fourth_subject_found = true;
                // For 4th subject: add only the bonus points (grade_point - 2.00) if grade_point > 2.00
                if ($grade_point > 2.00) {
                    $total_grade_points += ($grade_point - 2.00);
                    echo "     -> 4th subject bonus: " . ($grade_point - 2.00) . " (original: $grade_point)\n";
                } else {
                    echo "     -> 4th subject bonus: 0.00 (original: $grade_point)\n";
                }
            } else {
                // Regular subject - add full grade point
                $total_grade_points += $grade_point;
            }
            $gpa_subjects++;
        }
    }

    echo "\n=== GPA CALCULATION ===\n";
    echo "Total Grade Points: $total_grade_points\n";
    echo "GPA Subjects: $gpa_subjects\n";
    echo "Fourth Subject Found: " . ($fourth_subject_found ? 'Yes' : 'No') . "\n";
    echo "Failed in Non-Fourth Subject: " . ($has_failed_in_non_fourth_subject ? 'Yes' : 'No') . "\n";

    if ($has_failed_in_non_fourth_subject) {
        $gpa = 0.00;
        $overall_grade = 'F';
        echo "GPA: 0.00 (Failed in non-fourth subject)\n";
        echo "Overall Grade: F\n";
    } else {
        // Calculate GPA with Jessore Board rules
        if ($gpa_subjects > 0) {
            if ($fourth_subject_found) {
                $divisor = ($gpa_subjects - 1) > 0 ? ($gpa_subjects - 1) : 1;
                $gpa = $total_grade_points / $divisor;
                echo "GPA Calculation: $total_grade_points / $divisor = $gpa (4th subject rule)\n";
            } else {
                $gpa = $total_grade_points / $gpa_subjects;
                echo "GPA Calculation: $total_grade_points / $gpa_subjects = $gpa\n";
            }

            // Apply Jessore Board 4th subject rule: If 4th subject exists and GPA > 5.00, cap it at 5.00
            if ($fourth_subject_found && $gpa > 5.00) {
                $gpa = 5.00;
                echo "GPA capped at 5.00 (4th subject rule)\n";
            }

            // Ensure total GPA never exceeds 5.00
            if ($gpa > 5.00) {
                $gpa = 5.00;
                echo "GPA capped at 5.00\n";
            }

            $gpa = round($gpa, 2);
            echo "Final GPA: $gpa\n";
        } else {
            $gpa = 0.00;
            echo "GPA: 0.00 (no subjects passed)\n";
        }

        // Calculate overall grade from GPA
        $overall_grade = calculateGradeFromGPA($gpa);
        echo "Overall Grade: $overall_grade\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;
        case 'F': return 0.00;
        default: return 0.00;
    }
}

function calculateGradeFromGPA($gpa) {
    if ($gpa >= 5.00) return 'A+';
    elseif ($gpa >= 4.00) return 'A';
    elseif ($gpa >= 3.50) return 'A-';
    elseif ($gpa >= 3.00) return 'B';
    elseif ($gpa >= 2.00) return 'C';
    elseif ($gpa >= 1.00) return 'D';
    else return 'F';
}

// Calculate Bangla grade (Jessore Board SSC rules)
function calculateBanglaGrade($cq_marks_array, $mcq_marks, $full_marks, $pass_marks) {
    // For combined Bangla: CQ average > 22 AND MCQ average > 9 to pass
    if (is_array($cq_marks_array) && count($cq_marks_array) > 0) {
        // Calculate average of CQ marks
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);

        // Both averages must pass individually
        if ($cq_average > 22 && $mcq_marks > 9) {
            // Calculate total obtained marks
            $total_obtained = $cq_average + $mcq_marks;
            // Calculate percentage
            $percentage = ($total_obtained / $full_marks) * 100;

            // Assign grade based on percentage
            if ($percentage >= 80) return 'A+';
            if ($percentage >= 70) return 'A';
            if ($percentage >= 60) return 'A-';
            if ($percentage >= 50) return 'B';
            if ($percentage >= 40) return 'C';
            if ($percentage >= 33) return 'D';
            return 'F';
        } else {
            return 'F';
        }
    }
    return 'F';
}

// Calculate English grade (Jessore Board SSC rules)
function calculateEnglishGrade($cq_marks_array, $full_marks, $pass_marks) {
    // For combined English: CQ average > 32 to pass
    if (is_array($cq_marks_array) && count($cq_marks_array) > 0) {
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);
        if ($cq_average > 32) {
            // Calculate percentage
            $percentage = ($cq_average / $full_marks) * 100;

            // Assign grade based on percentage
            if ($percentage >= 80) return 'A+';
            if ($percentage >= 70) return 'A';
            if ($percentage >= 60) return 'A-';
            if ($percentage >= 50) return 'B';
            if ($percentage >= 40) return 'C';
            if ($percentage >= 33) return 'D';
            return 'F';
        } else {
            return 'F';
        }
    }
    return 'F';
}

// Combine Bangla subjects function (from all_subjects_marksheet.php)
function combineBanglaSubjects($bangla_results) {
    if (empty($bangla_results)) return null;

    // If only one Bangla subject, return it as is but mark it as combined
    if (count($bangla_results) == 1) {
        $result = $bangla_results[0];
        $result['subject_name'] = 'বাংলা(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        return $result;
    }

    // For multiple Bangla subjects, combine them
    $combined = [
        'subject_name' => 'বাংলা(একত্রে)',
        'subject_code' => 'CBAN',
        'subject_id' => 'combined_bangla',
        'cq_marks' => 0,
        'cq_marks_array' => [], // Store individual CQ marks for processing
        'mcq_marks' => 0,
        'mcq_marks_array' => [], // Store individual MCQ marks for processing
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];

    // Consider only first 2 Bangla papers for CQ/MCQ averaging
    $considered_results = array_slice($bangla_results, 0, 2);

    // Sum up other marks from all Bangla subjects; don't include CQ/MCQ here
    foreach ($bangla_results as $result) {
        $combined['practical_marks'] += $result['practical_marks'];
        $combined['assignment_marks'] += $result['assignment_marks'];
        $combined['attendance_marks'] += $result['attendance_marks'];
        $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }

    // Average CQ and MCQ based on first 2 papers
    $cq_total = 0;
    $mcq_total = 0;
    foreach ($considered_results as $result) {
        $cq_total += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $mcq_total += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual MCQ marks
    }

    $count = count($considered_results);
    if ($count > 0) {
        $combined['cq_marks'] = $cq_total / $count;
        $combined['mcq_marks'] = $mcq_total / $count;
    }

    // For Jessore Board SSC: Calculate obtained marks as total sum from both subjects
    // CQ and MCQ are averaged for grading, but marks_obtained shows total sum
    $total_marks_sum = 0;
    foreach ($bangla_results as $result) {
        $total_marks_sum += $result['marks_obtained'];
    }
    $combined['marks_obtained'] = $total_marks_sum; // Total sum from both subjects

    // Average full and pass marks over total Bangla results
    $total_count = count($bangla_results);
    if ($total_count > 0) {
        $combined['full_marks'] = $combined['full_marks'] / $total_count;
        $combined['pass_marks'] = $combined['pass_marks'] / $total_count;
    }

    return $combined;
}

// Combine English subjects function (from all_subjects_marksheet.php)
function combineEnglishSubjects($english_results) {
    if (empty($english_results)) return null;

    // If only one English subject, return it as is but mark it as combined
    if (count($english_results) == 1) {
        $result = $english_results[0];
        $result['subject_name'] = 'ইংরেজি(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        $result['mcq_marks_array'] = [$result['mcq_marks']]; // Convert to array for display
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        return $result;
    }

    // For multiple English subjects, combine them
    $combined = [
        'subject_name' => 'ইংরেজি(একত্রে)',
        'subject_code' => 'CENG',
        'subject_id' => 'combined_english',
        'cq_marks' => 0,
        'cq_marks_array' => [], // Store individual CQ marks for processing
        'mcq_marks' => 0,
        'mcq_marks_array' => [], // Store individual MCQ marks for display
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];

    // Sum up the marks from all English subjects
    foreach ($english_results as $result) {
        $combined['cq_marks'] += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $combined['mcq_marks'] += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual MCQ marks
        $combined['practical_marks'] += $result['practical_marks'];
        $combined['assignment_marks'] += $result['assignment_marks'];
        $combined['attendance_marks'] += $result['attendance_marks'];
        $combined['marks_obtained'] += $result['marks_obtained'];
        $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }

    // For Jessore Board SSC: Show total sum of marks_obtained from both English subjects
    // CQ and MCQ are averaged for grading criteria, but marks_obtained shows total sum
    $count = count($english_results);
    if ($count > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $count; // Average for grading
        $combined['mcq_marks'] = $combined['mcq_marks'] / $count; // Average for grading
        // marks_obtained remains as total sum (not averaged)
        $combined['full_marks'] = $combined['full_marks'] / $count;
        $combined['pass_marks'] = $combined['pass_marks'] / $count;
    }

    return $combined;
}
?>