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

// Functions from reports/bulk_print_marksheets_separate.php

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 calculateGPA($results) {
    $total_grade_points = 0;
    $gpa_subjects = 0; // Subjects used for GPA calculation (excluding failed subjects and 4th subjects)
    $has_failed_in_non_fourth_subject = false; // Track if student failed in any non-fourth subject
    $fourth_subject_grade_point = 0; // Track 4th subject grade point for adjustment
    $fourth_subject_found = false; // Track if 4th subject exists
    
    foreach ($results as $result) {
        if (($result['grade'] ?? '') != 'F') {
            $grade_point = $result['grade_point'] ?? 0.00;
            
            // Handle 4th subject GPA adjustment according to Jessore Board rules
            if (!empty($result['is_fourth_subject']) && ($result['is_fourth_subject'] ?? false)) {
                $fourth_subject_found = true;
                $fourth_subject_grade_point = $grade_point;
                // For 4th subject: add only the bonus points (grade_point - 2.00) if grade_point > 2.00
                // Otherwise, add 0 bonus points
                if ($grade_point > 2.00) {
                    $total_grade_points += ($grade_point - 2.00);
                }
            } else {
                // Regular subject - add full grade point
                $total_grade_points += $grade_point;
                $gpa_subjects++; // Count only non-fourth subjects for GPA calculation
            }
        } else {
            // Student failed in this subject
            if (empty($result['is_fourth_subject']) || !($result['is_fourth_subject'] ?? false)) {
                // Failed in a non-fourth subject
                $has_failed_in_non_fourth_subject = true;
            }
        }
    }
    
    // GPA is 0.00 if student failed in any non-fourth subject
    if ($has_failed_in_non_fourth_subject) {
        return 0.00;
    }
    
    // If no subjects for GPA calculation, return 0.00
    if ($gpa_subjects == 0) {
        // If there are no regular subjects but there is a 4th subject, GPA is 0.00
        if ($fourth_subject_found) {
            return 0.00;
        } else {
            return 0.00;
        }
    }
    
    // Calculate GPA (Grade Point Average) with Jessore Board rules
    // For Jessore Board: Total subjects for calculation = regular subjects only (excluding 4th subject)
    // Final GPA = (sum of regular subjects' points + 4th subject additional points) / regular subjects count
    if ($fourth_subject_found) {
        // When 4th subject exists, divide by number of regular subjects (gpa_subjects)
        // The 4th subject contributes bonus points but is not counted as an additional subject in the division
        $gpa = $total_grade_points / $gpa_subjects;
    } else {
        // Normal calculation - divide by number of regular subjects
        $gpa = $total_grade_points / $gpa_subjects;
    }
    
    // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
    if ($gpa > 5.00) {
        $gpa = 5.00;
    }
    
    return round($gpa, 2);
}

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

function calculateBanglaGrade($cq_marks_array, $mcq_marks, $total_marks, $pass_marks) {
    // Calculate average of 2 CQ marks
    $cq_average = 0;
    if (count($cq_marks_array) >= 2) {
        $cq_average = ($cq_marks_array[0] + $cq_marks_array[1]) / 2;
    } else if (count($cq_marks_array) == 1) {
        $cq_average = $cq_marks_array[0];
    }
    
    // For Bangla: CQ average > 22 AND MCQ > 9 to pass
    if ($cq_average > 22 && $mcq_marks > 9) {
        // Calculate overall marks
        $overall_marks = $cq_average + $mcq_marks;
        
        // Calculate percentage based on total marks
        $percentage = ($overall_marks / $total_marks) * 100;
        
        if ($percentage >= 80) return 'A+';
        elseif ($percentage >= 70) return 'A';
        elseif ($percentage >= 60) return 'A-';
        elseif ($percentage >= 50) return 'B';
        elseif ($percentage >= 40) return 'C';
        elseif ($percentage >= 33) return 'D';
        else return 'F';
    } else {
        // If criteria not met, return F
        return 'F';
    }
}

