<?php
require_once '../config/database.php';
require_once '../includes/site_settings.php';
require_once '../includes/subject_helpers.php';

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$site_address = $settings['site_address'] ?? '';
$logo_image = $settings['logo_image'] ?? '';
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;

// Check if user is logged in and has appropriate permissions
session_start();
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

// Get parameters
$class_id = $_GET['class_id'] ?? '';
$session = $_GET['session'] ?? '';
$exam_type = $_GET['exam_type'] ?? '';
$group_name = trim($_GET['group_name'] ?? '');
$sort_by = $_GET['sort_by'] ?? 'roll'; // Default sort by roll number

// Get toggle parameters
$show_bangla_avg = isset($_GET['show_bangla_avg']) ? filter_var($_GET['show_bangla_avg'], FILTER_VALIDATE_BOOLEAN) : true;
$show_english_avg = isset($_GET['show_english_avg']) ? filter_var($_GET['show_english_avg'], FILTER_VALIDATE_BOOLEAN) : true;

// Initialize variables
$students = [];
$subjects = [];
$results_matrix = [];
$original_subjects = [];

// Fetch class information
$class_info = [];
if ($class_id) {
    $stmt = $pdo->prepare("SELECT * FROM classes WHERE id = ?");
    $stmt->execute([$class_id]);
    $class_info = $stmt->fetch();
}

// Fetch group information
$group_display_name = '';
if ($group_name) {
    $group_display_name = $group_name;
}

// Fetch exam types
$stmt = $pdo->query("SELECT DISTINCT exam_type FROM results ORDER BY exam_type");
$exam_types = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

// Fetch sessions
$stmt = $pdo->query("SELECT DISTINCT session FROM results ORDER BY session DESC");
$sessions = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

// Fetch classes
$classes = [];
$stmt = $pdo->query("SELECT * FROM classes ORDER BY name, section");
while ($row = $stmt->fetch()) {
    $classes[] = $row;
}

// Fetch groups
$groups = [];
if ($class_id) {
    // Get all groups for this class regardless of session initially
    // When session is selected, we'll filter in the UI or with AJAX
    $stmt = $pdo->prepare("
        SELECT DISTINCT group_name as name 
        FROM students 
        WHERE class_id = ? AND group_name IS NOT NULL 
        ORDER BY group_name
    ");
    $stmt->execute([$class_id]);
    $groups = $stmt->fetchAll();
}

// If we have all required parameters, fetch data
if ($class_id && $session && $exam_type) {
    // Fetch subjects for this class with category information
    $stmt = $pdo->prepare("
        SELECT DISTINCT s.id, s.name, s.code,
               COALESCE(cs.group_name, '') as group_name,
               CASE WHEN cs.group_name IS NULL OR cs.group_name = '' THEN 1 ELSE 0 END as is_general
        FROM results r
        JOIN subjects s ON r.subject_id = s.id
        JOIN students st ON r.student_id = st.id
        LEFT JOIN class_subjects cs ON cs.subject_id = s.id AND cs.class_id = ?
        WHERE st.class_id = ? AND r.session = ? AND r.exam_type = ?
            " . ($group_name ? "AND LOWER(TRIM(st.group_name)) = LOWER(TRIM(?))" : "") . "
    ");
    $params = [$class_id, $class_id, $session, $exam_type];
    if ($group_name) $params[] = $group_name;
    $stmt->execute($params);
    $raw_subjects = $stmt->fetchAll();
    
    // Check for 4th subjects for each subject
    foreach ($raw_subjects as &$subject) {
        // Check if this subject is a 4th subject for any student in this class/session
        $stmt_check = $pdo->prepare("
            SELECT COUNT(*) as count
            FROM student_subjects ss
            JOIN students st ON ss.student_id = st.id
            WHERE ss.subject_id = ? AND ss.is_fourth_subject = 1 
            AND st.class_id = ? AND st.session = ?
            " . ($group_name ? "AND LOWER(TRIM(st.group_name)) = LOWER(TRIM(?))" : "") . "
            LIMIT 1
        ");
        $check_params = [$subject['id'], $class_id, $session];
        if ($group_name) $check_params[] = $group_name;
        $stmt_check->execute($check_params);
        $fourth_check = $stmt_check->fetch();
        $subject['is_fourth_subject'] = !in_array((int)$class_id, [6,7,8])
            && ($fourth_check && $fourth_check['count'] > 0) ? 1 : 0;
    }
    unset($subject);
    
    // Group Bangla and English subjects and sort by category
    $subjects = groupSubjectsWithCategory($raw_subjects, $pdo, $class_id, $session, $group_name);
    
    // Store original subjects for processing combined subjects
    $original_subjects = $raw_subjects;
    
    // Fetch students for this class
    $sql = "
        SELECT s.* 
        FROM students s 
        WHERE s.class_id = ? AND s.session = ?
    ";
    
    if ($group_name) {
        $sql .= " AND LOWER(TRIM(s.group_name)) = LOWER(TRIM(?))";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$class_id, $session, $group_name]);
    } else {
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$class_id, $session]);
    }
    
    $students = $stmt->fetchAll();
    
    // Fetch all results for this class, session, and exam to build results matrix
    if (!empty($students) && !empty($subjects)) {
        // Build the results matrix first
        $stmt = $pdo->prepare(
            "SELECT r.*, s.student_id as roll_number
            FROM results r
            JOIN students s ON r.student_id = s.id
            WHERE s.class_id = ? AND r.session = ? AND r.exam_type = ?
            AND r.id IN (
                SELECT MAX(id)
                FROM results
                WHERE student_id = r.student_id AND subject_id = r.subject_id AND session = ? AND exam_type = ?
                GROUP BY student_id, subject_id
            )
            " . ($group_name ? "AND LOWER(TRIM(s.group_name)) = LOWER(TRIM(?))" : "") . "
        ");
        $params = [$class_id, $session, $exam_type, $session, $exam_type];
        if ($group_name) $params[] = $group_name;
        $stmt->execute($params);
        $all_results = $stmt->fetchAll();
        
        // Organize results in matrix format and add 4th subject information
        foreach ($all_results as $result) {
            // Check if this subject is a fourth subject for this student
            $stmt_check = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
            $stmt_check->execute([$result['student_id'], $result['subject_id']]);
            $subject_info = $stmt_check->fetch();
            $result['is_fourth_subject'] = !in_array((int)$class_id, [6,7,8])
                && $subject_info && $subject_info['is_fourth_subject'] ? true : false;
            
            $results_matrix[$result['student_id']][$result['subject_id']] = $result;
        }
        
        // Calculate GPA for each student and add to student data for sorting
        foreach ($students as &$student) {
            // Calculate GPA for this student using the same logic as in the display
            $total_grade_points = 0;
            $has_failed_in_non_fourth_subject = false;
            $fourth_subject_found = false;
            $gpa_subjects_count = 0;
            
            // Recalculate GPA with proper 4th subject handling
            foreach ($subjects as $subject) {
                // Handle combined subjects
                if ($subject['id'] == 'combined_bangla') {
                    $bangla_subjects = array_filter($original_subjects, function($s) { return (stripos($s['name'], 'বাংলা') !== false) || (stripos($s['name'], 'Bangla') !== false && stripos($s['name'], 'Bangladesh') === false); });
                    $result = getCombinedBanglaResult($student['id'], $bangla_subjects, $results_matrix);
                } else if ($subject['id'] == 'combined_english') {
                    $english_subjects = array_filter($original_subjects, function($s) { return stripos($s['name'], 'ইংরেজি') !== false || stripos($s['name'], 'English') !== false; });
                    $result = getCombinedEnglishResult($student['id'], $english_subjects, $results_matrix);
                } else {
                    $result = isset($results_matrix[$student['id']][$subject['id']]) ? $results_matrix[$student['id']][$subject['id']] : null;
                }
                
                if ($result && isset($result['grade'])) {
                    // Check if student failed in this subject and it's not a fourth subject
                    if ($result['grade'] == 'F' && !(isset($result['is_fourth_subject']) && $result['is_fourth_subject'])) {
                        $has_failed_in_non_fourth_subject = true;
                    }
                    
                    // Handle 4th subject GPA adjustment according to Jessore Board rules
                    if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                        $fourth_subject_found = true;
                        // For 4th subject: add only the bonus points (grade_point - 2.00) if grade_point > 2.00
                        // Otherwise, add 0 bonus points
                        $grade_point = getGradePoint($result['grade']);
                        if ($grade_point > 2.00) {
                            $total_grade_points += ($grade_point - 2.00);
                        }
                        // Count 4th subject in subject count (it contributes to the divisor adjustment)
                        if ($result['grade'] != 'F') {
                            $gpa_subjects_count++; // Count subjects for GPA calculation
                        }
                    } else {
                        // For regular subjects, calculate grade from marks if needed
                        $subject_grade = isset($result['grade']) ? $result['grade'] : 'F';
                        
                        // If grade is not set or is invalid, calculate it from marks
                        if (!isset($result['grade']) || $result['grade'] == '' || $result['grade'] == 'F') {
                            if (isset($result['marks_obtained']) && isset($result['full_marks'])) {
                                $subject_grade = calculateGradeFromMarks($result['marks_obtained'], $result['full_marks']);
                            }
                        }
                        
                        // Regular subject - add full grade point
                        $grade_point_to_add = getGradePoint($subject_grade);
                        $total_grade_points += $grade_point_to_add;
                        
                        // Count regular subjects in subject count
                        if ($subject_grade != 'F') {
                            $gpa_subjects_count++; // Count subjects for GPA calculation
                        }
                    }
                }
            }
            
            // Calculate final GPA with Jessore Board rules
            if ($has_failed_in_non_fourth_subject) {
                $gpa = 0.00;
            } else if ($gpa_subjects_count > 0) {
                // For Jessore Board: when 4th subject exists, divide by (number of subjects - 1)
                // because 4th subject's extra points are added but the subject itself is not counted in division
                if ($fourth_subject_found) {
                    // When 4th subject exists, divide by (gpa_subjects_count - 1)
                    // Prevent division by zero when student has only one subject which is a fourth subject
                    $divisor = ($gpa_subjects_count - 1) > 0 ? ($gpa_subjects_count - 1) : 1;
                    $gpa = $total_grade_points / $divisor;
                } else {
                    // Normal calculation
                    $gpa = $total_grade_points / $gpa_subjects_count;
                }
                
                // 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;
                }
                
                $gpa = round($gpa, 2);
            } else {
                $gpa = 0.00;
            }
            
            // Add GPA to student data
            $student['calculated_gpa'] = $gpa;
        }
        unset($student); // Break the reference with the last element
        
        // Calculate merit positions based on GPA (primary) and total marks (secondary), excluding students with GPA 0
        $student_merit_positions = [];
        if (!empty($students)) {
            // Calculate total marks for each student to use as tiebreaker
            foreach ($students as &$student) {
                $total_marks = 0;
                $has_valid_marks = false; // Flag to check if student has at least some valid marks
                
                foreach ($subjects as $subject) {
                    // Handle combined subjects
                    if ($subject['id'] == 'combined_bangla') {
                        $bangla_subjects = array_filter($original_subjects, function($s) { return (stripos($s['name'], 'বাংলা') !== false) || (stripos($s['name'], 'Bangla') !== false && stripos($s['name'], 'Bangladesh') === false); });
                        $result = getCombinedBanglaResult($student['id'], $bangla_subjects, $results_matrix);
                    } else if ($subject['id'] == 'combined_english') {
                        $english_subjects = array_filter($original_subjects, function($s) { return stripos($s['name'], 'ইংরেজি') !== false || stripos($s['name'], 'English') !== false; });
                        $result = getCombinedEnglishResult($student['id'], $english_subjects, $results_matrix);
                    } else {
                        $result = isset($results_matrix[$student['id']][$subject['id']]) ? $results_matrix[$student['id']][$subject['id']] : null;
                    }
                    
                    if ($result) {
                        $has_valid_marks = true; // Student has at least one valid result
                        
                        // For combined subjects, use the appropriate toggle to calculate marks
                        if ($subject['id'] == 'combined_bangla' || $subject['id'] == 'combined_english') {
                            $use_avg = false;
                            if ($subject['id'] == 'combined_bangla') {
                                $use_avg = $show_bangla_avg;
                            } else if ($subject['id'] == 'combined_english') {
                                $use_avg = $show_english_avg;
                            }
                            
                            if (isset($result['cq_marks_array']) && isset($result['mcq_marks_array']) && !empty($result['cq_marks_array']) && !empty($result['mcq_marks_array'])) {
                                if ($use_avg) {
                                    // Use average: avg_cq + avg_mcq
                                    $avg_cq = array_sum($result['cq_marks_array']) / count($result['cq_marks_array']);
                                    $avg_mcq = array_sum($result['mcq_marks_array']) / count($result['mcq_marks_array']);
                                    $marks_for_total = $avg_cq + $avg_mcq;
                                } else {
                                    // Use total: total_cq + total_mcq
                                    $total_cq = array_sum($result['cq_marks_array']);
                                    $total_mcq = array_sum($result['mcq_marks_array']);
                                    $marks_for_total = $total_cq + $total_mcq;
                                }
                            } else {
                                $marks_for_total = $result['marks_obtained'];
                            }
                        } else {
                            $marks_for_total = $result['marks_obtained'];
                        }
                        
                        $total_marks += $marks_for_total;
                    }
                }
                
                $student['total_marks_for_merit'] = $total_marks;
                $student['has_valid_marks'] = $has_valid_marks;
            }
            unset($student); // Break the reference
            
            // Filter students with GPA > 0 AND who have actual marks entries for merit calculation
            $students_for_merit = array_filter($students, function($student) {
                // Include in merit only if GPA > 0 AND has valid marks entries
                return $student['calculated_gpa'] > 0 && 
                       $student['has_valid_marks'] === true;
            });
            
            // Sort students for merit by GPA (primary) and total marks (secondary)
            usort($students_for_merit, function($a, $b) {
                // Primary sort: GPA descending
                if ($a['calculated_gpa'] != $b['calculated_gpa']) {
                    return $b['calculated_gpa'] <=> $a['calculated_gpa'];
                }
                // Secondary sort: Total marks descending
                return $b['total_marks_for_merit'] <=> $a['total_marks_for_merit'];
            });
            
            // Assign merit positions
            $position = 1;
            foreach ($students_for_merit as $student) {
                $student_merit_positions[$student['id']] = $position++;
            }
        }
        
        // Sort students based on sort_by parameter
        if ($sort_by == 'gpa') {
            // Sort by GPA descending (highest first)
            usort($students, function($a, $b) {
                return $b['calculated_gpa'] <=> $a['calculated_gpa'];
            });
        } elseif ($sort_by == 'merit') {
            // Sort by merit position (lowest first)
            usort($students, function($a, $b) use ($student_merit_positions) {
                $merit_a = isset($student_merit_positions[$a['id']]) ? $student_merit_positions[$a['id']] : PHP_INT_MAX;
                $merit_b = isset($student_merit_positions[$b['id']]) ? $student_merit_positions[$b['id']] : PHP_INT_MAX;
                return $merit_a <=> $merit_b;
            });
        } else {
            // Default sort by roll number ascending
            usort($students, function($a, $b) {
                $roll_a = isset($a['roll_number']) ? (int)$a['roll_number'] : 0;
                $roll_b = isset($b['roll_number']) ? (int)$b['roll_number'] : 0;
                return $roll_a <=> $roll_b;
            });
        }
    }
}