function calculateEnglishGrade($cq_marks_array, $total_marks, $pass_marks) {
    // Calculate average of 2 CQ marks
    $cq_average = 0;
    if (count($cq_marks_array) >= 2) {
        $cq_average = ($cq_marks_array[0] + $cq_marks_array[1]) / 2;
    } else if (count($cq_marks_array) == 1) {
        $cq_average = $cq_marks_array[0];
    }
    
    // For English: CQ average > 32 to pass
    if ($cq_average > 32) {
        // Calculate overall marks (CQ average only for English as per requirements)
        $overall_marks = $cq_average;
        
        // Calculate percentage based on total marks
        $percentage = ($overall_marks / $total_marks) * 100;
        
        if ($percentage >= 80) return 'A+';
        elseif ($percentage >= 70) return 'A';
        elseif ($percentage >= 60) return 'A-';
        elseif ($percentage >= 50) return 'B';
        elseif ($percentage >= 40) return 'C';
        elseif ($percentage >= 33) return 'D';
        else return 'F';
    } else {
        // If criteria not met, return F
        return 'F';
    }
}


$student_id = 6279;
$session = '2025';
$exam_type = 'test';
$class_id = 10;

// Get results for the student - FIXED to avoid duplicates
$stmt = $pdo->prepare(
    "SELECT r.*, sub.name as subject_name, sub.code as subject_code, ss.is_fourth_subject
    FROM results r
    LEFT JOIN subjects sub ON r.subject_id = sub.id
    LEFT JOIN student_subjects ss ON r.subject_id = ss.subject_id AND r.student_id = ss.student_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);

// Process results to calculate grades and grade points
foreach ($results as &$result) {
    // Calculate marks obtained
    $result['marks_obtained'] = ($result['cq_marks'] ?? 0) + ($result['mcq_marks'] ?? 0) +
                               ($result['practical_marks'] ?? 0) + ($result['assignment_marks'] ?? 0) +
                               ($result['attendance_marks'] ?? 0);

    // Try to get subject-specific mark distribution
    $stmt_dist = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
    $stmt_dist->execute([$result['subject_id'], $class_id, $session, $exam_type]);
    $smd = $stmt_dist->fetch();

    if ($smd) {
        $result['full_marks'] = $smd['total_marks'];
        $result['pass_marks'] = $smd['overall_pass_marks'];
    } else {
        // Default values if no subject distribution found
        $result['full_marks'] = 100;
        $result['pass_marks'] = 33;
    }

    // Calculate grade based on marks obtained vs pass marks
    if ($result['marks_obtained'] >= ($result['full_marks'] * 0.8)) {
        $effective_grade = 'A+';
    } elseif ($result['marks_obtained'] >= ($result['full_marks'] * 0.7)) {
        $effective_grade = 'A';
    } elseif ($result['marks_obtained'] >= ($result['full_marks'] * 0.6)) {
        $effective_grade = 'A-';
    } elseif ($result['marks_obtained'] >= ($result['full_marks'] * 0.5)) {
        $effective_grade = 'B';
    } elseif ($result['marks_obtained'] >= ($result['full_marks'] * 0.4)) {
        $effective_grade = 'C';
    } elseif ($result['marks_obtained'] >= $result['pass_marks']) {
        $effective_grade = 'D';
    } else {
        $effective_grade = 'F';
    }

    // Apply custom grading for Bangla and English subjects
    $subject_name = $result['subject_name'] ?? '';
    if (stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'Bangla') !== false) {
        $cq_marks_array = [$result['cq_marks'] ?? 0];
        $effective_grade = calculateBanglaGrade($cq_marks_array, $result['mcq_marks'] ?? 0, $result['full_marks'], $result['pass_marks']);
    } else if (stripos($subject_name, 'ইংরেজি') !== false || stripos($subject_name, 'English') !== false) {
        $cq_marks_array = [$result['cq_marks'] ?? 0];
        $effective_grade = calculateEnglishGrade($cq_marks_array, $result['full_marks'], $result['pass_marks']);
    }

    $result['grade'] = $effective_grade;
    $result['grade_point'] = getGradePoint($effective_grade);

    // Ensure is_fourth_subject is set
    $result['is_fourth_subject'] = $result['is_fourth_subject'] ?? false;
}
unset($result); 

$gpa = calculateGPA($results);
$grade = calculateGradeFromGPA($gpa);

echo json_encode([
    'gpa' => $gpa,
    'grade' => $grade,
    'results' => $results
]);

?>