// Site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$site_address = $settings['address'] ?? '';
$logo_image = $settings['logo_image'] ?? '';
$logo_size = $settings['logo_size'] ?? '50';

// Subject grouping functions are now in includes/subject_helpers.php

// Function to get combined results for grouped subjects
function getCombinedBanglaResult($student_id, $bangla_subjects, $results_matrix) {
    if (empty($bangla_subjects)) return null;
    
    // If only one Bangla subject, return it as is
    if (count($bangla_subjects) == 1) {
        $subject_id = $bangla_subjects[0]['id'];
        return isset($results_matrix[$student_id][$subject_id]) ? $results_matrix[$student_id][$subject_id] : null;
    }
    
    // For multiple Bangla subjects, combine them
    $combined = [
        'student_id' => $student_id,
        'subject_id' => 'combined_bangla',
        'cq_marks' => 0,
        'cq_marks_array' => [],
        'mcq_marks' => 0,
        'mcq_marks_array' => [],
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00,
        'individual_results' => [], // Store individual results for detailed display
        'is_fourth_subject' => false // Track if this combined subject is a fourth subject
    ];
    
    $valid_results = 0;
    
    // Sum up the marks from all Bangla subjects
    foreach ($bangla_subjects as $subject) {
        $subject_id = $subject['id'];
        if (isset($results_matrix[$student_id][$subject_id])) {
            $result = $results_matrix[$student_id][$subject_id];
            
            // Check if any of the individual Bangla subjects is a fourth subject
            if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                $combined['is_fourth_subject'] = true;
            }
            
            $combined['cq_marks'] += $result['cq_marks'];
            $combined['cq_marks_array'][] = $result['cq_marks'];
            $combined['mcq_marks'] += $result['mcq_marks'];
            $combined['mcq_marks_array'][] = $result['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'] += 100; // Assuming 100 marks per subject
            $combined['pass_marks'] += 40;  // Assuming 40 pass marks per subject
            
            // Store individual result for detailed display
            $combined['individual_results'][] = [
                'subject_name' => $subject['name'],
                'cq_marks' => $result['cq_marks'],
                'mcq_marks' => $result['mcq_marks']
            ];
            
            $valid_results++;
        }
    }
    
    // Average the marks for proper grading
    if ($valid_results > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $valid_results;
        $combined['mcq_marks'] = $combined['mcq_marks'] / $valid_results;
        $combined['marks_obtained'] = $combined['marks_obtained'] / $valid_results;
        $combined['full_marks'] = $combined['full_marks'] / $valid_results;
        $combined['pass_marks'] = $combined['pass_marks'] / $valid_results;
        
        // For Bangla subjects: determine pass/fail based on Jessore Board rules
        // CQ average > 22 AND MCQ average > 9 to pass
        if ($combined['cq_marks'] > 22 && $combined['mcq_marks'] > 9) {
            // Calculate overall percentage for grade assignment
            $overall_marks = $combined['cq_marks'] + $combined['mcq_marks'];
            $total_possible_marks = 100; // Assuming 50+50 for CQ+MCQ
            $percentage = ($overall_marks / $total_possible_marks) * 100;
            
            if ($percentage >= 80) $combined['grade'] = 'A+';
            elseif ($percentage >= 70) $combined['grade'] = 'A';
            elseif ($percentage >= 60) $combined['grade'] = 'A-';
            elseif ($percentage >= 50) $combined['grade'] = 'B';
            elseif ($percentage >= 40) $combined['grade'] = 'C';
            elseif ($percentage >= 33) $combined['grade'] = 'D';
            else $combined['grade'] = 'F';
        } else {
            // Student fails according to Jessore Board Bangla rules
            $combined['grade'] = 'F';
        }
        
        $combined['grade_point'] = getGradePoint($combined['grade']);
        
        return $combined;
    }
    
    // If no valid results, return null
    return null;
}

// Function to determine pass/fail status for language subjects (Bangla/English) based on average of CQ and MCQ parts
function isLanguageSubjectPass($cq_marks, $mcq_marks, $cq_full_marks = 50, $mcq_full_marks = 50) {
    // Calculate average of CQ and MCQ parts
    $cq_percentage = ($cq_marks / $cq_full_marks) * 100;
    $mcq_percentage = ($mcq_marks / $mcq_full_marks) * 100;
    
    // Calculate average percentage
    $average_percentage = ($cq_percentage + $mcq_percentage) / 2;
    
    // For language subjects: if average of CQ and MCQ parts is >= 33%, then pass
    // This means both parts average to at least 33% for the subject to be passed
    return $average_percentage >= 33;
}

// Function to determine grade for language subjects (Bangla/English) based on average of CQ and MCQ parts
function getLanguageSubjectGrade($cq_marks, $mcq_marks, $cq_full_marks = 50, $mcq_full_marks = 50) {
    // Calculate average of CQ and MCQ parts
    $cq_percentage = ($cq_marks / $cq_full_marks) * 100;
    $mcq_percentage = ($mcq_marks / $mcq_full_marks) * 100;
    
    // Calculate average percentage
    $average_percentage = ($cq_percentage + $mcq_percentage) / 2;
    
    // Assign grade based on average percentage
    if ($average_percentage >= 80) return 'A+';
    if ($average_percentage >= 70) return 'A';
    if ($average_percentage >= 60) return 'A-';
    if ($average_percentage >= 50) return 'B';
    if ($average_percentage >= 40) return 'C';
    if ($average_percentage >= 33) return 'D';
    return 'F';
}

// Function to convert grade to grade point
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;
    }
}

// Function to calculate grade from marks for regular subjects
function calculateGradeFromMarks($obtained_marks, $full_marks) {
    // Ensure we have valid numbers
    if ($full_marks <= 0) return 'F';
    
    // Calculate percentage
    $percentage = ($obtained_marks / $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';
}

// Function to calculate overall grade from GPA
function calculateOverallGradeFromGPA($gpa) {
    if ($gpa >= 5.00) return 'A+';
    if ($gpa >= 4.00) return 'A';
    if ($gpa >= 3.50) return 'A-';
    if ($gpa >= 3.00) return 'B';
    if ($gpa >= 2.00) return 'C';
    if ($gpa >= 1.00) return 'D';
    return 'F';
}

// Function to get combined results for grouped English subjects
function getCombinedEnglishResult($student_id, $english_subjects, $results_matrix) {
    if (empty($english_subjects)) return null;
    
    // If only one English subject, return it as is
    if (count($english_subjects) == 1) {
        $subject_id = $english_subjects[0]['id'];
        return isset($results_matrix[$student_id][$subject_id]) ? $results_matrix[$student_id][$subject_id] : null;
    }
    
    // For multiple English subjects, combine them
    $combined = [
        'student_id' => $student_id,
        'subject_id' => 'combined_english',
        'cq_marks' => 0,
        'cq_marks_array' => [],
        'mcq_marks' => 0,
        'mcq_marks_array' => [],
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00,
        'individual_results' => [], // Store individual results for detailed display
        'is_fourth_subject' => false // Track if this combined subject is a fourth subject
    ];
    
    $valid_results = 0;
    
    // Sum up the marks from all English subjects
    foreach ($english_subjects as $subject) {
        $subject_id = $subject['id'];
        if (isset($results_matrix[$student_id][$subject_id])) {
            $result = $results_matrix[$student_id][$subject_id];
            
            // Check if any of the individual English subjects is a fourth subject
            if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                $combined['is_fourth_subject'] = true;
            }
            
            $combined['cq_marks'] += $result['cq_marks'];
            $combined['cq_marks_array'][] = $result['cq_marks'];
            $combined['mcq_marks'] += $result['mcq_marks'];
            $combined['mcq_marks_array'][] = $result['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'] += 100; // Assuming 100 marks per subject
            $combined['pass_marks'] += 40;  // Assuming 40 pass marks per subject
            
            // Store individual result for detailed display
            $combined['individual_results'][] = [
                'subject_name' => $subject['name'],
                'cq_marks' => $result['cq_marks'],
                'mcq_marks' => $result['mcq_marks']
            ];
            
            $valid_results++;
        }
    }
    
    // Average the marks for proper grading
    if ($valid_results > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $valid_results;
        $combined['mcq_marks'] = $combined['mcq_marks'] / $valid_results;
        $combined['marks_obtained'] = $combined['marks_obtained'] / $valid_results;
        $combined['full_marks'] = $combined['full_marks'] / $valid_results;
        $combined['pass_marks'] = $combined['pass_marks'] / $valid_results;
        
        // For English subjects: determine pass/fail based on average of CQ and MCQ parts
        // If average of CQ and MCQ parts is pass (>=40%), then student passes
        // Otherwise, student fails
        $cq_full_marks = 50; // Assuming 50 marks for CQ part
        $mcq_full_marks = 50; // Assuming 50 marks for MCQ part
        
        // Calculate grade based on average of CQ and MCQ parts
        $combined['grade'] = getLanguageSubjectGrade($combined['cq_marks'], $combined['mcq_marks'], $cq_full_marks, $mcq_full_marks);
        $combined['grade_point'] = getGradePoint($combined['grade']);
        
        return $combined;
    }
    
    // If no valid results, return null
    return null;
}
?>
<!DOCTYPE html>
<html lang="bn" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>টেবুলেশন শীট - <?php echo htmlspecialchars($site_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        .container-fluid {
            padding-top: 20px;
        }
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
        }
        .form-section {
            background-color: #fff;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .tabulation-sheet {
            background-color: #fff;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        .school-header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #000;
        }
        .school-header h3 {
            margin: 0;
            font-weight: bold;
        }
        .exam-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            padding: 10px;
            background-color: #e9ecef;
            border-radius: 5px;
        }
        .tabulation-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            font-size: 15px;
        }
        .tabulation-table th,
        .tabulation-table td {
            border: 1px solid #000;
            padding: 10px 12px;
            text-align: center;
            vertical-align: middle;
            font-weight: 800;
        }
        .tabulation-table th {
            background-color: #f8f9fa;
            font-weight: 900;
        }
        .student-column {
            min-width: 100px;
            background-color: #e9ecef !important;
        }
        .student-name {
            min-width: 200px;
        }
        .subject-column {
            min-width: 150px;
            background-color: #d1ecf1 !important;
        }
        .marks-column {
            min-width: 80px;
        }
        .total-column {
            background-color: #f8d7da !important;
            font-weight: bold;
        }
        .grade-column {
            background-color: #fff3cd !important;
            font-weight: bold;
        }
        .gpa-column {
            background-color: #d1ecf1 !important;
            font-weight: bold;
        }
        .result-column {
            background-color: #d4edda !important;
            font-weight: bold;
        }
        .signature-section {
            display: flex;
            justify-content: space-between;
            margin-top: 40px;
        }
        .signature-box {
            border-top: 1px solid #000;
            padding-top: 5px;
            text-align: center;
            min-width: 150px;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            body {
                background-color: #fff;
            }
            .tabulation-sheet {
                box-shadow: none;
                border: none;
            }
        }
        .subject-header {
            writing-mode: vertical-lr;
            transform: rotate(180deg);
            white-space: nowrap;
            padding: 10px 5px;
        }
        .student-row-header {
            writing-mode: vertical-lr;
            transform: rotate(180deg);
            white-space: nowrap;
            padding: 10px 5px;
        }
        
        /* Column visibility styles */
        .tabulation-table th,
        .tabulation-table td {
            transition: all 0.3s ease;
        }
        
        .column-hidden {
            display: none !important;
        }
        
        /* Styling for column visibility controls */
        .column-visibility-controls {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .column-visibility-controls .form-check {
            margin-bottom: 5px;
        }
        
        .column-visibility-controls .form-check-label {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3 no-print">
            <h2><i class="fas fa-table"></i> টেবুলেশন শীট</h2>
            <a href="../index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরে যান</a>
        </div>

        <!-- Filter Form -->
        <div class="card no-print">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label for="class_id" class="form-label">ক্লাস *</label>
                        <select class="form-select" id="class_id" name="class_id" required>
                            <option value="">ক্লাস নির্বাচন করুন</option>
                            <?php foreach ($classes as $cls): ?>
                                <option value="<?php echo $cls['id']; ?>" <?php echo ($class_id == $cls['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cls['name'] . ' - ' . $cls['section']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label for="session" class="form-label">সেশন *</label>
                        <select class="form-select" id="session" name="session" required>
                            <option value="">সেশন নির্বাচন করুন</option>
                            <?php foreach ($sessions as $sess): ?>
                                <option value="<?php echo htmlspecialchars($sess); ?>" <?php echo ($session == $sess) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($sess); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label for="exam_type" class="form-label">পরীক্ষা *</label>
                        <select class="form-select" id="exam_type" name="exam_type" required>
                            <option value="">পরীক্ষা নির্বাচন করুন</option>
                            <?php foreach ($exam_types as $et): ?>
                                <option value="<?php echo $et; ?>" <?php echo ($exam_type == $et) ? 'selected' : ''; ?>>
                                    <?php echo ucfirst(str_replace('_', ' ', $et)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label for="group_name" class="form-label">গ্রুপ (যদি থাকে)</label>
                        <select class="form-select" id="group_name" name="group_name">
                            <option value="">সব গ্রুপ</option>
                            <?php foreach ($groups as $g): ?>
                                <option value="<?php echo isset($g['name']) ? $g['name'] : ''; ?>" <?php echo (isset($g['name']) && isset($group_name) && strtolower(trim($g['name'])) == strtolower(trim($group_name))) ? 'selected' : ''; ?>>
                                    <?php echo isset($g['name']) ? htmlspecialchars($g['name']) : ''; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label for="sort_by" class="form-label">সাজানোর ক্রম</label>
                        <select class="form-select" id="sort_by" name="sort_by">
                            <option value="roll" <?php echo ($sort_by == 'roll') ? 'selected' : ''; ?>>রোল নম্বর অনুযায়ী</option>
                            <option value="gpa" <?php echo ($sort_by == 'gpa') ? 'selected' : ''; ?>>জিপিএ অনুযায়ী</option>
                            <option value="merit" <?php echo ($sort_by == 'merit') ? 'selected' : ''; ?>>মেরিট পজিশন অনুযায়ী</option>
                        </select>
                    </div>
                    
                    <div class="col-12 text-end">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-filter"></i> ফিল্টার করুন</button>
                        <button type="reset" class="btn btn-secondary"><i class="fas fa-redo"></i> রিসেট</button>
                    </div>
                    <!-- Preserve toggle parameters -->
                    <input type="hidden" name="show_bangla_avg" value="<?php echo $show_bangla_avg ? 'true' : 'false'; ?>">
                    <input type="hidden" name="show_english_avg" value="<?php echo $show_english_avg ? 'true' : 'false'; ?>">
                </form>
            </div>
        </div>

        <?php if ($class_id && $session && $exam_type): ?>
        <div class="tabulation-sheet">
            <!-- School Header -->
            <div class="school-header">
                <div class="school-logo">
                    <?php if ($logo_image): ?>
                        <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" style="max-height: <?php echo $logo_size; ?>px; width: auto;">
                    <?php else: ?>
                        <i class="fas fa-graduation-cap"></i>
                    <?php endif; ?>
                </div>
                <h3><?php echo htmlspecialchars($site_name); ?></h3>
                <p><?php echo htmlspecialchars($site_address); ?></p>
                <h4 style="text-decoration: underline;">টেবুলেশন শীট</h4>
            </div>

            <!-- Exam Information -->
            <div class="exam-info">
                <div>
                    <strong>ক্লাস:</strong> <?php echo (isset($class_info['name']) ? $class_info['name'] : '') . ' - ' . (isset($class_info['section']) ? $class_info['section'] : ''); ?><br>
                    <strong>গ্রুপ:</strong> <?php echo !empty($group_name) ? htmlspecialchars($group_name) : 'সব গ্রুপ'; ?><br>
                    <strong>সাজানোর ক্রম:</strong> <?php echo ($sort_by == 'gpa') ? 'জিপিএ অনুযায়ী' : (($sort_by == 'merit') ? 'মেরিট পজিশন অনুযায়ী' : 'রোল নম্বর অনুযায়ী'); ?>
                </div>
                <div>
                    <strong>পরীক্ষা:</strong> <?php echo ucfirst($exam_type); ?><br>
                    <strong>সেশন:</strong> <?php echo $session; ?>
                </div>
                <div>
                    <strong>মোট ছাত্র-ছাত্রী:</strong> <?php echo count($students); ?><br>
                    <strong>তারিখ:</strong> <?php echo date('d/m/Y'); ?>
                </div>
            </div>

            <!-- Print Controls -->
            <div class="text-center mb-3 no-print">
                <button onclick="window.print()" class="btn btn-success btn-lg me-2">
                    <i class="fas fa-print"></i> প্রিন্ট করুন
                </button>
            </div>

            <!-- Toggle Switches for Bengali and English Marks Display -->
            <div class="d-flex justify-content-center gap-3 mb-3 no-print" style="flex-wrap: wrap;">
                <div class="d-flex align-items-center gap-2" style="background: #f8f9fa; padding: 10px 15px; border-radius: 5px; border: 1px solid #dee2e6;">
                    <label for="banglaToggle" style="margin: 0; font-weight: 500;">বাংলা:</label>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="banglaToggle" <?php echo $show_bangla_avg ? 'checked' : ''; ?> style="cursor: pointer; width: 50px; height: 25px;">
                        <label class="form-check-label" for="banglaToggle" style="cursor: pointer;">
                            <span id="banglaToggleText"><?php echo $show_bangla_avg ? 'গড়' : 'মোট'; ?></span>
                        </label>
                    </div>
                </div>
                <div class="d-flex align-items-center gap-2" style="background: #f8f9fa; padding: 10px 15px; border-radius: 5px; border: 1px solid #dee2e6;">
                    <label for="englishToggle" style="margin: 0; font-weight: 500;">ইংরেজি:</label>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="englishToggle" <?php echo $show_english_avg ? 'checked' : ''; ?> style="cursor: pointer; width: 50px; height: 25px;">
                        <label class="form-check-label" for="englishToggle" style="cursor: pointer;">
                            <span id="englishToggleText"><?php echo $show_english_avg ? 'গড়' : 'মোট'; ?></span>
                        </label>
                    </div>
                </div>
            </div>

            <!-- Column Visibility Controls -->
            <div class="d-flex justify-content-center mb-3 no-print">
                <div class="column-visibility-controls">
                    <div class="d-flex align-items-center gap-3 flex-wrap">
                        <label class="mb-0" style="font-weight: 500; min-width: 120px;">কলাম দৃশ্যমানতা:</label>
                        <div class="d-flex flex-wrap gap-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="showRollColumn" checked>
                                <label class="form-check-label" for="showRollColumn">রোল ও আইডি</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="showNameColumn" checked>
                                <label class="form-check-label" for="showNameColumn">নাম</label>
                            </div>
                            <?php foreach ($subjects as $index => $subject): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="showSubjectColumn_<?php echo $index; ?>" checked>
                                <label class="form-check-label" for="showSubjectColumn_<?php echo $index; ?>">
                                    <?php echo htmlspecialchars(isset($subject['name']) ? $subject['name'] : ''); ?>
                                </label>
                            </div>
                            <?php endforeach; ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="showTotalColumn" checked>
                                <label class="form-check-label" for="showTotalColumn">মোট</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="showGradeColumn" checked>
                                <label class="form-check-label" for="showGradeColumn">গ্রেড/জিপিএ</label>
                            </div>
                        </div>
                        <div class="ms-auto d-flex gap-2">
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="selectAllColumns()">সব চেক করুন</button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="unselectAllColumns()">সব আনচেক করুন</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Transposed Tabulation Table -->
            <div class="table-responsive">
                <table class="tabulation-table">
                    <thead>
                        <tr>
                            <th class="student-column">রোল ও আইডি</th>
                            <th class="student-column">নাম</th>
                            <?php foreach ($subjects as $subject): ?>
                                <th class="subject-column">
                                    <?php echo htmlspecialchars(isset($subject['name']) ? $subject['name'] : ''); ?>
                                    <?php if (!empty($subject['code'])): ?>
                                        <br><small>(<?php echo htmlspecialchars($subject['code']); ?>)</small>
                                    <?php endif; ?>
                                </th>
                            <?php endforeach; ?>
                            <th class="total-column">মোট</th>
                            <th class="grade-column">গ্রেড/জিপিএ</th>
                            <th class="grade-column">মেরিট পজিশন</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($students as $student): ?>
                            <tr>
                                <td>
                                    <?php 
                                        $roll_number = isset($student['roll_number']) ? htmlspecialchars($student['roll_number']) : '';
                                        $student_id = isset($student['student_id']) ? htmlspecialchars($student['student_id']) : '';
                                        if ($roll_number && $student_id) {
                                            echo $roll_number . ' (' . $student_id . ')';
                                        } else if ($roll_number) {
                                            echo $roll_number;
                                        } else if ($student_id) {
                                            echo $student_id;
                                        } else {
                                            echo '-';
                                        }
                                    ?>
                                </td>
                                <td class="student-name">
                                    <?php echo htmlspecialchars((isset($student['first_name']) ? $student['first_name'] : '') . ' ' . (isset($student['last_name']) ? $student['last_name'] : '')); ?>
                                </td>
                                <?php 
                                $total_marks = 0;
                                $subject_count = 0;
                                $grade_points = 0;
                                $gpa_subjects = 0;
                                foreach ($subjects as $subject): 
                                    // Handle combined subjects
                                    if ($subject['id'] == 'combined_bangla') {
                                        $bangla_subjects = array_filter($original_subjects, function($s) { return (stripos($s['name'], 'বাংলা') !== false) || (stripos($s['name'], 'Bangla') !== false && stripos($s['name'], 'Bangladesh') === false); });
                                        $result = getCombinedBanglaResult($student['id'], $bangla_subjects, $results_matrix);
                                    } else if ($subject['id'] == 'combined_english') {
                                        $english_subjects = array_filter($original_subjects, function($s) { return stripos($s['name'], 'ইংরেজি') !== false || stripos($s['name'], 'English') !== false; });
                                        $result = getCombinedEnglishResult($student['id'], $english_subjects, $results_matrix);
                                    } else {
                                        $result = isset($results_matrix[$student['id']][$subject['id']]) ? $results_matrix[$student['id']][$subject['id']] : null;
                                    }
                                    ?>
                                    <?php 
                                    // Check if this is a 4th subject for highlighting
                                    $is_fourth_subject_cell = false;
                                    if ($result && isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                                        $is_fourth_subject_cell = true;
                                    }
                                    ?>
                                    <td<?php echo $is_fourth_subject_cell ? ' style="background-color: #ffeeba;"' : ''; ?>>
                                        <?php 
                                        if ($result) {
                                            // For combined subjects, show detailed breakdown
                                            if ($subject['id'] == 'combined_bangla' || $subject['id'] == 'combined_english') {
                                                // Check which toggle to use based on subject
                                                $use_avg = false;
                                                if ($subject['id'] == 'combined_bangla') {
                                                    $use_avg = $show_bangla_avg;
                                                } else if ($subject['id'] == 'combined_english') {
                                                    $use_avg = $show_english_avg;
                                                }
                                                
                                                // Calculate marks for display and total based on toggle
                                                $marks_for_display = $result['marks_obtained'];
                                                $marks_for_total = $result['marks_obtained'];
                                                
                                                if (isset($result['cq_marks_array']) && isset($result['mcq_marks_array']) && !empty($result['cq_marks_array']) && !empty($result['mcq_marks_array'])) {
                                                    if ($use_avg) {
                                                        // Use average: avg_cq + avg_mcq
                                                        $avg_cq = array_sum($result['cq_marks_array']) / count($result['cq_marks_array']);
                                                        $avg_mcq = array_sum($result['mcq_marks_array']) / count($result['mcq_marks_array']);
                                                        $marks_for_display = $avg_cq + $avg_mcq;
                                                        $marks_for_total = $marks_for_display;
                                                    } else {
                                                        // Use total: total_cq + total_mcq
                                                        $total_cq = array_sum($result['cq_marks_array']);
                                                        $total_mcq = array_sum($result['mcq_marks_array']);
                                                        $marks_for_display = $total_cq + $total_mcq; // Show total in cell when toggle is off
                                                        $marks_for_total = $marks_for_display;
                                                    }
                                                }
                                                
                                                // Show combined marks, grade, and grade point in brackets
                                                $grade_point_display = isset($result['grade_point']) ? number_format($result['grade_point'], 2) : '0.00';
                                                echo ceil($marks_for_display) . ' (' . $result['grade'] . ', GP: ' . $grade_point_display . ')';
                                                $total_marks += $marks_for_total;
                                                $subject_count++;
                                                
                                                // Show individual CQ and MCQ marks for each part
                                                if (isset($result['individual_results']) && !empty($result['individual_results'])) {
                                                    // For combined subjects, show individual parts
                                                    echo '<br><small>';
                                                    foreach ($result['individual_results'] as $index => $individual) {
                                                        if ($index > 0) echo '; ';
                                                        echo 'CQ-' . ceil($individual['cq_marks']) . ', MCQ-' . ceil($individual['mcq_marks']);
                                                    }
                                                    echo '</small>';
                                                } else if (isset($result['cq_marks']) || isset($result['mcq_marks'])) {
                                                    // Fallback to averaged marks
                                                    echo '<br><small>(';
                                                    if (isset($result['cq_marks'])) {
                                                        echo 'CQ: ' . ceil($result['cq_marks']);
                                                    }
                                                    if (isset($result['cq_marks']) && isset($result['mcq_marks'])) {
                                                        echo ', ';
                                                    }
                                                    if (isset($result['mcq_marks'])) {
                                                        echo 'MCQ: ' . ceil($result['mcq_marks']);
                                                    }
                                                    echo ')</small>';
                                                }
                                                
                                                // Use actual grade point from result for combined subjects
                                                if (isset($result['grade_point'])) {
                                                    if ($result['grade'] != 'F') {
                                                        $grade_points += $result['grade_point'];
                                                        $gpa_subjects++;
                                                    }
                                                }
                                            } else {
                                                // For regular subjects, calculate grade from marks if not already set
                                                $subject_grade = isset($result['grade']) ? $result['grade'] : 'F';
                                                
                                                // If grade is not set or is invalid, calculate it from marks
                                                if (!isset($result['grade']) || $result['grade'] == '' || $result['grade'] == 'F') {
                                                    if (isset($result['marks_obtained']) && isset($result['full_marks'])) {
                                                        $subject_grade = calculateGradeFromMarks($result['marks_obtained'], $result['full_marks']);
                                                    }
                                                }
                                                
                                                // Regular subject display with detailed marks
                                                $grade_point_value = getGradePoint($subject_grade);
                                                $grade_point_display = number_format($grade_point_value, 2);
                                                echo ceil($result['marks_obtained']) . ' (' . $subject_grade . ', GP: ' . $grade_point_display . ')';
                                                $total_marks += $result['marks_obtained'];
                                                $subject_count++;
                                                
                                                // Show detailed breakdown for regular subjects (CQ and MCQ marks)
                                                echo '<br><small>(';
                                                if (isset($result['cq_marks'])) {
                                                    echo 'CQ: ' . ceil($result['cq_marks']);
                                                }
                                                if (isset($result['cq_marks']) && isset($result['mcq_marks'])) {
                                                    echo ', ';
                                                }
                                                if (isset($result['mcq_marks'])) {
                                                    echo 'MCQ: ' . ceil($result['mcq_marks']);
                                                }
                                                echo ')</small>';
                                                
                                                // Calculate grade point from grade for regular subjects
                                                if ($subject_grade != 'F') {
                                                    $grade_point_value = getGradePoint($subject_grade);
                                                    $grade_points += $grade_point_value;
                                                    $gpa_subjects++;
                                                }
                                            }
                                        } else {
                                            echo '-';
                                        }
                                        ?>
                                    </td>
                                <?php endforeach; ?>
                                <td class="total-column"><?php echo ceil($total_marks); ?></td>
                                <td class="grade-column">
                                    <?php 
                                    // Calculate GPA with Jessore Board 4th subject rules
                                    $total_grade_points = 0;
                                    $has_failed_in_non_fourth_subject = false;
                                    $fourth_subject_grade_point = 0;
                                    $fourth_subject_found = false;
                                    $gpa_subjects_count = 0;
                                    
                                    // Recalculate GPA with proper 4th subject handling
                                    foreach ($subjects as $subject) {
                                        // Handle combined subjects
                                        if ($subject['id'] == 'combined_bangla') {
                                            $bangla_subjects = array_filter($original_subjects, function($s) { return (stripos($s['name'], 'বাংলা') !== false) || (stripos($s['name'], 'Bangla') !== false && stripos($s['name'], 'Bangladesh') === false); });
                                            $result = getCombinedBanglaResult($student['id'], $bangla_subjects, $results_matrix);
                                        } else if ($subject['id'] == 'combined_english') {
                                            $english_subjects = array_filter($original_subjects, function($s) { return stripos($s['name'], 'ইংরেজি') !== false || stripos($s['name'], 'English') !== false; });
                                            $result = getCombinedEnglishResult($student['id'], $english_subjects, $results_matrix);
                                        } else {
                                            $result = isset($results_matrix[$student['id']][$subject['id']]) ? $results_matrix[$student['id']][$subject['id']] : null;
                                        }
                                        
                                        if ($result && isset($result['grade'])) {
                                            // Check if student failed in this subject and it's not a fourth subject
                                            if ($result['grade'] == 'F' && !(isset($result['is_fourth_subject']) && $result['is_fourth_subject'])) {
                                                $has_failed_in_non_fourth_subject = true;
                                            }
                                            
                                            // Handle 4th subject GPA adjustment according to Jessore Board rules
                                            if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                                                $fourth_subject_found = true;
                                                // For 4th subject: add only the bonus points (grade_point - 2.00) if grade_point > 2.00
                                                // Otherwise, add 0 bonus points
                                                $grade_point = getGradePoint($result['grade']);
                                                if ($grade_point > 2.00) {
                                                    $total_grade_points += ($grade_point - 2.00);
                                                }
                                                // Count 4th subject in subject count (it contributes to the divisor adjustment)
                                                if ($result['grade'] != 'F') {
                                                    $gpa_subjects_count++; // Count subjects for GPA calculation
                                                }
                                            } else {
                                                // For regular subjects, calculate grade from marks if needed
                                                $subject_grade = isset($result['grade']) ? $result['grade'] : 'F';
                                                
                                                // If grade is not set or is invalid, calculate it from marks
                                                if (!isset($result['grade']) || $result['grade'] == '' || $result['grade'] == 'F') {
                                                    if (isset($result['marks_obtained']) && isset($result['full_marks'])) {
                                                        $subject_grade = calculateGradeFromMarks($result['marks_obtained'], $result['full_marks']);
                                                    }
                                                }
                                                
                                                // Regular subject - add full grade point
                                                $grade_point_to_add = getGradePoint($subject_grade);
                                                $total_grade_points += $grade_point_to_add;
                                                
                                                // Count regular subjects in subject count
                                                if ($subject_grade != 'F') {
                                                    $gpa_subjects_count++; // Count subjects for GPA calculation
                                                }
                                            }
                                        }
                                    }
                                    
                                    // Calculate final GPA with Jessore Board rules
                                    if ($has_failed_in_non_fourth_subject) {
                                        $gpa = 0.00;
                                        echo number_format($gpa, 2);
                                    } else if ($gpa_subjects_count > 0) {
                                        // For Jessore Board: when 4th subject exists, divide by (number of subjects - 1)
                                        // because 4th subject's extra points are added but the subject itself is not counted in division
                                        if ($fourth_subject_found) {
                                            // When 4th subject exists, divide by (gpa_subjects_count - 1)
                                            // Prevent division by zero when student has only one subject which is a fourth subject
                                            $divisor = ($gpa_subjects_count - 1) > 0 ? ($gpa_subjects_count - 1) : 1;
                                            $gpa = $total_grade_points / $divisor;
                                        } else {
                                            // Normal calculation
                                            $gpa = $total_grade_points / $gpa_subjects_count;
                                        }
                                        
                                        // 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;
                                        }
                                        
                                        // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
                                        if ($gpa > 5.00) {
                                            $gpa = 5.00;
                                        }
                                        
                                        $gpa = round($gpa, 2);
                                        
                                        $overall_grade = calculateOverallGradeFromGPA($gpa);
                                        echo number_format($gpa, 2) . ' (' . $overall_grade . ')';
                                    } else {
                                        echo '-';
                                    }
                                    ?>
                                </td>
                                <td class="grade-column">
                                    <?php 
                                    // Display merit position
                                    if (isset($student_merit_positions[$student['id']])) {
                                        echo $student_merit_positions[$student['id']];
                                    } else {
                                        echo '-'; // For students with GPA 0 or no merit position
                                    }
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Signatures -->
            <div class="signature-section">
                <div>
                    <div class="signature-box"> প্রধান শিক্ষক</div>
                </div>
                <div>
                    <div class="signature-box">পরীক্ষা কমিটি</div>
                </div>
                <div>
                    <div class="signature-box">পরীক্ষা কমিটির সদস্যবৃন্দ</div>
                </div>
            </div>
        </div>

        <?php elseif ($class_id && $session && $exam_type): ?>
        <div class="alert alert-warning text-center">
            <i class="fas fa-exclamation-triangle"></i> 
            নির্বাচিত ক্লাস, সেশন ও পরীক্ষার জন্য কোন ডেটা পাওয়া যায়নি।
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-submit form when sort option changes
        document.getElementById('sort_by').addEventListener('change', function() {
            this.form.submit();
        });
        
        // Toggle switches for Bengali and English marks display
        function updateToggleText(toggleId, textId) {
            const toggle = document.getElementById(toggleId);
            const text = document.getElementById(textId);
            if (toggle && text) {
                // Checked = show average (গড়), Unchecked = show total (মোট)
                text.textContent = toggle.checked ? 'গড়' : 'মোট';
            }
        }
        
        function handleToggleChange(toggleId, textId, paramName) {
            const toggle = document.getElementById(toggleId);
            if (!toggle) return;
            
            // Initialize toggle text based on current state
            updateToggleText(toggleId, textId);
            
            toggle.addEventListener('change', function() {
                // Update toggle text
                updateToggleText(toggleId, textId);
                
                // Get current URL parameters
                const urlParams = new URLSearchParams(window.location.search);
                // Set the parameter: checked means show average (true), unchecked means show total (false)
                urlParams.set(paramName, this.checked ? 'true' : 'false');
                
                // Reload page with new parameters
                window.location.search = urlParams.toString();
            });
        }
        
        // Handle Bengali toggle
        handleToggleChange('banglaToggle', 'banglaToggleText', 'show_bangla_avg');
        
        // Handle English toggle
        handleToggleChange('englishToggle', 'englishToggleText', 'show_english_avg');
        
        // Function to show/hide columns
        function toggleColumn(columnIndex, isVisible) {
            const table = document.querySelector('.tabulation-table');
            if (!table) return;
            
            const headerCells = table.querySelectorAll('thead th');
            const bodyRows = table.querySelectorAll('tbody tr');
            
            if (headerCells[columnIndex]) {
                headerCells[columnIndex].style.display = isVisible ? 'table-cell' : 'none';
            }
            
            bodyRows.forEach(row => {
                const cells = row.querySelectorAll('td');
                if (cells[columnIndex]) {
                    cells[columnIndex].style.display = isVisible ? 'table-cell' : 'none';
                }
            });
        }
        
        // Initialize column visibility based on checkbox states
        function initializeColumnVisibility() {
            // Roll column (index 0)
            const rollCheckbox = document.getElementById('showRollColumn');
            if (rollCheckbox) {
                rollCheckbox.addEventListener('change', function() {
                    toggleColumn(0, this.checked);
                });
                // Apply initial state
                toggleColumn(0, rollCheckbox.checked);
            }
            
            // Name column (index 1)
            const nameCheckbox = document.getElementById('showNameColumn');
            if (nameCheckbox) {
                nameCheckbox.addEventListener('change', function() {
                    toggleColumn(1, this.checked);
                });
                // Apply initial state
                toggleColumn(1, nameCheckbox.checked);
            }
            
            // Subject columns (starting from index 2)
            <?php foreach ($subjects as $index => $subject): ?>
            const subjectCheckbox_<?php echo $index; ?> = document.getElementById('showSubjectColumn_<?php echo $index; ?>');
            if (subjectCheckbox_<?php echo $index; ?>) {
                subjectCheckbox_<?php echo $index; ?>.addEventListener('change', function() {
                    toggleColumn(<?php echo $index + 2; ?>, this.checked);
                });
                // Apply initial state
                toggleColumn(<?php echo $index + 2; ?>, subjectCheckbox_<?php echo $index; ?>.checked);
            }
            <?php endforeach; ?>
            
            // Total column (after subject columns)
            const totalColumnIndex = 2 + <?php echo count($subjects); ?>;
            const totalCheckbox = document.getElementById('showTotalColumn');
            if (totalCheckbox) {
                totalCheckbox.addEventListener('change', function() {
                    toggleColumn(totalColumnIndex, this.checked);
                });
                // Apply initial state
                toggleColumn(totalColumnIndex, totalCheckbox.checked);
            }
            
            // Grade column (last column)
            const gradeColumnIndex = totalColumnIndex + 1;
            const gradeCheckbox = document.getElementById('showGradeColumn');
            if (gradeCheckbox) {
                gradeCheckbox.addEventListener('change', function() {
                    toggleColumn(gradeColumnIndex, this.checked);
                });
                // Apply initial state
                toggleColumn(gradeColumnIndex, gradeCheckbox.checked);
            }
        }
        
        // Function to select all column checkboxes
        function selectAllColumns() {
            // Check Roll column
            const rollCheckbox = document.getElementById('showRollColumn');
            if (rollCheckbox) {
                rollCheckbox.checked = true;
                toggleColumn(0, true);
            }
            
            // Check Name column
            const nameCheckbox = document.getElementById('showNameColumn');
            if (nameCheckbox) {
                nameCheckbox.checked = true;
                toggleColumn(1, true);
            }
            
            // Check Subject columns
            <?php foreach ($subjects as $index => $subject): ?>
            const subjectCheckbox_<?php echo $index; ?> = document.getElementById('showSubjectColumn_<?php echo $index; ?>');
            if (subjectCheckbox_<?php echo $index; ?>) {
                subjectCheckbox_<?php echo $index; ?>.checked = true;
                toggleColumn(<?php echo $index + 2; ?>, true);
            }
            <?php endforeach; ?>
            
            // Check Total column
            const totalCheckbox = document.getElementById('showTotalColumn');
            if (totalCheckbox) {
                totalCheckbox.checked = true;
                const totalColumnIndex = 2 + <?php echo count($subjects); ?>;
                toggleColumn(totalColumnIndex, true);
            }
            
            // Check Grade column
            const gradeCheckbox = document.getElementById('showGradeColumn');
            if (gradeCheckbox) {
                gradeCheckbox.checked = true;
                const gradeColumnIndex = 2 + <?php echo count($subjects); ?> + 1;
                toggleColumn(gradeColumnIndex, true);
            }
        }
        
        // Function to unselect all column checkboxes
        function unselectAllColumns() {
            // Uncheck Roll column
            const rollCheckbox = document.getElementById('showRollColumn');
            if (rollCheckbox) {
                rollCheckbox.checked = false;
                toggleColumn(0, false);
            }
            
            // Uncheck Name column
            const nameCheckbox = document.getElementById('showNameColumn');
            if (nameCheckbox) {
                nameCheckbox.checked = false;
                toggleColumn(1, false);
            }
            
            // Uncheck Subject columns
            <?php foreach ($subjects as $index => $subject): ?>
            const subjectCheckbox_<?php echo $index; ?> = document.getElementById('showSubjectColumn_<?php echo $index; ?>');
            if (subjectCheckbox_<?php echo $index; ?>) {
                subjectCheckbox_<?php echo $index; ?>.checked = false;
                toggleColumn(<?php echo $index + 2; ?>, false);
            }
            <?php endforeach; ?>
            
            // Uncheck Total column
            const totalCheckbox = document.getElementById('showTotalColumn');
            if (totalCheckbox) {
                totalCheckbox.checked = false;
                const totalColumnIndex = 2 + <?php echo count($subjects); ?>;
                toggleColumn(totalColumnIndex, false);
            }
            
            // Uncheck Grade column
            const gradeCheckbox = document.getElementById('showGradeColumn');
            if (gradeCheckbox) {
                gradeCheckbox.checked = false;
                const gradeColumnIndex = 2 + <?php echo count($subjects); ?> + 1;
                toggleColumn(gradeColumnIndex, false);
            }
        }
        
        // Run column visibility initialization after page loads
        document.addEventListener('DOMContentLoaded', function() {
            initializeColumnVisibility();
        });
    </script>
</body>
</html>