<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$site_address = $settings['site_address'] ?? 'ঠিকানা: গ্রাম/থানা, জেলা, বাংলাদেশ';
$logo_image = $settings['logo_image'] ?? null;
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;

// Function to calculate GPA with Jessore Board 4th subject rules
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: when 4th subject exists, divide total grade points by number of regular subjects
    // The 4th subject contributes bonus points but is not counted in the subject total for division
    if ($fourth_subject_found) {
        // When 4th subject exists, divide by number of regular subjects (gpa_subjects)
        // because 4th subject's bonus points are added but it's not counted in the division
        $gpa = $total_grade_points / $gpa_subjects;
    } else {
        // Normal calculation - divide by total number of 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);
}



// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

// Get teacher's assigned classes if user is a teacher
$teacher_id = null;
$assigned_class_ids = [];
if ($_SESSION['user_role'] == 'teacher') {
    // Get teacher ID
    $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch();
    if ($teacher) {
        $teacher_id = $teacher['id'];
        
        // Get assigned class IDs
        $stmt = $pdo->prepare("SELECT DISTINCT c.id FROM classes c WHERE (c.class_teacher_id = ? OR c.id IN (SELECT class_id FROM class_subjects WHERE teacher_id = ?)) AND c.status = 'active'");
        $stmt->execute([$teacher_id, $teacher_id]);
        $assigned_classes = $stmt->fetchAll();
        $assigned_class_ids = array_column($assigned_classes, 'id');
    }
}

// Get search parameters
$class_id = $_GET['class_id'] ?? '';
$session = $_GET['session'] ?? date('Y');
$exam_type = $_GET['exam_type'] ?? '';
$student_search = $_GET['student_search'] ?? '';
$student_id = $_GET['student_id'] ?? '';

$bulk_print_all = $_GET['bulk_print_all'] ?? false;
$selected_students = $_GET['selected_students'] ?? '';
$separate_print = $_GET['separate_print'] ?? false;

// For bulk print, clear student_id to avoid individual student display
if ($bulk_print_all) {
    $student_id = '';
}

// Get custom marks parameters
$custom_bangla_cq1 = isset($_GET['custom_bangla_cq1']) ? floatval($_GET['custom_bangla_cq1']) : null;
$custom_bangla_cq2 = isset($_GET['custom_bangla_cq2']) ? floatval($_GET['custom_bangla_cq2']) : null;
$custom_bangla_mcq1 = isset($_GET['custom_bangla_mcq1']) ? floatval($_GET['custom_bangla_mcq1']) : null;
$custom_bangla_mcq2 = isset($_GET['custom_bangla_mcq2']) ? floatval($_GET['custom_bangla_mcq2']) : null;
$custom_bangla_total = isset($_GET['custom_bangla_total']) ? floatval($_GET['custom_bangla_total']) : null;
$custom_english_cq1 = isset($_GET['custom_english_cq1']) ? floatval($_GET['custom_english_cq1']) : null;
$custom_english_cq2 = isset($_GET['custom_english_cq2']) ? floatval($_GET['custom_english_cq2']) : null;
$custom_english_mcq1 = isset($_GET['custom_english_mcq1']) ? floatval($_GET['custom_english_mcq1']) : null;
$custom_english_mcq2 = isset($_GET['custom_english_mcq2']) ? floatval($_GET['custom_english_mcq2']) : null;
$custom_english_total = isset($_GET['custom_english_total']) ? floatval($_GET['custom_english_total']) : null;

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

// Get merit position visibility parameter
$show_merit_position = isset($_GET['show_merit_position']) ? filter_var($_GET['show_merit_position'], FILTER_VALIDATE_BOOLEAN) : true;

// Show notification if custom marks are being applied
$show_custom_marks_notification = false;
if ($custom_bangla_cq1 !== null || $custom_bangla_cq2 !== null || $custom_bangla_mcq1 !== null || $custom_bangla_mcq2 !== null || $custom_bangla_total !== null || 
    $custom_english_cq1 !== null || $custom_english_cq2 !== null || $custom_english_mcq1 !== null || $custom_english_mcq2 !== null || $custom_english_total !== null) {
    $show_custom_marks_notification = true;
}

$student = null;
$results = [];
$subjects = [];
$merit_position = null;
$students_in_class = [];
$gpa = 0.00; // Add GPA variable

// Get classes for dropdown
if ($_SESSION['user_role'] == 'teacher' && !empty($assigned_class_ids)) {
    // Teacher: only show assigned classes
    $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
    $stmt = $pdo->prepare("SELECT id, name, section FROM classes WHERE id IN ($placeholders) AND status = 'active' ORDER BY name, section");
    $stmt->execute($assigned_class_ids);
    $classes = $stmt->fetchAll();
} else {
    // Admin: show all classes
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
    $classes = $stmt->fetchAll();
}

// Check if we're showing student list (after first search)
$show_student_list = false;
$all_students_data = [];

if ($class_id && $session && $exam_type) {
    $show_student_list = true;
    
    // Get students based on class, session, and exam type
    if ($bulk_print_all || $separate_print) {
        // For bulk print or separate print, get all students in the class
        $stmt = $pdo->prepare(
            "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
            FROM students s 
            WHERE s.class_id = ? AND s.status = 'active'
            ORDER BY s.roll_number, s.first_name, s.last_name
        ");
        $stmt->execute([$class_id]);
    } else {
        // For regular view, only get students who have results
        $stmt = $pdo->prepare(
            "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
            FROM students s 
            WHERE s.class_id = ? AND s.status = 'active'
            AND EXISTS (
                SELECT 1 FROM results r 
                WHERE r.student_id = s.id 
                AND r.session = ? 
                AND r.exam_type = ?
            )
            ORDER BY s.roll_number, s.first_name, s.last_name
        ");
        $stmt->execute([$class_id, $session, $exam_type]);
    }
    $all_students_in_class = $stmt->fetchAll();
    
    // Set students_in_class based on bulk_print_all or separate_print
    if ($bulk_print_all || $separate_print) {
        // For bulk print or separate print, use all students in the class
        $students_in_class = $all_students_in_class;
    } else {
        // Apply search filter only when not bulk printing
        if (!empty($student_search)) {
            $students_in_class = array_filter($all_students_in_class, function($student) use ($student_search) {
                $search_term = strtolower($student_search);
                return strpos(strtolower($student['first_name']), $search_term) !== false ||
                       strpos(strtolower($student['last_name']), $search_term) !== false ||
                       strpos($student['roll_number'], $search_term) !== false ||
                       strpos($student['student_id'], $search_term) !== false;
            });
        } else {
            $students_in_class = $all_students_in_class;
        }
        
        // If specific students are selected, filter to only those students
        if (!empty($selected_students)) {
            $selected_student_ids = explode(',', $selected_students);
            $students_in_class = array_filter($students_in_class, function($student) use ($selected_student_ids) {
                return in_array($student['id'], $selected_student_ids);
            });
        }
    }


    if (($bulk_print_all || $separate_print || !empty($selected_students)) && !empty($students_in_class)) {

        foreach ($students_in_class as $student_item) {

            // Get student details
            $stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section FROM students s JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
            $stmt->execute([$student_item['id']]);
            $student_data = $stmt->fetch();
            
            // Also get the group name for display
            $group_stmt = $pdo->prepare("SELECT group_name FROM students WHERE id = ?");
            $group_stmt->execute([$student_item['id']]);
            $group_data = $group_stmt->fetch();
            if ($group_data && !empty($group_data['group_name'])) {
                $student_data['group_name'] = $group_data['group_name'];
            } else {
                $student_data['group_name'] = '';
            }
            
            if ($student_data) {
                // Get all subjects selected by the student from student_subjects table
                $stmt = $pdo->prepare("SELECT ss.subject_id, ss.is_fourth_subject, s.name as subject_name, s.code as subject_code FROM student_subjects ss JOIN subjects s ON ss.subject_id = s.id WHERE ss.student_id = ? AND s.status = 'active' ORDER BY s.name");
                $stmt->execute([$student_item['id']]);
                $all_student_subjects = $stmt->fetchAll();
                
                // 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_item['id'], $session, $exam_type, $student_item['id'], $session, $exam_type]);
                $results_with_marks = $stmt->fetchAll();
                
                // Create a map of results by subject_id for easy lookup
                $results_map = [];
                foreach ($results_with_marks as $result) {
                    $results_map[$result['subject_id']] = $result;
                }
                
                // Create combined results array with all subjects
                $results = [];
                $has_missing_marks = false; // Track if any subject is missing marks
                
                foreach ($all_student_subjects as $subject) {
                    $subject_id = $subject['subject_id'];
                    
                    // If student has marks for this subject, use the result data
                    if (isset($results_map[$subject_id])) {
                        $results[] = $results_map[$subject_id];
                    } else {
                        // If student doesn't have marks, create a placeholder result with 'F' grade
                        $placeholder_result = [
                            'subject_id' => $subject_id,
                            'subject_name' => $subject['subject_name'],
                            'subject_code' => $subject['subject_code'],
                            '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' => 100,
                            'pass_marks' => 33,
                            'grade' => 'F', // Mark as failed if no marks
                            'grade_point' => 0.00,
                            'class_max_marks' => 0,
                            'is_fourth_subject' => $subject['is_fourth_subject'] ?? false
                        ];
                        
                        // Try to get subject-specific mark distribution
                        $stmt = $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->execute([$subject_id, $student_data['class_id'], $session, $exam_type]);
                        $smd = $stmt->fetch();
                        
                        if ($smd) {
                            $placeholder_result['full_marks'] = $smd['total_marks'];
                            $placeholder_result['pass_marks'] = $smd['overall_pass_marks'];
                        } else {
                            // Fallback to mark_distributions
                            $stmt = $pdo->prepare("SELECT total_marks, pass_marks as overall_pass_marks FROM mark_distributions WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                            $stmt->execute([$subject_id, $student_data['class_id'], $session, $exam_type]);
                            $md = $stmt->fetch();
                            
                            if ($md) {
                                $placeholder_result['full_marks'] = $md['total_marks'];
                                $placeholder_result['pass_marks'] = $md['overall_pass_marks'];
                            }
                        }
                        
                        $results[] = $placeholder_result;
                        $has_missing_marks = true; // Mark that we have missing marks
                    }
                }
                
                // Group subjects according to specific ordering requirements
                $bangla_results = [];
                $english_results = [];
                $science_math_ict_subjects = []; // Science, Math, and ICT (go at the top)
                $middle_subjects = [];           // Other subjects except special cases
                $economics_subjects = [];        // Economics (go in middle)
                $career_edu = [];                // Career Education
                $agri_edu = [];                  // Agricultural Education (goes at the very end)
                
                foreach ($results as $result) {
                    $subject_name = strtolower($result['subject_name']);
                    // Debug: Uncomment to see subject processing
                    
                    // Check if this is a Bangla subject (Bangla 1st/2nd Paper)
                    if (((stripos($result['subject_name'], 'বাংলা') !== false && stripos($result['subject_name'], 'পত্র') !== false) || (stripos($result['subject_name'], 'Bangla') !== false && stripos($result['subject_name'], 'Paper') !== false)) && stripos($result['subject_name'], 'বাংলাদেশ') === false && stripos($result['subject_name'], 'Bangladesh') === false) {
                        $bangla_results[] = $result;
                        // Debug: Show Bangla detection
                    }
                    // Check if this is an English subject (English 1st/2nd Paper)
                    else if (stripos($result['subject_name'], 'ইংরেজি') !== false || (stripos($result['subject_name'], 'English') !== false && stripos($result['subject_name'], 'Paper') !== false)) {
                        $english_results[] = $result;
                        // Debug: Show English detection
                    }
                    // Check for Science, Math, and ICT subjects (go at the top)
                    else if (strpos($subject_name, 'science') !== false || strpos($subject_name, 'বিজ্ঞান') !== false ||
                             strpos($subject_name, 'math') !== false || strpos($subject_name, 'গণিত') !== false ||
                             strpos($subject_name, 'ict') !== false) {
                        $science_math_ict_subjects[] = $result;
                    }
                    // Check for Economics subjects (go in middle)
                    else if (strpos($subject_name, 'economics') !== false || strpos($subject_name, 'অর্থনীতি') !== false) {
                        $economics_subjects[] = $result;
                    }
                    // Check for Career Education
                    else if (strpos($subject_name, 'career') !== false || strpos($subject_name, 'ক্যারিয়ার') !== false) {
                        $career_edu[] = $result;
                    }
                    // Check for Agricultural Education
                    else if (strpos($subject_name, 'agricultural') !== false || strpos($subject_name, 'কৃষি') !== false) {
                        $agri_edu[] = $result;
                        // Debug: Uncomment to see Agricultural Education detection
                    }
                    // All other subjects
                    else {
                        $middle_subjects[] = $result;
                    }
                }
                
                // Store the original results for use in maximum marks calculation
                $original_bangla_results = $bangla_results;
                $original_english_results = $english_results;
                
                // Process combined subjects first to place them at the top of the list
                $top_subjects = [];
                
                // Process Bangla subjects as a combined subject
                if (!empty($bangla_results)) {
                    // Combine Bangla and Bangla Grammar into one subject
                    $combined_bangla = combineBanglaSubjects($bangla_results);
                    $top_subjects[] = $combined_bangla;
                }
                
                // Process English subjects as a combined subject
                if (!empty($english_results)) {
                    // Combine English and English Grammar into one subject
                    $combined_english = combineEnglishSubjects($english_results);
                    $top_subjects[] = $combined_english;
                }
                
                // Sort Science/Math/ICT subjects by name to match subject list ordering
                usort($science_math_ict_subjects, function($a, $b) {
                    return strcmp($a['subject_name'], $b['subject_name']);
                });
                
                // Sort Economics subjects by name to match subject list ordering
                usort($economics_subjects, function($a, $b) {
                    return strcmp($a['subject_name'], $b['subject_name']);
                });
                
                // Apply custom layout only to middle subjects (excluding Science/Math/ICT and Economics)
                $ordered_middle_subjects = applyCustomLayout($middle_subjects);
                        
                // Combine all subjects in the required order
                // Order: Bangla/English (combined) -> Science/Math/ICT -> Other subjects (with custom layout) -> Economics -> Career Edu -> Agricultural Edu
                $combined_middle = array_merge($science_math_ict_subjects, $ordered_middle_subjects, $economics_subjects);
                        
                // Sort Career Education subjects by name to match subject list ordering
                usort($career_edu, function($a, $b) {
                    return strcmp($a['subject_name'], $b['subject_name']);
                });
                
                // Add Career Education if it exists
                if (!empty($career_edu)) {
                    $combined_middle = array_merge($combined_middle, $career_edu);
                }
                        
                // Sort Agricultural Education subjects by name to match subject list ordering
                usort($agri_edu, function($a, $b) {
                    return strcmp($a['subject_name'], $b['subject_name']);
                });
                
                // Add Agricultural Education at the very end if it exists
                if (!empty($agri_edu)) {
                    $combined_middle = array_merge($combined_middle, $agri_edu);
                }
                
                // Debug: Show counts
                        
                // Combine the top subjects with the rest of the subjects
                $results = array_merge($top_subjects, $combined_middle);
                
                // Move fourth subject to the end of the list
                $normal_subjects = [];
                $fourth_subjects = [];
                
                foreach ($results as $result) {
                    if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                        $fourth_subjects[] = $result;
                    } else {
                        $normal_subjects[] = $result;
                    }
                }
                
                // Combine subjects with fourth subject at the end
                $results = array_merge($normal_subjects, $fourth_subjects);
                
                // Ensure combined subjects have required fields
                foreach ($results as &$result) {
                    if ($result['subject_id'] == 'combined_bangla' || $result['subject_id'] == 'combined_english') {
                        // For combined subjects, try to get actual marks from subject_mark_distribution
                        // Use a generic subject ID to fetch the passing marks (we'll use the first Bangla/English subject ID)
                        $combined_subject_id = null;
                        if ($result['subject_id'] == 'combined_bangla' && !empty($original_bangla_results)) {
                            $combined_subject_id = $original_bangla_results[0]['subject_id'];
                        } else if ($result['subject_id'] == 'combined_english' && !empty($original_english_results)) {
                            $combined_subject_id = $original_english_results[0]['subject_id'];
                        }
                        
                        if ($combined_subject_id) {
                            $stmt = $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->execute([$combined_subject_id, $student_data['class_id'], $session, $exam_type]);
                            $smd = $stmt->fetch();
                            
                            if ($smd) {
                                $result['full_marks'] = $smd['total_marks'];
                                $result['pass_marks'] = $smd['overall_pass_marks'];
                            } else {
                                // Fallback to defaults
                                if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                                    $result['full_marks'] = 100;
                                }
                                if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                                    $result['pass_marks'] = 40;
                                }
                            }
                        } else {
                            // Fallback to defaults
                            if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                                $result['full_marks'] = 100;
                            }
                            if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                                $result['pass_marks'] = 40;
                            }
                        }
                    }
                }
                
                // Enhance results with subject-specific marks distribution and GP
                foreach ($results as &$result) {
                    // Try to get subject-specific mark distribution
                    $stmt = $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->execute([$result['subject_id'], $student_data['class_id'], $session, $exam_type]);
                    $smd = $stmt->fetch();
                    
                    if ($smd) {
                        $result['full_marks'] = $smd['total_marks'];
                        $result['pass_marks'] = $smd['overall_pass_marks'];
                    } else {
                        // Fallback to mark_distributions
                        $stmt = $pdo->prepare("SELECT total_marks, pass_marks as overall_pass_marks FROM mark_distributions WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                        $stmt->execute([$result['subject_id'], $student_data['class_id'], $session, $exam_type]);
                        $md = $stmt->fetch();
                        
                        if ($md) {
                            $result['full_marks'] = $md['total_marks'];
                            $result['pass_marks'] = $md['overall_pass_marks'];
                        } else {
                            // Default values
                            $result['full_marks'] = 100;
                            $result['pass_marks'] = 33; // Use 40 as default passing marks as requested
                        }
                    }
                    
                    // Add subject-based GP (Grade Point)
                    $result['grade_point'] = getGradePoint($result['grade']);
                    
                    // Get maximum obtained marks for this subject in the class
                    if ($result['subject_id'] == 'combined_bangla') {
                        // For combined Bangla, we need to find the maximum combined marks across all students in the class
                        // First, get all Bangla subject IDs
                        $bangla_ids = array_column($original_bangla_results, 'subject_id');
                        if (!empty($bangla_ids)) {
                            // Get all students in the class
                            $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                            $stmt->execute([$student_data['class_id']]);
                            $students = $stmt->fetchAll();
                                            
                            $max_combined_marks = 0;
                            foreach ($students as $student_row) {
                                $student_id_tmp = $student_row['id'];
                                                
                                // Get results for this student in all Bangla subjects - FIXED to avoid duplicates
                                $placeholders = str_repeat('?,', count($bangla_ids) - 1) . '?';
                                $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name, 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.subject_id IN ($placeholders) AND r.session = ? AND r.exam_type = ? AND r.id IN (SELECT MAX(id) FROM results WHERE student_id = ? AND subject_id IN ($placeholders) AND session = ? AND exam_type = ? GROUP BY subject_id)");
                                $params = array_merge([$student_id_tmp], $bangla_ids, [$session, $exam_type], [$student_id_tmp], $bangla_ids, [$session, $exam_type]);
                                $stmt->execute($params);
                                $student_results = $stmt->fetchAll();
                                                
                                if (!empty($student_results)) {
                                    // Combine Bangla subjects for this student using the same logic as combineBanglaSubjects
                                    $combined_for_student = combineBanglaSubjects($student_results);
                                    if ($combined_for_student && $combined_for_student['marks_obtained'] > $max_combined_marks) {
                                        $max_combined_marks = $combined_for_student['marks_obtained'];
                                    }
                                }
                            }
                                            
                            $result['class_max_marks'] = $max_combined_marks;
                        } else {
                            $result['class_max_marks'] = 0;
                        }
                    } else if ($result['subject_id'] == 'combined_english') {
                        // For combined English, we need to find the maximum combined marks across all students in the class
                        // First, get all English subject IDs
                        $english_ids = array_column($original_english_results, 'subject_id');
                        if (!empty($english_ids)) {
                            // Get all students in the class
                            $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                            $stmt->execute([$student_data['class_id']]);
                            $students = $stmt->fetchAll();
                                            
                            $max_combined_marks = 0;
                            foreach ($students as $student_row) {
                                $student_id_tmp = $student_row['id'];
                                                
                                // Get results for this student in all English subjects - FIXED to avoid duplicates
                                $placeholders = str_repeat('?,', count($english_ids) - 1) . '?';
                                $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name, 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.subject_id IN ($placeholders) AND r.session = ? AND r.exam_type = ? AND r.id IN (SELECT MAX(id) FROM results WHERE student_id = ? AND subject_id IN ($placeholders) AND session = ? AND exam_type = ? GROUP BY subject_id)");
                                $params = array_merge([$student_id_tmp], $english_ids, [$session, $exam_type], [$student_id_tmp], $english_ids, [$session, $exam_type]);
                                $stmt->execute($params);
                                $student_results = $stmt->fetchAll();
                                                
                                if (!empty($student_results)) {
                                    // Combine English subjects for this student using the same logic as combineEnglishSubjects
                                    $combined_for_student = combineEnglishSubjects($student_results);
                                    if ($combined_for_student && $combined_for_student['marks_obtained'] > $max_combined_marks) {
                                        $max_combined_marks = $combined_for_student['marks_obtained'];
                                    }
                                }
                            }
                                            
                            $result['class_max_marks'] = $max_combined_marks;
                        } else {
                            $result['class_max_marks'] = 0;
                        }
                    } else {
                        // For regular subjects
                        $stmt = $pdo->prepare("SELECT MAX(cq_marks + mcq_marks) as max_marks FROM results WHERE subject_id = ? AND session = ? AND exam_type = ? AND student_id IN (SELECT id FROM students WHERE class_id = ? AND status = 'active')");
                        $stmt->execute([$result['subject_id'], $session, $exam_type, $student_data['class_id']]);
                        $max_result = $stmt->fetch();
                        $result['class_max_marks'] = $max_result['max_marks'] ?? 0;
                    }
                    
                    // Check if this subject is a fourth subject
                    if ($result['subject_id'] == 'combined_bangla') {
                        // For combined Bangla, check if any of the original Bangla subjects is a fourth subject
                        $is_fourth_subject = false;
                        foreach ($original_bangla_results as $bangla_result) {
                            try {
                                $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                                $stmt->execute([$student_item['id'], $bangla_result['subject_id']]);
                                $subject_info = $stmt->fetch();
                                if ($subject_info && isset($subject_info['is_fourth_subject']) && $subject_info['is_fourth_subject']) {
                                    $is_fourth_subject = true;
                                    break;
                                }
                            } catch (Exception $e) {
                                // Column might not exist, ignore error
                                error_log("Error checking is_fourth_subject for Bangla: " . $e->getMessage());
                            }
                        }
                        $result['is_fourth_subject'] = $is_fourth_subject;
                    } else if ($result['subject_id'] == 'combined_english') {
                        // For combined English, check if any of the original English subjects is a fourth subject
                        $is_fourth_subject = false;
                        foreach ($original_english_results as $english_result) {
                            try {
                                $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                                $stmt->execute([$student_item['id'], $english_result['subject_id']]);
                                $subject_info = $stmt->fetch();
                                if ($subject_info && isset($subject_info['is_fourth_subject']) && $subject_info['is_fourth_subject']) {
                                    $is_fourth_subject = true;
                                    break;
                                }
                            } catch (Exception $e) {
                                // Column might not exist, ignore error
                                error_log("Error checking is_fourth_subject for English: " . $e->getMessage());
                            }
                        }
                        $result['is_fourth_subject'] = $is_fourth_subject;
                    } else {
                        // For regular subjects
                        try {
                            $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                            $stmt->execute([$student_item['id'], $result['subject_id']]);
                            $subject_info = $stmt->fetch();
                            
                            $result['is_fourth_subject'] = $subject_info && isset($subject_info['is_fourth_subject']) && $subject_info['is_fourth_subject'] ? true : false;
                        } catch (Exception $e) {
                            // Column might not exist, ignore error
                            error_log("Error checking is_fourth_subject for regular subject: " . $e->getMessage());
                            $result['is_fourth_subject'] = false;
                        }
                    }
                    
                    // Apply custom grading for combined Bangla and English subjects
                    if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                        // For combined Bangla: CQ average > 22 AND MCQ average > 9 to pass
                        $custom_grade = calculateBanglaGrade($result['cq_marks_array'], $result['mcq_marks'], $result['full_marks'], $result['pass_marks']);
                        $result['grade'] = $custom_grade;
                        $result['grade_point'] = getGradePoint($custom_grade);
                    } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                        // For combined English: CQ average > 32 to pass
                        $custom_grade = calculateEnglishGrade($result['cq_marks_array'], $result['full_marks'], $result['pass_marks']);
                        $result['grade'] = $custom_grade;
                        $result['grade_point'] = getGradePoint($custom_grade);
                    }
                }
                unset($result); // Break the reference with the last element
                
                // Calculate totals and GPA with Jessore Board 4th subject rules
                $total_marks = 0;
                $total_obtained = 0;
                $total_subjects = count($results);
                $passed_subjects = 0;
                $total_grade_points = 0;
                $gpa_subjects = 0; // Subjects used for GPA calculation (excluding failed 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) {
                    // For combined Bengali and English subjects, calculate full_marks based on toggle
                    $marks_for_total_calculation = $result['full_marks'];
                    if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                        isset($result['full_marks']) && $result['full_marks'] > 0) {
                        // Check which toggle to use based on subject
                        $use_avg = false;
                        if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                            $use_avg = $show_bangla_avg;
                        } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                            $use_avg = $show_english_avg;
                        }
                        
                        // If showing total, multiply by number of papers
                        if (!$use_avg) {
                            $paper_count = 2; // Default to 2 papers for combined subjects
                            if (isset($result['cq_marks_array'])) {
                                $paper_count = count($result['cq_marks_array']);
                            }
                            $marks_for_total_calculation = $result['full_marks'] * $paper_count;
                        }
                    }
                    
                    $total_marks += $marks_for_total_calculation;
                    
                    // For combined Bengali and English subjects, calculate obtained marks based on toggle
                    $marks_for_total = $result['marks_obtained'];
                    if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                        isset($result['cq_marks_array']) && isset($result['mcq_marks_array'])) {
                        // Check which toggle to use based on subject
                        $use_avg = false;
                        if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                            $use_avg = $show_bangla_avg;
                        } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                            $use_avg = $show_english_avg;
                        }
                        
                        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;
                        }
                    }
                    
                    $total_obtained += $marks_for_total;
                    
                    // Check if student failed in this subject and it's not a fourth subject
                    if ($result['grade'] == 'F' && !$result['is_fourth_subject']) {
                        $has_failed_in_non_fourth_subject = true;
                    }
                    
                    if ($result['grade'] != 'F') {
                        $passed_subjects++;
                        
                        // Handle fourth subject specially according to Jessore Board rules
                        if ($result['is_fourth_subject']) {
                            $fourth_subject_found = true;
                            $fourth_subject_grade_point = $result['grade_point'];
                            // Fourth subject contributes only bonus points
                            // It does NOT count as a regular subject in GPA calculation
                            // Bonus points = grade_point - 2.00 (if grade_point > 2.00), otherwise 0
                            $bonus_points = ($result['grade_point'] > 2.00) ? ($result['grade_point'] - 2.00) : 0;
                            $total_grade_points += $bonus_points;
                        } else {
                            // Regular subject - add full grade point and count in GPA calculation
                            $total_grade_points += $result['grade_point'];
                            $gpa_subjects++; // Count regular subjects for GPA calculation
                        }
                        // Fourth subject does not count toward subject total for GPA calculation
                    }
                }
                
                $percentage = $total_marks > 0 ? round(($total_obtained / $total_marks) * 100, 2) : 0;
                
                // If student failed in any non-fourth subject OR has missing marks, overall grade is F and GPA is 0
                $gpa = 0.00;
                if ($has_failed_in_non_fourth_subject || $has_missing_marks) {
                    $overall_grade = 'F';
                    $gpa = 0.00;
                } else {
                    $overall_grade = calculateOverallGrade($percentage, $passed_subjects, $total_subjects);
                    
                    // Calculate GPA (Grade Point Average) with Jessore Board rules
                    if ($gpa_subjects > 0) {
                        // Calculate GPA according to Jessore Board rules
                        // Fourth subject contributes bonus points but does not count toward subject total
                        if ($fourth_subject_found) {
                            // When fourth subject exists, divide by gpa_subjects (regular subjects count)
                            // The bonus points are already added to total_grade_points
                            if ($gpa_subjects > 0) {
                                $gpa = round($total_grade_points / $gpa_subjects, 2);
                            } else {
                                $gpa = 0.00;
                            }
                        } else {
                            // Normal calculation
                            $gpa = round($total_grade_points / $gpa_subjects, 2);
                        }
                    } else {
                        $gpa = 0.00; // GPA is 0.00 if all subjects are failed
                    }
                    
                    // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
                    if ($gpa > 5.00) {
                        $gpa = 5.00;
                    }
                }
                
                // Add student data to the array
                $all_students_data[] = [
                    'student' => $student_data,
                    'results' => $results,
                    'total_marks' => $total_marks,
                    'total_obtained' => $total_obtained,
                    'percentage' => $percentage,
                    'gpa' => $gpa,
                    'passed_subjects' => $passed_subjects,
                    'total_subjects' => $total_subjects
                ];
            }
        }
    }
}

// Calculate merit positions for all students in bulk print
$merit_positions = [];

// Check which sorting method to use
$sort_by_gpa = isset($_GET['sort_by_gpa']) ? filter_var($_GET['sort_by_gpa'], FILTER_VALIDATE_BOOLEAN) : false;
$sort_by_total_points = isset($_GET['sort_by_total_points']) ? filter_var($_GET['sort_by_total_points'], FILTER_VALIDATE_BOOLEAN) : false;

if (!empty($all_students_data)) {
    // Calculate merit positions based on ALL students in the class who have results
    // This ensures that when specific students are selected, their merit position
    // is calculated against all students in the class, not just the selected ones
    
    // Get ALL students in the class with results for merit calculation
    $stmt = $pdo->prepare(
        "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
        FROM students s 
        WHERE s.class_id = ? AND s.status = 'active'
        AND EXISTS (
            SELECT 1 FROM results r 
            WHERE r.student_id = s.id 
            AND r.session = ? 
            AND r.exam_type = ?
        )
        ORDER BY s.roll_number, s.first_name, s.last_name
    ");
    $stmt->execute([$class_id, $session, $exam_type]);
    $all_class_students_with_results = $stmt->fetchAll();
    
    // Calculate merit data for ALL students in class
    $all_class_merit_data = [];
    foreach ($all_class_students_with_results as $student_item) {
        // Get student results for GPA and total marks calculation
        $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_item['id'], $session, $exam_type, $student_item['id'], $session, $exam_type]);
        $results = $stmt->fetchAll();
        
        // Calculate total obtained marks for this student
        $total_obtained = 0;
        $gpa = 0.00; // Initialize GPA for this student
        $has_valid_marks = false; // Flag to check if student has at least some valid marks
        
        // Calculate GPA using the existing calculateGPA function
        $gpa = calculateGPA($results);
        
        // Calculate total obtained marks and check for valid marks
        foreach ($results as $result) {
            $total_obtained += $result['marks_obtained'] ?? 0;
            if ($result['marks_obtained'] > 0 || $result['cq_marks'] > 0 || $result['mcq_marks'] > 0) {
                $has_valid_marks = true;
            }
        }
        
        $all_class_merit_data[$student_item['id']] = [
            'total_obtained' => $total_obtained,
            'gpa' => $gpa,
            'has_valid_marks' => $has_valid_marks
        ];
    }

    // Now create student_merit_data for only the students we're displaying
    // but using the merit data calculated from ALL students in the class
    $student_merit_data = [];
    foreach ($all_students_data as $index => $student_data) {
        $current_student_id = $student_data['student']['id'];
        $student_merit_data[$current_student_id] = [
            'total_obtained' => $all_class_merit_data[$current_student_id]['total_obtained'] ?? $student_data['total_obtained'],
            'gpa' => $all_class_merit_data[$current_student_id]['gpa'] ?? $student_data['gpa'],
            'has_valid_marks' => $all_class_merit_data[$current_student_id]['has_valid_marks'] ?? false,
            'index' => $index // Store original index to update the right student in all_students_data
        ];
    }
    
    if ($sort_by_total_points) {
        // Sort by total points (main subjects + 4th subject bonus) (primary) and GPA (secondary)
        uasort($student_merit_data, function($a, $b) {
            // Primary sort: total points (main subjects + 4th subject bonus) (higher is better)
            if ($a['total_points_with_bonus'] != $b['total_points_with_bonus']) {
                return $b['total_points_with_bonus'] - $a['total_points_with_bonus']; // Descending order
            }
            // Secondary sort: GPA (higher is better)
            return $b['gpa'] - $a['gpa']; // Descending order
        });
    } elseif ($sort_by_gpa) {
        // Sort by GPA (primary) and total marks (secondary) for merit position calculation
        uasort($student_merit_data, function($a, $b) {
            // Primary sort: GPA (higher is better)
            if ($a['gpa'] != $b['gpa']) {
                return $b['gpa'] - $a['gpa']; // Descending order
            }
            // Secondary sort: total obtained marks (higher is better)
            return $b['total_obtained'] - $a['total_obtained']; // Descending order
        });
    } else {
        // Sort by GPA (primary) and total marks (secondary) for merit position calculation - DEFAULT BEHAVIOR
        uasort($student_merit_data, function($a, $b) {
            // Primary sort: GPA (higher is better)
            if ($a['gpa'] != $b['gpa']) {
                return $b['gpa'] - $a['gpa']; // Descending order
            }
            // Secondary sort: total obtained marks (higher is better)
            return $b['total_obtained'] - $a['total_obtained']; // Descending order
        });
    }
    
    // Create an array of merit positions based on GPA first, then total marks for tie-breaking, excluding students with GPA 0
    $position = 1;
    foreach ($student_merit_data as $current_student_id => $data) {
        // Only assign merit position to students with GPA > 0 AND valid marks entries
        if ($data['gpa'] > 0 && $all_class_merit_data[$current_student_id]['has_valid_marks'] === true) {
            $merit_positions[$current_student_id] = $position++;
        }
    }
    
    // Update the all_students_data array with merit positions
    foreach ($all_students_data as $index => &$student_data) {
        $current_student_id = $student_data['student']['id'];
        if (isset($merit_positions[$current_student_id])) {
            $all_students_data[$index]['merit_position'] = $merit_positions[$current_student_id];
        } else {
            // Students with GPA 0 OR without valid marks do not get a merit position
            $all_students_data[$index]['merit_position'] = null;
        }
    }
    unset($student_data); // Remove reference
}

if ($student_id && $session && $exam_type) {
    // Get student details
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, c.section 
        FROM students s 
        JOIN classes c ON s.class_id = c.id 
        WHERE s.id = ?
    ");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    if ($student) {
        // Get all subjects selected by the student from student_subjects table
        $stmt = $pdo->prepare("
            SELECT ss.subject_id, s.name as subject_name, s.code as subject_code
            FROM student_subjects ss
            JOIN subjects s ON ss.subject_id = s.id
            WHERE ss.student_id = ? AND s.status = 'active'
            ORDER BY s.name
        ");
        $stmt->execute([$student_id]);
        $all_student_subjects = $stmt->fetchAll();
        
        // 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_with_marks = $stmt->fetchAll();
        
        // Create a map of results by subject_id for easy lookup
        $results_map = [];
        foreach ($results_with_marks as $result) {
            $results_map[$result['subject_id']] = $result;
        }
        
        // Create combined results array with all subjects
        $results = [];
        $has_missing_marks = false; // Track if any subject is missing marks
        
        foreach ($all_student_subjects as $subject) {
            $subject_id = $subject['subject_id'];
            
            // If student has marks for this subject, use the result data
            if (isset($results_map[$subject_id])) {
                $results[] = $results_map[$subject_id];
            } else {
                // If student doesn't have marks, create a placeholder result with 'F' grade
                $placeholder_result = [
                    'subject_id' => $subject_id,
                    'subject_name' => $subject['subject_name'],
                    'subject_code' => $subject['subject_code'],
                    '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' => 100,
                    'pass_marks' => 33,
                    'grade' => 'F', // Mark as failed if no marks
                    'grade_point' => 0.00,
                    'class_max_marks' => 0,
                    'is_fourth_subject' => $subject['is_fourth_subject'] ?? false
                ];
                
                // Try to get subject-specific mark distribution
                $stmt = $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->execute([
                    $subject_id, 
                    $student['class_id'], 
                    $session, 
                    $exam_type
                ]);
                $smd = $stmt->fetch();
                
                if ($smd) {
                    $placeholder_result['full_marks'] = $smd['total_marks'];
                    $placeholder_result['pass_marks'] = $smd['overall_pass_marks'];
                } else {
                    // Fallback to mark_distributions
                    $stmt = $pdo->prepare("
                        SELECT total_marks, pass_marks as overall_pass_marks 
                        FROM mark_distributions 
                        WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                        LIMIT 1
                    ");
                    $stmt->execute([
                        $subject_id, 
                        $student['class_id'], 
                        $session, 
                        $exam_type
                    ]);
                    $md = $stmt->fetch();
                    
                    if ($md) {
                        $placeholder_result['full_marks'] = $md['total_marks'];
                        $placeholder_result['pass_marks'] = $md['overall_pass_marks'];
                    }
                }
                
                $results[] = $placeholder_result;
                $has_missing_marks = true; // Mark that we have missing marks
            }
        }
        
        // Group subjects according to specific ordering requirements
        $bangla_results = [];
        $english_results = [];
        $science_math_ict_subjects = []; // Science, Math, and ICT (go at the top)
        $middle_subjects = [];           // Other subjects except special cases
        $economics_subjects = [];        // Economics (go in middle)
        $career_edu = [];                // Career Education
        $agri_edu = [];                  // Agricultural Education (goes at the very end)
        
        foreach ($results as $result) {
            $subject_name = strtolower($result['subject_name']);
            
            // Check if this is a Bangla subject (Bangla or Bangla Grammar)
            if ((stripos($result['subject_name'], 'বাংলা') !== false && stripos($result['subject_name'], 'বাংলাদেশ') === false) || 
                (stripos($result['subject_name'], 'Bangla') !== false && stripos($result['subject_name'], 'Bangladesh') === false)) {
                $bangla_results[] = $result;
            }
            // Check if this is an English subject (English or English Grammar)
            else if (stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) {
                $english_results[] = $result;
            }
            // Check for Science, Math, and ICT subjects (go at the top)
            else if (strpos($subject_name, 'science') !== false || strpos($subject_name, 'বিজ্ঞান') !== false ||
                     strpos($subject_name, 'math') !== false || strpos($subject_name, 'গণিত') !== false ||
                     strpos($subject_name, 'ict') !== false) {
                $science_math_ict_subjects[] = $result;
            }
            // Check for Economics subjects (go in middle)
            else if (strpos($subject_name, 'economics') !== false || strpos($subject_name, 'অর্থনীতি') !== false) {
                $economics_subjects[] = $result;
            }
            // Check for Career Education
            else if (strpos($subject_name, 'career') !== false || strpos($subject_name, 'ক্যারিয়ার') !== false) {
                $career_edu[] = $result;
            }
            // Check for Agricultural Education
            else if (strpos($subject_name, 'agricultural') !== false || strpos($subject_name, 'কৃষি') !== false) {
                $agri_edu[] = $result;
            }
            // All other subjects
            else {
                $middle_subjects[] = $result;
            }
        }
        
        // Store the original results for use in maximum marks calculation
        $original_bangla_results = $bangla_results;
        $original_english_results = $english_results;
        
        // Process combined subjects first to place them at the top of the list
        $top_subjects = [];
        
        // Process Bangla subjects as a combined subject
        if (!empty($bangla_results)) {
            // Check for custom marks from GET/POST parameters
            $custom_bangla_cq1 = isset($_GET['custom_bangla_cq1']) ? floatval($_GET['custom_bangla_cq1']) : null;
            $custom_bangla_cq2 = isset($_GET['custom_bangla_cq2']) ? floatval($_GET['custom_bangla_cq2']) : null;
            $custom_bangla_mcq1 = isset($_GET['custom_bangla_mcq1']) ? floatval($_GET['custom_bangla_mcq1']) : null;
            $custom_bangla_mcq2 = isset($_GET['custom_bangla_mcq2']) ? floatval($_GET['custom_bangla_mcq2']) : null;
            $custom_bangla_total = isset($_GET['custom_bangla_total']) ? floatval($_GET['custom_bangla_total']) : null;
            
            // Combine Bangla and Bangla Grammar into one subject
            $combined_bangla = combineBanglaSubjects($bangla_results, $custom_bangla_cq1, $custom_bangla_cq2, $custom_bangla_mcq1, $custom_bangla_mcq2, $custom_bangla_total);
            $top_subjects[] = $combined_bangla;
        }
        
        // Process English subjects as a combined subject
        if (!empty($english_results)) {
            // Check for custom marks from GET/POST parameters
            $custom_english_cq1 = isset($_GET['custom_english_cq1']) ? floatval($_GET['custom_english_cq1']) : null;
            $custom_english_cq2 = isset($_GET['custom_english_cq2']) ? floatval($_GET['custom_english_cq2']) : null;
            $custom_english_mcq1 = isset($_GET['custom_english_mcq1']) ? floatval($_GET['custom_english_mcq1']) : null;
            $custom_english_mcq2 = isset($_GET['custom_english_mcq2']) ? floatval($_GET['custom_english_mcq2']) : null;
            $custom_english_total = isset($_GET['custom_english_total']) ? floatval($_GET['custom_english_total']) : null;
            
            // Combine English and English Grammar into one subject
            $combined_english = combineEnglishSubjects($english_results, $custom_english_cq1, $custom_english_cq2, $custom_english_mcq1, $custom_english_mcq2, $custom_english_total);
            $top_subjects[] = $combined_english;
        }
        
        // Sort Science/Math/ICT subjects by name to match subject list ordering
        usort($science_math_ict_subjects, function($a, $b) {
            return strcmp($a['subject_name'], $b['subject_name']);
        });
        
        // Sort Economics subjects by name to match subject list ordering
        usort($economics_subjects, function($a, $b) {
            return strcmp($a['subject_name'], $b['subject_name']);
        });
        
        // Apply custom layout only to middle subjects (excluding Science/Math/ICT and Economics)
        $ordered_middle_subjects = applyCustomLayout($middle_subjects);
        
        // Combine all subjects in the required order
        // Order: Bangla/English (combined) -> Science/Math/ICT -> Other subjects (with custom layout) -> Economics -> Career Edu -> Agricultural Edu
        $combined_middle = array_merge($science_math_ict_subjects, $ordered_middle_subjects, $economics_subjects);
        
        // Sort Career Education subjects by name to match subject list ordering
        usort($career_edu, function($a, $b) {
            return strcmp($a['subject_name'], $b['subject_name']);
        });
        
        // Add Career Education if it exists
        if (!empty($career_edu)) {
            $combined_middle = array_merge($combined_middle, $career_edu);
        }
        
        // Sort Agricultural Education subjects by name to match subject list ordering
        usort($agri_edu, function($a, $b) {
            return strcmp($a['subject_name'], $b['subject_name']);
        });
        
        // Add Agricultural Education at the very end if it exists
        if (!empty($agri_edu)) {
            $combined_middle = array_merge($combined_middle, $agri_edu);
        }
        
        // Combine the top subjects with the rest of the subjects
        $results = array_merge($top_subjects, $combined_middle);
        
        // Ensure combined subjects have required fields
        foreach ($results as &$result) {
            if ($result['subject_id'] == 'combined_bangla' || $result['subject_id'] == 'combined_english') {
                // For combined subjects, try to get actual marks from subject_mark_distribution
                // Use a generic subject ID to fetch the passing marks (we'll use the first Bangla/English subject ID)
                $combined_subject_id = null;
                if ($result['subject_id'] == 'combined_bangla' && !empty($original_bangla_results)) {
                    $combined_subject_id = $original_bangla_results[0]['subject_id'];
                } else if ($result['subject_id'] == 'combined_english' && !empty($original_english_results)) {
                    $combined_subject_id = $original_english_results[0]['subject_id'];
                }
                
                if ($combined_subject_id) {
                    $stmt = $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->execute([$combined_subject_id, $student['class_id'], $session, $exam_type]);
                    $smd = $stmt->fetch();
                    
                    if ($smd) {
                        $result['full_marks'] = $smd['total_marks'];
                        $result['pass_marks'] = $smd['overall_pass_marks'];
                    } else {
                        // Fallback to defaults
                        if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                            $result['full_marks'] = 100;
                        }
                        if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                            $result['pass_marks'] = 40;
                        }
                    }
                } else {
                    // Fallback to defaults
                    if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                        $result['full_marks'] = 100;
                    }
                    if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                        $result['pass_marks'] = 40;
                    }
                }
            }
        }
        
        // Enhance results with subject-specific marks distribution and GP
        foreach ($results as &$result) {
            // Try to get subject-specific mark distribution
            $stmt = $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->execute([
                $result['subject_id'], 
                $student['class_id'], 
                $session, 
                $exam_type
            ]);
            $smd = $stmt->fetch();
            
            if ($smd) {
                $result['full_marks'] = $smd['total_marks'];
                $result['pass_marks'] = $smd['overall_pass_marks'];
            } else {
                // Fallback to mark_distributions
                $stmt = $pdo->prepare("
                    SELECT total_marks, pass_marks as overall_pass_marks 
                    FROM mark_distributions 
                    WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                    LIMIT 1
                ");
                $stmt->execute([
                    $result['subject_id'], 
                    $student['class_id'], 
                    $session, 
                    $exam_type
                ]);
                $md = $stmt->fetch();
                
                if ($md) {
                    $result['full_marks'] = $md['total_marks'];
                    $result['pass_marks'] = $md['overall_pass_marks'];
                } else {
                    // Default values
                    $result['full_marks'] = 100;
                    $result['pass_marks'] = 33; // Use 40 as default passing marks as requested
                }
            }
            
            // Add subject-based GP (Grade Point)
            $result['grade_point'] = getGradePoint($result['grade']);
            
            // Get maximum obtained marks for this subject in the class
            if ($result['subject_id'] == 'combined_bangla') {
                // For combined Bangla, we need to find the maximum combined marks across all students in the class
                // First, get all Bangla subject IDs
                $bangla_ids = array_column($original_bangla_results, 'subject_id');
                if (!empty($bangla_ids)) {
                    // Get all students in the class
                    $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                    $stmt->execute([$student['class_id']]);
                    $students = $stmt->fetchAll();
                                    
                    $max_combined_marks = 0;
                    foreach ($students as $student_row) {
                        $student_id_tmp = $student_row['id'];
                                        
                        // Get results for this student in all Bangla subjects - FIXED to avoid duplicates
                        $placeholders = str_repeat('?,', count($bangla_ids) - 1) . '?';
                        $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name FROM results r LEFT JOIN subjects sub ON r.subject_id = sub.id WHERE r.student_id = ? AND r.subject_id IN ($placeholders) AND r.session = ? AND r.exam_type = ? AND r.id IN (SELECT MAX(id) FROM results WHERE student_id = ? AND subject_id IN ($placeholders) AND session = ? AND exam_type = ? GROUP BY subject_id)");
                        $params = array_merge([$student_id_tmp], $bangla_ids, [$session, $exam_type], [$student_id_tmp], $bangla_ids, [$session, $exam_type]);
                        $stmt->execute($params);
                        $student_results = $stmt->fetchAll();
                                        
                        if (!empty($student_results)) {
                            // Combine Bangla subjects for this student using the same logic as combineBanglaSubjects
                            $combined_for_student = combineBanglaSubjects($student_results);
                            if ($combined_for_student && $combined_for_student['marks_obtained'] > $max_combined_marks) {
                                $max_combined_marks = $combined_for_student['marks_obtained'];
                            }
                        }
                    }
                                    
                    $result['class_max_marks'] = $max_combined_marks;
                } else {
                    $result['class_max_marks'] = 0;
                }
            } else if ($result['subject_id'] == 'combined_english') {
                // For combined English, we need to find the maximum combined marks across all students in the class
                // First, get all English subject IDs
                $english_ids = array_column($original_english_results, 'subject_id');
                if (!empty($english_ids)) {
                    // Get all students in the class
                    $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                    $stmt->execute([$student['class_id']]);
                    $students = $stmt->fetchAll();
                                    
                    $max_combined_marks = 0;
                    foreach ($students as $student_row) {
                        $student_id_tmp = $student_row['id'];
                                        
                        // Get results for this student in all English subjects - FIXED to avoid duplicates
                        $placeholders = str_repeat('?,', count($english_ids) - 1) . '?';
                        $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name FROM results r LEFT JOIN subjects sub ON r.subject_id = sub.id WHERE r.student_id = ? AND r.subject_id IN ($placeholders) AND r.session = ? AND r.exam_type = ? AND r.id IN (SELECT MAX(id) FROM results WHERE student_id = ? AND subject_id IN ($placeholders) AND session = ? AND exam_type = ? GROUP BY subject_id)");
                        $params = array_merge([$student_id_tmp], $english_ids, [$session, $exam_type], [$student_id_tmp], $english_ids, [$session, $exam_type]);
                        $stmt->execute($params);
                        $student_results = $stmt->fetchAll();
                                        
                        if (!empty($student_results)) {
                            // Combine English subjects for this student using the same logic as combineEnglishSubjects
                            $combined_for_student = combineEnglishSubjects($student_results);
                            if ($combined_for_student && $combined_for_student['marks_obtained'] > $max_combined_marks) {
                                $max_combined_marks = $combined_for_student['marks_obtained'];
                            }
                        }
                    }
                                    
                    $result['class_max_marks'] = $max_combined_marks;
                } else {
                    $result['class_max_marks'] = 0;
                }
            } else {
                // For regular subjects
                $stmt = $pdo->prepare("SELECT MAX(cq_marks + mcq_marks) as max_marks FROM results WHERE subject_id = ? AND session = ? AND exam_type = ? AND student_id IN (SELECT id FROM students WHERE class_id = ? AND status = 'active')");
                $stmt->execute([$result['subject_id'], $session, $exam_type, $student['class_id']]);
                $max_result = $stmt->fetch();
                $result['class_max_marks'] = $max_result['max_marks'] ?? 0;
            }
            
            // Check if this subject is a fourth subject
            if ($result['subject_id'] == 'combined_bangla') {
                // For combined Bangla, check if any of the original Bangla subjects is a fourth subject
                $is_fourth_subject = false;
                foreach ($original_bangla_results as $bangla_result) {
                    // Check if the original Bangla result has the is_fourth_subject field
                    if (isset($bangla_result['is_fourth_subject']) && $bangla_result['is_fourth_subject']) {
                        $is_fourth_subject = true;
                        break;
                    }
                }
                $result['is_fourth_subject'] = $is_fourth_subject;
            } else if ($result['subject_id'] == 'combined_english') {
                // For combined English, check if any of the original English subjects is a fourth subject
                $is_fourth_subject = false;
                foreach ($original_english_results as $english_result) {
                    // Check if the original English result has the is_fourth_subject field
                    if (isset($english_result['is_fourth_subject']) && $english_result['is_fourth_subject']) {
                        $is_fourth_subject = true;
                        break;
                    }
                }
                $result['is_fourth_subject'] = $is_fourth_subject;
            } else {
                // For regular subjects, use the is_fourth_subject field from the query result
                $result['is_fourth_subject'] = $result['is_fourth_subject'] ?? false;
            }
            
            // Apply custom grading for combined Bangla and English subjects
            if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                // For combined Bangla: CQ average > 22 AND MCQ average > 9 to pass
                $custom_grade = calculateBanglaGrade($result['cq_marks_array'], $result['mcq_marks'], $result['full_marks'], $result['pass_marks']);
                $result['grade'] = $custom_grade;
                $result['grade_point'] = getGradePoint($custom_grade);
            } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                // For combined English: CQ average > 32 to pass
                $custom_grade = calculateEnglishGrade($result['cq_marks_array'], $result['full_marks'], $result['pass_marks']);
                $result['grade'] = $custom_grade;
                $result['grade_point'] = getGradePoint($custom_grade);
            }
        }
        unset($result); // Break the reference with the last element
        
        // Calculate totals and GPA with Jessore Board 4th subject rules
        $total_marks = 0;
        $total_obtained = 0;
        $total_subjects = count($results);
        $passed_subjects = 0;
        $total_grade_points = 0;
        $gpa_subjects = 0; // Subjects used for GPA calculation (excluding failed 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) {
            // For combined Bengali and English subjects, calculate full_marks based on toggle
            $marks_for_total_calculation = $result['full_marks'];
            if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                isset($result['full_marks']) && $result['full_marks'] > 0) {
                // Check which toggle to use based on subject
                $use_avg = false;
                if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                    $use_avg = $show_bangla_avg;
                } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                    $use_avg = $show_english_avg;
                }
                
                // If showing total, multiply by number of papers
                if (!$use_avg) {
                    $paper_count = 2; // Default to 2 papers for combined subjects
                    if (isset($result['cq_marks_array'])) {
                        $paper_count = count($result['cq_marks_array']);
                    }
                    $marks_for_total_calculation = $result['full_marks'] * $paper_count;
                }
            }
            
            $total_marks += $marks_for_total_calculation;
            
            // For combined Bengali and English subjects, calculate obtained marks based on toggle
            $marks_for_total = $result['marks_obtained'];
            if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                isset($result['cq_marks_array']) && isset($result['mcq_marks_array'])) {
                // Check which toggle to use based on subject
                $use_avg = false;
                if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                    $use_avg = $show_bangla_avg;
                } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                    $use_avg = $show_english_avg;
                }
                
                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;
                }
            }
            
            $total_obtained += $marks_for_total;
            
            // Check if student failed in this subject and it's not a fourth subject
            if ($result['grade'] == 'F' && !$result['is_fourth_subject']) {
                $has_failed_in_non_fourth_subject = true;
            }
            
            if ($result['grade'] != 'F') {
                $passed_subjects++;
                
                // Handle fourth subject specially according to Jessore Board rules
                if ($result['is_fourth_subject']) {
                    $fourth_subject_found = true;
                    $fourth_subject_grade_point = $result['grade_point'];
                    // Fourth subject contributes only bonus points
                    // It does NOT count as a regular subject in GPA calculation
                    // Bonus points = grade_point - 2.00 (if grade_point > 2.00), otherwise 0
                    $bonus_points = ($result['grade_point'] > 2.00) ? ($result['grade_point'] - 2.00) : 0;
                    $total_grade_points += $bonus_points;
                } else {
                    // Regular subject - add full grade point and count in GPA calculation
                    $total_grade_points += $result['grade_point'];
                    $gpa_subjects++; // Count regular subjects for GPA calculation
                }
                // Fourth subject does not count toward subject total for GPA calculation
            }
        }
        
        $percentage = $total_marks > 0 ? round(($total_obtained / $total_marks) * 100, 2) : 0;
        
        // If student failed in any non-fourth subject OR has missing marks, overall grade is F and GPA is 0
        if ($has_failed_in_non_fourth_subject || $has_missing_marks) {
            $overall_grade = 'F';
            $gpa = 0.00;
        } else {
            $overall_grade = calculateOverallGrade($percentage, $passed_subjects, $total_subjects);
            
            // Calculate GPA (Grade Point Average) with Jessore Board rules
            if ($gpa_subjects > 0) {
                // Calculate GPA according to Jessore Board rules
                // Fourth subject contributes bonus points but does not count toward subject total
                if ($fourth_subject_found) {
                    // When fourth subject exists, divide by gpa_subjects (regular subjects count)
                    // The bonus points are already added to total_grade_points
                    if ($gpa_subjects > 0) {
                        $gpa = round($total_grade_points / $gpa_subjects, 2);
                    } else {
                        $gpa = 0.00;
                    }
                } else {
                    // Normal calculation
                    $gpa = round($total_grade_points / $gpa_subjects, 2);
                }
            } else {
                $gpa = 0.00; // GPA is 0.00 if all subjects are failed
            }
            
            // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
            if ($gpa > 5.00) {
                $gpa = 5.00;
            }
        }
        
        // Calculate merit position based on total marks (primary) and GPA (secondary)
        if ($student && $session && $exam_type) {
            // Get all students in the same class with their total marks and GPA for merit calculation
            $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
            $stmt->execute([$student['class_id']]);
            $all_student_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            // Calculate total marks and GPA for each student
            $student_data = [];
            foreach ($all_student_ids as $sid) {
                // Get student results - FIXED to avoid duplicates
                $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name, 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)");
                $stmt->execute([$sid, $session, $exam_type, $sid, $session, $exam_type]);
                $student_results = $stmt->fetchAll();
                
                if (empty($student_results)) {
                    $student_data[$sid] = ['total_marks' => 0, 'gpa' => 0.00];
                    continue;
                }
                
                $total_marks = 0;
                $total_grade_points = 0;
                $gpa_subjects = 0;
                $student_failed = false;
                $fourth_subject_found = false;
                
                // Process each result to calculate total marks and GPA
                foreach ($student_results as $result) {
                    // Add to total marks
                    $total_marks += $result['marks_obtained'] ?? 0;
                    
                    // Get subject name for proper grading
                    $stmt = $pdo->prepare("SELECT name FROM subjects WHERE id = ?");
                    $stmt->execute([$result['subject_id']]);
                    $subject_data = $stmt->fetch();
                    $subject_name = $subject_data ? $subject_data['name'] : '';
                    
                    // Check if this subject is a fourth subject
                    $is_fourth_subject = $result['is_fourth_subject'] ?? false;
                    
                    // Apply custom grading for Bangla and English subjects
                    $subject_grade = $result['grade'];
                    if (stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'Bangla') !== false) {
                        // For Bangla: Check average of 2 CQ marks + MCQ marks
                        $cq_marks_array = [$result['cq_marks']]; // Simplified - in real system, this would be an array of individual CQ marks
                        $custom_grade = calculateBanglaGrade($cq_marks_array, $result['mcq_marks'], 100, 40); // Assuming 100 total marks and 40 pass marks
                        $subject_grade = $custom_grade;
                    } else if (stripos($subject_name, 'ইংরেজি') !== false || stripos($subject_name, 'English') !== false) {
                        // For English: Check CQ marks average
                        $cq_marks_array = [$result['cq_marks']]; // Simplified - in real system, this would be an array of individual CQ marks
                        $custom_grade = calculateEnglishGrade($cq_marks_array, 100, 40); // Assuming 100 total marks and 40 pass marks
                        $subject_grade = $custom_grade;
                    }
                    
                    if ($subject_grade == 'F') {
                        // Check if student failed in this subject and it's not a fourth subject
                        if (!$is_fourth_subject) {
                            $student_failed = true;
                        }
                    } else {
                        // Add grade point for GPA calculation (only for passed subjects)
                        if ($is_fourth_subject) {
                            $fourth_subject_found = true;
                            $fourth_subject_grade_point = getGradePoint($subject_grade);
                            // For 4th subject: add bonus points (grade_point - 2.00 if > 2.00, otherwise 0)
                            $bonus_points = ($fourth_subject_grade_point > 2.00) ? ($fourth_subject_grade_point - 2.00) : 0;
                            $total_grade_points += $bonus_points;
                            // Fourth subject does NOT count toward subject total for GPA calculation
                        } else {
                            // Regular subject - add full grade point
                            $total_grade_points += getGradePoint($subject_grade);
                            $gpa_subjects++; // Count regular subjects for GPA calculation
                        }
                    }
                }
                
                // Calculate final GPA for this student
                if ($student_failed) {
                    $student_data[$sid] = ['total_marks' => $total_marks, 'gpa' => 0.00];
                } else {
                    if ($gpa_subjects > 0) {
                        // Check if student has a fourth subject
                        $stmt = $pdo->prepare("SELECT COUNT(*) as fourth_count FROM student_subjects WHERE student_id = ? AND is_fourth_subject = 1");
                        $stmt->execute([$sid]);
                        $fourth_subject_count = $stmt->fetch()['fourth_count'];
                        
                        // Calculate GPA according to Jessore Board rules
                        // Fourth subject contributes bonus points but does not count toward subject total
                        if ($fourth_subject_count > 0) {
                            // When fourth subject exists, divide by gpa_subjects (regular subjects count)
                            // The bonus points are already added to total_grade_points
                            if ($gpa_subjects > 0) {
                                $gpa = round($total_grade_points / $gpa_subjects, 2);
                            } else {
                                $gpa = 0.00;
                            }
                        } else {
                            // Normal calculation
                            if ($gpa_subjects > 0) {
                                $gpa = round($total_grade_points / $gpa_subjects, 2);
                            } else {
                                $gpa = 0.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;
                        }
                        $student_data[$sid] = ['total_marks' => $total_marks, 'gpa' => $gpa];
                    } else {
                        $student_data[$sid] = ['total_marks' => $total_marks, 'gpa' => 0.00];
                    }
                }
            }
            
            // Sort students by total marks (descending) and then by GPA (descending) for tie-breaking
            uasort($student_data, function($a, $b) {
                // Primary sort: total marks (higher is better)
                if ($a['total_marks'] != $b['total_marks']) {
                    return $b['total_marks'] - $a['total_marks']; // Descending order
                }
                // Secondary sort: GPA (higher is better)
                return $b['gpa'] - $a['gpa']; // Descending order
            });
            
            // Create an array of student IDs ordered by merit position
            $merit_order = [];
            $position = 1;
            foreach ($student_data as $sid => $data) {
                $merit_order[$sid] = $position++;
            }
            
            // Get merit position for current student
            $merit_position = isset($merit_order[$student_id]) ? $merit_order[$student_id] : null;
        }
    }
}

// Function to combine Bangla subjects
function combineBanglaSubjects($bangla_results, $custom_cq1 = null, $custom_cq2 = null, $custom_mcq1 = null, $custom_mcq2 = null, $custom_total = null) {
    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;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_bangla';
        
        // Apply custom marks if provided
        if ($custom_cq1 !== null || $custom_cq2 !== null) {
            // Calculate average if both values are provided, otherwise use the available one
            if ($custom_cq1 !== null && $custom_cq2 !== null) {
                $result['cq_marks'] = ($custom_cq1 + $custom_cq2) / 2;
                $result['cq_marks_array'] = [$custom_cq1, $custom_cq2];
            } elseif ($custom_cq1 !== null) {
                $result['cq_marks'] = $custom_cq1;
                $result['cq_marks_array'] = [$custom_cq1];
            } elseif ($custom_cq2 !== null) {
                $result['cq_marks'] = $custom_cq2;
                $result['cq_marks_array'] = [$custom_cq2];
            }
        }
        if ($custom_mcq1 !== null || $custom_mcq2 !== null) {
            // Calculate average if both values are provided, otherwise use the available one
            if ($custom_mcq1 !== null && $custom_mcq2 !== null) {
                $result['mcq_marks'] = ($custom_mcq1 + $custom_mcq2) / 2;
                $result['mcq_marks_array'] = [$custom_mcq1, $custom_mcq2];
            } elseif ($custom_mcq1 !== null) {
                $result['mcq_marks'] = $custom_mcq1;
                $result['mcq_marks_array'] = [$custom_mcq1];
            } elseif ($custom_mcq2 !== null) {
                $result['mcq_marks'] = $custom_mcq2;
                $result['mcq_marks_array'] = [$custom_mcq2];
            }
        }
        if ($custom_total !== null) {
            $result['marks_obtained'] = $custom_total;
        } else {
            // Calculate normally if custom total not provided
            $result['marks_obtained'] = $result['cq_marks'] + $result['mcq_marks'];
        }
        
        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 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
    ];
    
    // 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;
    }
    
    // Apply custom marks if provided
    if ($custom_cq1 !== null || $custom_cq2 !== null) {
        // Calculate average if both values are provided, otherwise use the available one
        if ($custom_cq1 !== null && $custom_cq2 !== null) {
            $combined['cq_marks'] = ($custom_cq1 + $custom_cq2) / 2;
            if (count($combined['cq_marks_array']) >= 2) {
                $combined['cq_marks_array'][0] = $custom_cq1;
                $combined['cq_marks_array'][1] = $custom_cq2;
            } else {
                $combined['cq_marks_array'] = [$custom_cq1, $custom_cq2];
            }
        } elseif ($custom_cq1 !== null) {
            $combined['cq_marks'] = $custom_cq1;
            if (count($combined['cq_marks_array']) > 0) {
                $combined['cq_marks_array'][0] = $custom_cq1;
            } else {
                $combined['cq_marks_array'] = [$custom_cq1];
            }
        } elseif ($custom_cq2 !== null) {
            $combined['cq_marks'] = $custom_cq2;
            if (count($combined['cq_marks_array']) > 0) {
                $combined['cq_marks_array'][1] = $custom_cq2;
            } else {
                $combined['cq_marks_array'] = [0, $custom_cq2];
            }
        }
    }
    if ($custom_mcq1 !== null || $custom_mcq2 !== null) {
        // Calculate average if both values are provided, otherwise use the available one
        if ($custom_mcq1 !== null && $custom_mcq2 !== null) {
            $combined['mcq_marks'] = ($custom_mcq1 + $custom_mcq2) / 2;
            if (count($combined['mcq_marks_array']) >= 2) {
                $combined['mcq_marks_array'][0] = $custom_mcq1;
                $combined['mcq_marks_array'][1] = $custom_mcq2;
            } else {
                $combined['mcq_marks_array'] = [$custom_mcq1, $custom_mcq2];
            }
        } elseif ($custom_mcq1 !== null) {
            $combined['mcq_marks'] = $custom_mcq1;
            if (count($combined['mcq_marks_array']) > 0) {
                $combined['mcq_marks_array'][0] = $custom_mcq1;
            } else {
                $combined['mcq_marks_array'] = [$custom_mcq1];
            }
        } elseif ($custom_mcq2 !== null) {
            $combined['mcq_marks'] = $custom_mcq2;
            if (count($combined['mcq_marks_array']) > 0) {
                $combined['mcq_marks_array'][1] = $custom_mcq2;
            } else {
                $combined['mcq_marks_array'] = [0, $custom_mcq2];
            }
        }
    }
    if ($custom_total !== null) {
        $combined['marks_obtained'] = $custom_total;
    } else {
        // Calculate normally if custom total not provided
        $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
    }
    
    // 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;
}

// Function to combine English subjects
function combineEnglishSubjects($english_results, $custom_cq1 = null, $custom_cq2 = null, $custom_mcq1 = null, $custom_mcq2 = null, $custom_total = null) {
    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;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_english';
        
        // Apply custom marks if provided
        if ($custom_cq1 !== null || $custom_cq2 !== null) {
            // Calculate average if both values are provided, otherwise use the available one
            if ($custom_cq1 !== null && $custom_cq2 !== null) {
                $result['cq_marks'] = ($custom_cq1 + $custom_cq2) / 2;
                $result['cq_marks_array'] = [$custom_cq1, $custom_cq2];
            } elseif ($custom_cq1 !== null) {
                $result['cq_marks'] = $custom_cq1;
                $result['cq_marks_array'] = [$custom_cq1];
            } elseif ($custom_cq2 !== null) {
                $result['cq_marks'] = $custom_cq2;
                $result['cq_marks_array'] = [$custom_cq2];
            }
        }
        if ($custom_mcq1 !== null || $custom_mcq2 !== null) {
            // Calculate average if both values are provided, otherwise use the available one
            if ($custom_mcq1 !== null && $custom_mcq2 !== null) {
                $result['mcq_marks'] = ($custom_mcq1 + $custom_mcq2) / 2;
                $result['mcq_marks_array'] = [$custom_mcq1, $custom_mcq2];
            } elseif ($custom_mcq1 !== null) {
                $result['mcq_marks'] = $custom_mcq1;
                $result['mcq_marks_array'] = [$custom_mcq1];
            } elseif ($custom_mcq2 !== null) {
                $result['mcq_marks'] = $custom_mcq2;
                $result['mcq_marks_array'] = [$custom_mcq2];
            }
        }
        if ($custom_total !== null) {
            $result['marks_obtained'] = $custom_total;
        } else {
            // Calculate normally if custom total not provided
            $result['marks_obtained'] = $result['cq_marks'] + $result['mcq_marks'];
        }
        
        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);
    }
    
    // Average the marks for proper grading
    $count = count($english_results);
    if ($count > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $count;
        $combined['mcq_marks'] = $combined['mcq_marks'] / $count;
        // For English: obtained marks = CQ average + MCQ average (as per user requirement)
        $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
        $combined['full_marks'] = $combined['full_marks'] / $count;
        $combined['pass_marks'] = $combined['pass_marks'] / $count;
    }
    
    // Apply custom marks if provided
    if ($custom_cq1 !== null || $custom_cq2 !== null) {
        // Calculate average if both values are provided, otherwise use the available one
        if ($custom_cq1 !== null && $custom_cq2 !== null) {
            $combined['cq_marks'] = ($custom_cq1 + $custom_cq2) / 2;
            if (count($combined['cq_marks_array']) >= 2) {
                $combined['cq_marks_array'][0] = $custom_cq1;
                $combined['cq_marks_array'][1] = $custom_cq2;
            } else {
                $combined['cq_marks_array'] = [$custom_cq1, $custom_cq2];
            }
        } elseif ($custom_cq1 !== null) {
            $combined['cq_marks'] = $custom_cq1;
            if (count($combined['cq_marks_array']) > 0) {
                $combined['cq_marks_array'][0] = $custom_cq1;
            } else {
                $combined['cq_marks_array'] = [$custom_cq1];
            }
        } elseif ($custom_cq2 !== null) {
            $combined['cq_marks'] = $custom_cq2;
            if (count($combined['cq_marks_array']) > 0) {
                $combined['cq_marks_array'][1] = $custom_cq2;
            } else {
                $combined['cq_marks_array'] = [0, $custom_cq2];
            }
        }
    }
    if ($custom_mcq1 !== null || $custom_mcq2 !== null) {
        // Calculate average if both values are provided, otherwise use the available one
        if ($custom_mcq1 !== null && $custom_mcq2 !== null) {
            $combined['mcq_marks'] = ($custom_mcq1 + $custom_mcq2) / 2;
            if (count($combined['mcq_marks_array']) >= 2) {
                $combined['mcq_marks_array'][0] = $custom_mcq1;
                $combined['mcq_marks_array'][1] = $custom_mcq2;
            } else {
                $combined['mcq_marks_array'] = [$custom_mcq1, $custom_mcq2];
            }
        } elseif ($custom_mcq1 !== null) {
            $combined['mcq_marks'] = $custom_mcq1;
            if (count($combined['mcq_marks_array']) > 0) {
                $combined['mcq_marks_array'][0] = $custom_mcq1;
            } else {
                $combined['mcq_marks_array'] = [$custom_mcq1];
            }
        } elseif ($custom_mcq2 !== null) {
            $combined['mcq_marks'] = $custom_mcq2;
            if (count($combined['mcq_marks_array']) > 0) {
                $combined['mcq_marks_array'][1] = $custom_mcq2;
            } else {
                $combined['mcq_marks_array'] = [0, $custom_mcq2];
            }
        }
    }
    if ($custom_total !== null) {
        $combined['marks_obtained'] = $custom_total;
    } else {
        // Calculate normally if custom total not provided
        $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
    }
    
    return $combined;
}

function calculateOverallGrade($percentage, $passed_subjects, $total_subjects) {
    // If failed in any subject, overall grade is F
    if ($passed_subjects < $total_subjects) {
        return 'F';
    }
    
    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';
}

// New function to calculate grade based on GPA
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 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 apply custom layout to results
function applyCustomLayout($results, $layout_name = null) {
    // If no layout specified, check for default layout
    if ($layout_name === null && isset($_SESSION['default_layout'])) {
        $layout_name = $_SESSION['default_layout'];
    }
    
    // Also check for subject layout from marks setup
    $subject_layout_name = null;
    if (isset($_SESSION['default_subject_layout'])) {
        $subject_layout_name = $_SESSION['default_subject_layout'];
    }
    
    // Determine which layout to use
    $actual_layout_name = null;
    $layout_source = null;
    
    // Priority: explicit layout > custom layout > subject layout
    if ($layout_name !== null && isset($_SESSION['custom_layout_' . $layout_name])) {
        $actual_layout_name = $layout_name;
        $layout_source = 'custom_layout_';
    } else if (isset($_SESSION['default_layout']) && isset($_SESSION['custom_layout_' . $_SESSION['default_layout']])) {
        $actual_layout_name = $_SESSION['default_layout'];
        $layout_source = 'custom_layout_';
    } else if ($subject_layout_name !== null && isset($_SESSION['subject_layout_' . $subject_layout_name])) {
        $actual_layout_name = $subject_layout_name;
        $layout_source = 'subject_layout_';
    } else if (isset($_SESSION['default_subject_layout']) && isset($_SESSION['subject_layout_' . $_SESSION['default_subject_layout']])) {
        $actual_layout_name = $_SESSION['default_subject_layout'];
        $layout_source = 'subject_layout_';
    }
    
    // If we have a layout name, apply it
    if ($actual_layout_name !== null && $layout_source !== null && isset($_SESSION[$layout_source . $actual_layout_name])) {
        $saved_order = explode(',', $_SESSION[$layout_source . $actual_layout_name]);
        $ordered_results = [];
        
        // First add subjects in the saved order
        foreach ($saved_order as $subject_id) {
            foreach ($results as $result) {
                if (isset($result['subject_id']) && $result['subject_id'] == $subject_id) {
                    $ordered_results[] = $result;
                    break;
                }
            }
        }
        
        // Then add any remaining subjects not in the saved order
        foreach ($results as $result) {
            $found = false;
            foreach ($saved_order as $subject_id) {
                if (isset($result['subject_id']) && $result['subject_id'] == $subject_id) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $ordered_results[] = $result;
            }
        }
        
        return $ordered_results;
    }
    
    // Return results sorted by subject name if no layout to apply (matches subject list default ordering)
    usort($results, function($a, $b) {
        return strcmp($a['subject_name'], $b['subject_name']);
    });
    return $results;
}

// Custom function to calculate Bangla subject grade based on new criteria
// For Bangla: CQ average > 22 AND MCQ average > 9 to pass
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';
    }
}

// Custom function to calculate English subject grade based on new criteria
// For English: CQ average > 32 to pass
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';
    }
}

// Get available sessions
$stmt = $pdo->query("SELECT DISTINCT session FROM results ORDER BY session DESC");
$sessions = $stmt->fetchAll();

// Get available exam types
$stmt = $pdo->query("SELECT DISTINCT exam_type FROM results ORDER BY exam_type");
$exam_types = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>সকল বিষয়ের মার্কশীট - স্কুল ম্যানেজমেন্ট সিস্টেম</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">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            font-size: 12px; /* Reduced from default */
        }
        
        .marksheet {
            border: 2px solid #2c3e50;
            padding: 12px; /* Reduced from 20px for better A4 fit */
            margin: 10px auto; /* Reduced from 20px for better A4 fit */
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            border-radius: 8px; /* Reduced from 12px */
            max-width: 210mm; /* A4 width */
            width: calc(210mm - 20px); /* Account for padding */
            position: relative;
            overflow: hidden;
        }
        
        .school-header {
            text-align: center;
            border-bottom: 2px double #3498db;
            padding-bottom: 10px; /* Reduced from 15px */
            margin-bottom: 15px; /* Reduced from 20px */
            background: linear-gradient(to right, #ffffff, #e3f2fd, #ffffff);
            border-radius: 6px 6px 0 0; /* Reduced from 8px */
            margin-left: -15px; /* Reduced from -20px */
            margin-right: -15px; /* Reduced from -20px */
            padding-left: 15px; /* Reduced from 20px */
            padding-right: 15px; /* Reduced from 20px */
            position: relative;
        }
        
        .school-logo {
            width: 60px; /* Reduced from 80px */
            height: 60px; /* Reduced from 80px */
            border: 2px solid #3498db; /* Reduced from 3px */
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 8px; /* Reduced from 12px */
            background: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* Reduced from 0 4px 8px */
            overflow: hidden;
        }
        
        .school-header h3 {
            color: #2c3e50;
            font-weight: 700;
        }
        
        /* Fourth Subject Container Styles */
        .fourth-subject-container {
            margin-top: 15px; /* Reduced for better A4 fit */
            border: 2px solid #3498db;
            border-radius: 8px;
            padding: 12px; /* Reduced for better A4 fit */
            background-color: #e3f2fd;
            width: calc(100% - 25px); /* Account for padding and border */
            max-width: 210mm; /* A4 width */
        }
        
        .fourth-subject-container h4 {
            text-align: center;
            color: #2980b9;
            margin-bottom: 15px;
            font-weight: bold;
        }
        
        .fourth-subject-details {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
        }
        
        .subject-name-code {
            flex: 1;
            min-width: 200px;
            margin-bottom: 10px;
        }
        
        .marks-details {
            flex: 2;
            min-width: 300px;
        }
        
        .fourth-subject-marks-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .fourth-subject-marks-table th {
            background-color: #3498db;
            color: white;
            border: 1px solid #2980b9;
            padding: 6px;
            text-align: center;
        }
        
        .fourth-subject-marks-table td {
            border: 1px solid #dee2e6;
            padding: 6px;
            text-align: center;
        }
        
        .fourth-subject-marks-table tbody tr {
            background-color: white;
        }
        
        .school-header h3 {
            margin: 8px 0 3px 0; /* Reduced from 10px 0 5px 0 */
            text-shadow: 1px 1px 1px rgba(0,0,0,0.1); /* Reduced from 2px */
            font-size: 20px; /* Reduced from 24px */
        }
        
        .school-header h4 {
            color: #e74c3c;
            font-weight: 600;
            margin: 10px 0 0 0; /* Reduced from 15px */
            text-decoration: underline;
            text-underline-offset: 5px; /* Reduced from 8px */
            font-size: 16px; /* Reduced from 18px */
        }
        
        .student-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px; /* Reduced from 15px for better A4 fit */
            margin-bottom: 12px; /* Reduced from 20px for better A4 fit */
            background: #f8f9fa;
            padding: 10px; /* Reduced from 15px for better A4 fit */
            border-radius: 6px; /* Reduced from 8px */
            border: 1px solid #e9ecef;
            font-size: 10px; /* Ensure text fits better on A4 */
        }
        
        .info-row {
            display: flex;
            margin-bottom: 5px; /* Reduced from 8px */
            align-items: center;
        }
        
        .info-label {
            font-weight: 600;
            min-width: 100px; /* Reduced from 120px */
            color: #2c3e50;
            font-size: 12px; /* Reduced from 14px */
        }
        
        .info-value {
            border-bottom: 1px dotted #3498db; /* Reduced from 2px */
            flex: 1;
            padding-left: 8px; /* Reduced from 10px */
            font-weight: 500;
            color: #34495e;
            font-size: 12px; /* Reduced from 14px */
        }
        
        .marks-table {
            width: 100%;
            border-collapse: collapse;
            margin: 12px 0; /* Reduced from 20px for better A4 fit */
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05); /* Reduced from 0 2px 10px */
            border-radius: 6px; /* Reduced from 8px */
            overflow: hidden;
            font-size: 10px; /* Reduced from default for better A4 fit */
            table-layout: fixed; /* Ensure table fits within container */
        }
        
        .marks-table th,
        .marks-table td {
            border: 1px solid #dee2e6;
            padding: 6px; /* Reduced from 8px */
            text-align: center;
            font-size: 11px; /* Reduced from 14px */
        }
        
        .marks-table th {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px; /* Reduced from 0.5px */
        }
        
        .marks-table tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .marks-table tbody tr:hover {
            background-color: #e3f2fd;
            transition: background-color 0.2s; /* Reduced from 0.3s */
        }
        
        .result-summary {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px; /* Reduced from 25px for better A4 fit */
            margin-top: 12px; /* Reduced from 20px for better A4 fit */
            padding-top: 12px; /* Reduced from 20px for better A4 fit */
            border-top: 1px dashed #3498db; /* Reduced from 2px */
            background: #f8f9fa;
            padding: 10px; /* Reduced from 15px for better A4 fit */
            border-radius: 6px; /* Reduced from 8px */
            font-size: 10px; /* Ensure text fits better on A4 */
        }
        
        .signature-section {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 10px; /* Reduced from 25px for better A4 fit */
            margin-top: 15px; /* Reduced from 30px for better A4 fit */
            text-align: center;
            font-size: 9px; /* Smaller text for better A4 fit */
        }
        
        .signature-box {
            border-top: 1px solid #3498db; /* Reduced from 2px */
            padding-top: 8px; /* Reduced from 10px */
            margin-top: 20px; /* Reduced from 30px */
            font-weight: 600;
            color: #2c3e50;
            font-size: 12px; /* Reduced from 14px */
        }
        
        .grade-scale {
            font-size: 9px; /* Reduced from 12px */
            margin-top: 20px; /* Reduced from 25px */
            padding: 10px; /* Reduced from 15px */
            background: #e3f2fd;
            border-radius: 6px; /* Reduced from 8px */
            border-left: 2px solid #3498db; /* Reduced from 4px */
        }
        
        .grade-scale strong {
            color: #2c3e50;
        }
        
        .student-list-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0; /* Reduced from 20px */
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05); /* Reduced from 0 2px 10px */
            border-radius: 6px; /* Reduced from 8px */
            overflow: hidden;
            font-size: 12px; /* Reduced from default */
        }
        
        .student-list-table th,
        .student-list-table td {
            border: 1px solid #dee2e6;
            padding: 8px; /* Reduced from 12px */
            text-align: center;
        }
        
        .student-list-table th {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            font-weight: 600;
        }
        
        .student-list-table tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .student-list-table tbody tr:hover {
            background-color: #e3f2fd;
            cursor: pointer;
            transition: background-color 0.2s; /* Reduced from 0.3s */
        }
        
        @media print {
            /* Define A4 page size and margins */
            @page {
                size: A4;
                margin: 0.5in;
            }
            
            .no-print { display: none !important; }
            .container-fluid { max-width: 100% !important; }
            .page-break-container {
                page-break-inside: avoid;
                page-break-after: always !important; /* Force page break after each container */
                break-after: page; /* Modern CSS alternative */
                margin-bottom: 50px !important;
                min-height: 1100px !important; /* Ensure container takes full page height */
            }
            .page-break-container:last-child {
                page-break-after: avoid !important; /* Don't break after the last one */
                break-after: avoid !important;
            }
            body { 
                font-size: 10px; /* Reduced for print */
                font-family: 'Hind Siliguri', sans-serif;
                width: 210mm; /* A4 width */
                height: 297mm; /* A4 height */
                margin: 0;
                padding: 0;
            }
            .marksheet {
                page-break-inside: avoid;
                box-shadow: none;
                border: 2px solid #000 !important;
                padding: 10px;
                background: white;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
                width: calc(100% - 20px); /* Account for border and padding */
                min-height: calc(297mm - 20px); /* A4 height minus padding */
                max-width: 210mm; /* A4 width */
                margin: 10px auto; /* Center the marksheet */
                page-break-before: always !important; /* Force each marksheet to start on new page */
                break-before: page; /* CSS3 page break alternative */
            }
            .marksheet::before {
                opacity: 0.03; /* Reduced from 0.05 */
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .school-header {
                border-bottom: 2px solid #000 !important;
                background: white;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .school-logo {
                border: 1px solid #000; /* Reduced from 2px */
                box-shadow: none;
                width: 50px; /* Reduced for print */
                height: 50px; /* Reduced for print */
                display: block !important;
            }
            
            .school-logo img {
                max-height: 50px !important;
                width: auto !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .marks-table {
                width: 100%;
                table-layout: fixed; /* Ensure table fits within A4 width */
                font-size: 9px; /* Slightly smaller for A4 */
            }
            .marks-table th {
                background: #f8f9fa;
                color: #000;
            }
            
            /* Ensure borders appear in print */
            .marks-table,
            .marks-table th,
            .marks-table td,
            .student-info,
            .result-summary,
            .signature-section {
                border: 1px solid #000 !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .marks-table th {
                background: #e9ecef !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .student-info,
            .result-summary {
                background: #f8f9fa !important;
                border: 1px solid #e9ecef !important;
                border-radius: 6px !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .signature-section {
                display: grid;
                grid-template-columns: 1fr 1fr 1fr;
                gap: 15px;
                margin-top: 20px;
                text-align: center;
            }
            
            .signature-box {
                border-top: 1px solid #3498db !important;
                padding-top: 8px;
                margin-top: 20px;
                font-weight: 600;
                color: #2c3e50;
                font-size: 12px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            /* Header styles */
            .school-header h3 {
                color: #2c3e50 !important;
                font-weight: 700;
                margin: 8px 0 3px 0;
                text-shadow: 1px 1px 1px rgba(0,0,0,0.1);
                font-size: 18px; /* Slightly smaller for A4 */
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .school-header h4 {
                color: #e74c3c !important;
                font-weight: 600;
                margin: 10px 0 0 0;
                text-decoration: underline;
                text-underline-offset: 5px;
                font-size: 14px; /* Slightly smaller for A4 */
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            /* Hide all watermark images when printing */
            .marksheet img[alt=''] {
                display: none !important;
            }
            /* Student photo styles */
            .student-photo {
                display: block;
            }
            
            .student-photo-print {
                max-width: 100px;
                max-height: 120px;
                border: 2px solid #3498db;
                border-radius: 5px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            
            /* Student photo print styles */
            .student-photo {
                display: block !important;
            }
            
            .student-photo-print {
                max-width: 80px !important;
                max-height: 100px !important;
                border: 1px solid #000 !important;
                border-radius: 3px !important;
                box-shadow: none !important;
            }
            
            /* Fourth Subject Container Print Styles */
            .fourth-subject-container {
                margin-top: 20px;
                border: 2px solid #000 !important;
                border-radius: 8px;
                padding: 15px;
                background: #e3f2fd !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
                page-break-inside: avoid;
                width: calc(100% - 30px); /* Account for padding */
            }
            
            .fourth-subject-container h4 {
                text-align: center;
                color: #000 !important;
                margin-bottom: 15px;
                font-weight: bold;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .fourth-subject-marks-table {
                width: 100%;
                border-collapse: collapse;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .fourth-subject-marks-table th {
                background: #3498db !important;
                color: #fff !important;
                border: 1px solid #000 !important;
                padding: 6px;
                text-align: center;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .fourth-subject-marks-table td {
                border: 1px solid #000 !important;
                padding: 6px;
                text-align: center;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .fourth-subject-marks-table tbody tr {
                background-color: white !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            /* Page break separator for separate printing */
            .page-break-separator {
                page-break-after: always;
            }

            /* Additional rules for bulk printing page breaks */
            .page-break-container + .page-break-container {
                page-break-before: always;
                break-before: page; /* Modern CSS alternative */
                margin-top: 150px; /* Add more top margin to force separation */
            }

            /* Ensure marksheets have enough content to force page breaks */
            .page-break-container .marksheet {
                orphans: 3;
                widows: 3;
                page-break-inside: avoid;
            }

            /* Style the page break div */
            .page-break-container div[style*="page-break-after: always"] {
                display: block !important;
                height: 50px !important;
                margin: 100px 0 !important;
                padding: 0 !important;
                border: 1px solid transparent !important;
                clear: both;
                background: transparent;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <?php if ($student_id && $session && $exam_type && $student): ?>
        <!-- Individual Student Marksheet Mode -->
        <?php if ($show_custom_marks_notification): ?>
        <div class="alert alert-success text-center mb-3 no-print">
            <i class="fas fa-check-circle"></i> কাস্টম মান প্রয়োগ করা হয়েছে: বাংলা (CQ ১ম: <?php echo $custom_bangla_cq1 !== null ? $custom_bangla_cq1 : 'অপরিবর্তিত'; ?>, CQ ২য়: <?php echo $custom_bangla_cq2 !== null ? $custom_bangla_cq2 : 'অপরিবর্তিত'; ?>, MCQ ১ম: <?php echo $custom_bangla_mcq1 !== null ? $custom_bangla_mcq1 : 'অপরিবর্তিত'; ?>, MCQ ২য়: <?php echo $custom_bangla_mcq2 !== null ? $custom_bangla_mcq2 : 'অপরিবর্তিত'; ?>, মোট: <?php echo $custom_bangla_total !== null ? $custom_bangla_total : 'অপরিবর্তিত'; ?>) <?php echo $show_bangla_avg ? '(গড় প্রদর্শন)' : '(মোট প্রদর্শন)'; ?>, ইংরেজি (CQ ১ম: <?php echo $custom_english_cq1 !== null ? $custom_english_cq1 : 'অপরিবর্তিত'; ?>, CQ ২য়: <?php echo $custom_english_cq2 !== null ? $custom_english_cq2 : 'অপরিবর্তিত'; ?>, MCQ ১ম: <?php echo $custom_english_mcq1 !== null ? $custom_english_mcq1 : 'অপরিবর্তিত'; ?>, MCQ ২য়: <?php echo $custom_english_mcq2 !== null ? $custom_english_mcq2 : 'অপরিবর্তিত'; ?>, মোট: <?php echo $custom_english_total !== null ? $custom_english_total : 'অপরিবর্তিত'; ?>) <?php echo $show_english_avg ? '(গড় প্রদর্শন)' : '(মোট প্রদর্শন)'; ?>
        </div>
        <?php endif; ?>
        <div class="text-center mb-3 no-print">
            <button onclick="window.print()" class="btn btn-success"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
            <a href="bulk_print_marksheets.php" class="btn btn-primary no-print"><i class="fas fa-search"></i> নতুন অনুসন্ধান</a>
            <a href="../index.php" class="btn btn-secondary no-print"><i class="fas fa-home"></i> হোম</a>
        </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>
        
        <div class="marksheet">
            <div class="school-header">
                
                
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <!-- School Logo - Left -->
                    <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>
                    
                    <!-- Institution Name and Address - Center -->
                    <div style="text-align: center; flex-grow: 1; padding: 0 20px;">
                        <h3 style="font-size: 24px; margin: 0 0 5px 0;"><?php echo htmlspecialchars($site_name); ?></h3>
                        <p style="color: #7f8c8d; margin: 0 0 5px 0; font-size: 14px;"><?php echo htmlspecialchars($site_address); ?></p>
                        <h4 style="font-size: 18px; margin: 0;">একাডেমিক মার্কশীট</h4>
                    </div>
                    
                    <!-- Student Photo - Right -->
                    <div style="text-align: right;" class="student-photo">
                        <?php if (!empty($student['photo']) && file_exists(__DIR__ . '/' . $student['photo'])): ?>
                            <img src="<?php echo htmlspecialchars($student['photo']); ?>" alt="Student Photo" class="student-photo-print" style="max-width: 100px; max-height: 120px; border: 2px solid #3498db; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                        <?php else: ?>
                            <div style="width: 100px; height: 120px; border: 2px dashed #3498db; border-radius: 5px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa;">
                                <i class="fas fa-user-graduate" style="font-size: 32px; color: #3498db;"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Modal for customizing Bangla and English marks -->
                <div class="modal fade" id="customMarksModal" tabindex="-1" aria-labelledby="customMarksModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="customMarksModalLabel">বাংলা ও ইংরেজি বিষয়ের নম্বর কাস্টমাইজ করুন</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6>বাংলা বিষয় (একত্রে)</h6>
                                        <div class="mb-3">
                                            <label class="form-label">CQ ১ম পত্রের নম্বর</label>
                                            <input type="number" class="form-control" id="customBanglaCq1" step="0.01" min="0">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">CQ ২য় পত্রের নম্বর</label>
                                            <input type="number" class="form-control" id="customBanglaCq2" step="0.01" min="0">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">MCQ ১ম পত্রের নম্বর</label>
                                            <input type="number" class="form-control" id="customBanglaMcq1" step="0.01" min="0">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">MCQ ২য় পত্রের নম্বর</label>
                                            <input type="number" class="form-control" id="customBanglaMcq2" step="0.01" min="0">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">মোট নম্বর</label>
                                            <input type="number" class="form-control" id="customBanglaTotal" step="0.01" min="0">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>ইংরেজি বিষয় (একত্রে)</h6>
                                        <div class="mb-3">
                                            <label class="form-label">CQ ১ম পত্রের নম্বর</label>
                                            <input type="number" class="form-control" id="customEnglishCq1" step="0.01" min="0">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">CQ ২য় পত্রের নম্বর</label>
                                            <input type="number" class="form-control" id="customEnglishCq2" step="0.01" min="0">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">MCQ ১ম পত্রের নম্বর</label>
                                            <input type="number" class="form-control" id="customEnglishMcq1" step="0.01" min="0">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">MCQ ২য় পত্রের নম্বর</label>
                                            <input type="number" class="form-control" id="customEnglishMcq2" step="0.01" min="0">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">মোট নম্বর</label>
                                            <input type="number" class="form-control" id="customEnglishTotal" step="0.01" min="0">
                                        </div>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label">বাংলা বিষয়ে প্রদর্শন পদ্ধতি:</label>
                                        <select class="form-select" id="showBanglaAvg">
                                            <option value="true">গড় দেখাবেন</option>
                                            <option value="false">মোট দেখাবেন</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">ইংরেজি বিষয়ে প্রদর্শন পদ্ধতি:</label>
                                        <select class="form-select" id="showEnglishAvg">
                                            <option value="true">গড় দেখাবেন</option>
                                            <option value="false">মোট দেখাবেন</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="alert alert-info">
                                    <small>নোট: কাস্টম মান দেওয়ার পর মার্কশীট রিফ্রেশ করুন বা প্রিন্ট করুন তো পরিবর্তনগুলো প্রয়োগ হবে। দুটি পত্রের নম্বর দিলে গড় হিসাব করা হবে।</small>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                                <button type="button" class="btn btn-primary" onclick="applyCustomMarks()">প্রয়োগ করুন</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <hr style="border-top: 2px solid #2c3e50; margin: 15px 0;">
                
                <div style="display: flex; justify-content: space-between;">
                    <div>
                        <div class="info-row">
                            <div class="info-label">শিক্ষার্থী আইডি</div>
                            <div class="info-value"><?php echo htmlspecialchars($student['student_id']); ?></div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">নাম</div>
                            <div class="info-value"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">পিতার নাম</div>
                            <div class="info-value"><?php echo htmlspecialchars($student['father_name'] ?? ''); ?></div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">মাতার নাম</div>
                            <div class="info-value"><?php echo htmlspecialchars($student['mother_name'] ?? ''); ?></div>
                        </div>
                    </div>
                    <div>
                        <div class="info-row">
                            <div class="info-label">রোল নম্বর</div>
                            <div class="info-value"><?php echo htmlspecialchars($student['roll_number']); ?></div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">শ্রেণী</div>
                            <div class="info-value"><?php echo htmlspecialchars($student['class_name'] . ' ' . $student['section']); ?><?php if (!empty($student['group_name'])): ?> <strong>(<?php echo htmlspecialchars($student['group_name']); ?>)</strong><?php endif; ?></div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">সেশন</div>
                            <div class="info-value"><?php echo htmlspecialchars($session); ?></div>
                        </div>
                        <div class="info-row">
                            <div class="info-label">পরীক্ষার ধরন</div>
                            <div class="info-value"><?php echo htmlspecialchars(ucfirst($exam_type)); ?></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <table class="marks-table">
                <thead>
                    <tr>
                        <th rowspan="2">বিষয়</th>
                        <th colspan="5">প্রাপ্ত নম্বর</th>
                        <th rowspan="2">প্রাপ্ত<br>নম্বর</th>
                        <th rowspan="2">পাস<br>নম্বর</th>
                        <th rowspan="2">গ্রেড</th>
                        <th rowspan="2">জিপি</th>
                    </tr>
                    <tr>
                        <th>সিকিউ</th>
                        <th>এমসিকিউ</th>
                        <th>প্র্যাকটিক্যাল</th>
                        <th>অ্যাসাইনমেন্ট</th>
                        <th>অ্যাটেনডেন্স</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $total_full_marks = 0;
                    $total_obtained_marks = 0;
                    $total_gp = 0;
                    $subject_count = 0;
                    $passed_subjects = 0;
                    $fourth_subject_data = null;
                    $fourth_subject_display_name = '';
                    
                    foreach ($results as $result):
                        // For combined subjects, calculate full_marks based on toggle
                        $subject_full_marks = $result['full_marks'] ?? 100;
                        if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                            isset($result['full_marks']) && $result['full_marks'] > 0) {
                            // Check which toggle to use based on subject
                            $use_avg = false;
                            if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                                $use_avg = $show_bangla_avg;
                            } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                                $use_avg = $show_english_avg;
                            }
                            
                            // If showing total, multiply by number of papers
                            if (!$use_avg) {
                                $paper_count = 2; // Default to 2 papers for combined subjects
                                if (isset($result['cq_marks_array'])) {
                                    $paper_count = count($result['cq_marks_array']);
                                }
                                $subject_full_marks = $result['full_marks'] * $paper_count;
                            }
                        }
                        
                        // For combined subjects, calculate obtained marks based on toggle
                        $subject_obtained_marks = $result['marks_obtained'] ?? 0;
                        if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                            isset($result['cq_marks_array']) && isset($result['mcq_marks_array'])) {
                            // Check which toggle to use based on subject
                            $use_avg = false;
                            if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                                $use_avg = $show_bangla_avg;
                            } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                                $use_avg = $show_english_avg;
                            }
                            
                            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']);
                                $subject_obtained_marks = $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']);
                                $subject_obtained_marks = $total_cq + $total_mcq;
                            }
                        }
                        
                        $grade_point = $result['grade_point'] ?? 0.00;
                        
                        // Skip subjects with 0 full marks
                        if ($subject_full_marks <= 0) continue;
                        
                        // Check if this is the fourth subject
                        if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                            $fourth_subject_data = $result;
                            // Store subject info for display later
                            $fourth_subject_display_name = $result['subject_name'] ?? '';
                            if ($result['subject_id'] == 'combined_bangla') {
                                $fourth_subject_display_name = 'বাংলা (১ম ও ২য় পত্র)';
                            } elseif ($result['subject_id'] == 'combined_english') {
                                $fourth_subject_display_name = 'ইংরেজি (১ম ও ২য় পত্র)';
                            }
                            
                            // Include 4th subject in total calculation
                            $total_full_marks += $subject_full_marks;
                            $total_obtained_marks += $subject_obtained_marks;
                            continue; // Skip displaying in main table - show separately
                        }
                        
                        $total_full_marks += $subject_full_marks;
                        $total_obtained_marks += $subject_obtained_marks;
                        $total_gp += $grade_point;
                        $subject_count++;
                        
                        if ($result['grade'] !== 'F') {
                            $passed_subjects++;
                        }
                        
                        // For combined subjects, show appropriate labels
                        $subject_display_name = $result['subject_name'] ?? '';
                        if ($result['subject_id'] == 'combined_bangla') {
                            $subject_display_name = 'বাংলা (১ম ও ২য় পত্র)';
                        } elseif ($result['subject_id'] == 'combined_english') {
                            $subject_display_name = 'ইংরেজি (১ম ও ২য় পত্র)';
                        }
                        
                        // Prepare CQ and MCQ display values based on toggle
                        $cq_display = $result['cq_marks'] ?? 0;
                        $mcq_display = $result['mcq_marks'] ?? 0;
                        
                        if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                            isset($result['cq_marks_array']) && isset($result['mcq_marks_array'])) {
                            // Check which toggle to use based on subject
                            $use_avg = false;
                            if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                                $use_avg = $show_bangla_avg;
                            } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                                $use_avg = $show_english_avg;
                            }
                            
                            // For CQ
                            $individual_cq = [];
                            foreach ($result['cq_marks_array'] as $mark) {
                                $individual_cq[] = floor($mark);
                            }
                            if ($use_avg) {
                                $avg_cq = array_sum($result['cq_marks_array']) / count($result['cq_marks_array']);
                                $cq_display = implode(', ', $individual_cq) . ' (গড়: ' . floor($avg_cq) . ')';
                            } else {
                                $total_cq = array_sum($result['cq_marks_array']);
                                $cq_display = implode(', ', $individual_cq) . ' (মোট: ' . floor($total_cq) . ')';
                            }
                            
                            // For MCQ
                            $individual_mcq = [];
                            foreach ($result['mcq_marks_array'] as $mark) {
                                $individual_mcq[] = floor($mark);
                            }
                            if ($use_avg) {
                                $avg_mcq = array_sum($result['mcq_marks_array']) / count($result['mcq_marks_array']);
                                $mcq_display = implode(', ', $individual_mcq) . ' (গড়: ' . floor($avg_mcq) . ')';
                            } else {
                                $total_mcq = array_sum($result['mcq_marks_array']);
                                $mcq_display = implode(', ', $individual_mcq) . ' (মোট: ' . floor($total_mcq) . ')';
                            }
                        }
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars($subject_display_name); ?><?php if (!empty($result['subject_code'])): ?> <small>(<?php echo htmlspecialchars($result['subject_code']); ?>)</small><?php endif; ?></td>
                        <td><?php echo is_numeric($cq_display) ? floor($cq_display) : htmlspecialchars($cq_display); ?></td>
                        <td><?php echo is_numeric($mcq_display) ? floor($mcq_display) : htmlspecialchars($mcq_display); ?></td>
                        <td><?php echo floor($result['practical_marks'] ?? 0); ?></td>
                        <td><?php echo $result['assignment_marks'] ?? 0; ?></td>
                        <td><?php echo $result['attendance_marks'] ?? 0; ?></td>
                        <td><?php echo floor($subject_obtained_marks); ?></td>
                        <td><?php echo $result['pass_marks'] ?? 33; ?></td>
                        <td><?php echo $result['grade'] ?? 'F'; ?></td>
                        <td><?php echo number_format($grade_point, 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    

                    <tr>
                        <th colspan="6">মোট</th>
                        <th><?php echo $total_obtained_marks; ?></th>
                        <th><?php echo $total_full_marks; ?></th>
                        <th colspan="2"></th>
                    </tr>

                    <tr>
                        <th colspan="8">পাস করা বিষয়: <?php echo $passed_subjects; ?>/<?php echo $subject_count; ?> <?php if ($merit_position !== null && $merit_position > 0 && $show_merit_position): ?>(মেরিট)<?php endif; ?></th>
                        <th colspan="2">
                            <?php 
                            $gpa = calculateGPA($results);
                            echo 'GPA: ' . number_format($gpa, 2);
                            ?>
                        </th>
                    </tr>
                </tfoot>
            </table>
            
            <!-- Display Fourth Subject below main table in individual student view -->
            <?php if ($fourth_subject_data): ?>
            <div class="fourth-subject-container" style="margin-top: 20px; border: 2px solid #000; border-radius: 8px; padding: 15px; background: #e3f2fd;">
                <table class="fourth-subject-marks-table" style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">বিষয়</th>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">সিকিউ</th>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">এমসিকিউ</th>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">প্র্যাকটিক্যাল</th>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">অ্যাসাইনমেন্ট</th>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">অ্যাটেনডেন্স</th>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">প্রাপ্ত<br>নম্বর</th>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">পাস<br>নম্বর</th>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">গ্রেড</th>
                            <th style="background: #3498db; color: #fff; border: 1px solid #000; padding: 6px; text-align: center;">জিপি</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td style="border: 1px solid #000; padding: 6px; text-align: left; padding-left: 15px; font-weight: 500;">
                                <?php echo htmlspecialchars($fourth_subject_display_name); ?>
                                <?php if (!empty($fourth_subject_data['subject_code'])): ?>
                                    <small>(<?php echo htmlspecialchars($fourth_subject_data['subject_code']); ?>)</small>
                                <?php endif; ?>
                            </td>
                            <td style="border: 1px solid #000; padding: 6px; text-align: center;"><?php echo floor($fourth_subject_data['cq_marks'] ?? 0); ?></td>
                            <td style="border: 1px solid #000; padding: 6px; text-align: center;"><?php echo floor($fourth_subject_data['mcq_marks'] ?? 0); ?></td>
                            <td style="border: 1px solid #000; padding: 6px; text-align: center;"><?php echo floor($fourth_subject_data['practical_marks'] ?? 0); ?></td>
                            <td style="border: 1px solid #000; padding: 6px; text-align: center;"><?php echo $fourth_subject_data['assignment_marks'] ?? 0; ?></td>
                            <td style="border: 1px solid #000; padding: 6px; text-align: center;"><?php echo $fourth_subject_data['attendance_marks'] ?? 0; ?></td>
                            <td style="border: 1px solid #000; padding: 6px; text-align: center; font-weight: 600;"><?php echo floor($fourth_subject_data['marks_obtained'] ?? 0); ?></td>
                            <td style="border: 1px solid #000; padding: 6px; text-align: center;"><?php echo $fourth_subject_data['pass_marks'] ?? 33; ?></td>
                            <td style="border: 1px solid #000; padding: 6px; text-align: center; font-weight: 700; 
                                <?php 
                                switch ($fourth_subject_data['grade'] ?? 'F') {
                                    case 'A+': echo 'color: #27ae60;'; break;
                                    case 'A': echo 'color: #2ecc71;'; break;
                                    case 'A-': echo 'color: #3498db;'; break;
                                    case 'B': echo 'color: #9b59b6;'; break;
                                    case 'C': echo 'color: #f39c12;'; break;
                                    case 'D': echo 'color: #e67e22;'; break;
                                    case 'F': echo 'color: #e74c3c;'; break;
                                    default: echo 'color: #34495e;';
                                }
                                ?>
                                "><?php echo $fourth_subject_data['grade'] ?? 'F'; ?></td>
                            <td style="border: 1px solid #000; padding: 6px; text-align: center;"><?php echo number_format($fourth_subject_data['grade_point'] ?? 0.00, 2); ?></td>
                        </tr>
                        <tr style="background-color: #f0f8ff;">
                            <td colspan="10" style="border: 1px solid #000; text-align: left; padding: 8px; font-style: italic; color: #2980b9;">
                                <?php 
                                // Calculate main subjects total points
                                $main_subjects_total_points = 0;
                                foreach ($results as $result) {
                                    // Only include non-4th subjects
                                    if (empty($result['is_fourth_subject']) || !($result['is_fourth_subject'] ?? false)) {
                                        if (($result['grade'] ?? '') != 'F') {
                                            $main_subjects_total_points += $result['grade_point'] ?? 0.00;
                                        }
                                    }
                                }
                                
                                $fourth_subject_grade_point = $fourth_subject_data['grade_point'] ?? 0.00;
                                $bonus_points = ($fourth_subject_grade_point > 2.00) ? ($fourth_subject_grade_point - 2.00) : 0;
                                $total_points = $main_subjects_total_points + $bonus_points;
                                ?>
                                <strong>মূল বিষয়গুলোর মোট পয়েন্ট:</strong> <?php echo number_format($main_subjects_total_points, 2); ?> 
                                <strong style="margin-left: 20px;">+ ৪র্থ বিষয় থেকে অতিরিক্ত পয়েন্ট:</strong> <?php echo number_format($bonus_points, 2); ?> 
                                <strong style="margin-left: 20px;">= মোট:</strong> <?php echo number_format($total_points, 2); ?>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
            
            <!-- Summary Information -->
            <div class="result-summary">
                <div>
                    <div class="info-row">
                        <div class="info-label">মোট নম্বর</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo $total_obtained_marks; ?>/<?php echo $total_full_marks; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শতাংশ</div>
                        <div class="info-value" style="font-weight: 700; color: #3498db;"><?php echo $percentage; ?>%</div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">গ্রেড</div>
                        <div class="info-value" style="font-weight: 700; font-size: 18px; 
                            <?php 
                            // Calculate grade based on GPA instead of percentage
                            $gpa_based_grade = calculateGradeFromGPA($gpa);
                            switch ($gpa_based_grade) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo $gpa_based_grade; ?>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">জিপিএ</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo number_format($gpa, 2); ?></div>
                    </div>
                    <?php if ($merit_position): ?>
                    <div class="info-row">
                        <div class="info-label">মেরিট</div>
                        <div class="info-value" style="font-weight: 700; 
                            <?php 
                            if ($merit_position == 1) {
                                echo 'color: #f1c40f; font-size: 20px;';
                            } elseif ($merit_position <= 3) {
                                echo 'color: #9b59b6; font-size: 18px;';
                            } else {
                                echo 'color: #3498db;';
                            }
                            ?>">
                            <!-- <?php echo $merit_position; ?> -->
                            <?php if ($merit_position == 1): ?>
                                <i class="fas fa-trophy" style="color: #f1c40f;"></i>
                            <?php elseif ($merit_position == 2): ?>
                                <i class="fas fa-medal" style="color: #aaa;"></i>
                            <?php elseif ($merit_position == 3): ?>
                                <i class="fas fa-medal" style="color: #cd7f32;"></i>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div style="margin-top: 30px; display: flex; justify-content: space-between;">
                <div>
                    <p>___________________________</p>
                    <p style="margin-bottom: 0;"><strong>প্রধান শিক্ষকের স্বাক্ষর</strong></p>
                </div>
                <div style="text-align: center;">
                    <p>___________________________</p>
                    <p style="margin-bottom: 0;"><strong>পরীক্ষা কমিটির স্বাক্ষর</strong></p>
                </div>
                <div style="text-align: center;">
                    <p>___________________________</p>
                    <p style="margin-bottom: 0;"><strong>শ্রেণি শিক্ষকের স্বাক্ষর</strong></p>
                </div>
            </div>
        </div>
        
        <div style="page-break-after: always;"></div>
        
        <?php elseif (($bulk_print_all || !empty($selected_students)) && !empty($all_students_data)): ?>
        <!-- Bulk Print All Students Mode -->
        <?php if ($show_custom_marks_notification): ?>
        <div class="alert alert-success text-center mb-3 no-print">
            <i class="fas fa-check-circle"></i> কাস্টম মান প্রয়োগ করা হয়েছে: বাংলা (CQ ১ম: <?php echo $custom_bangla_cq1 !== null ? $custom_bangla_cq1 : 'অপরিবর্তিত'; ?>, CQ ২য়: <?php echo $custom_bangla_cq2 !== null ? $custom_bangla_cq2 : 'অপরিবর্তিত'; ?>, MCQ ১ম: <?php echo $custom_bangla_mcq1 !== null ? $custom_bangla_mcq1 : 'অপরিবর্তিত'; ?>, MCQ ২য়: <?php echo $custom_bangla_mcq2 !== null ? $custom_bangla_mcq2 : 'অপরিবর্তিত'; ?>, মোট: <?php echo $custom_bangla_total !== null ? $custom_bangla_total : 'অপরিবর্তিত'; ?>) <?php echo $show_bangla_avg ? '(গড় প্রদর্শন)' : '(মোট প্রদর্শন)'; ?>, ইংরেজি (CQ ১ম: <?php echo $custom_english_cq1 !== null ? $custom_english_cq1 : 'অপরিবর্তিত'; ?>, CQ ২য়: <?php echo $custom_english_cq2 !== null ? $custom_english_cq2 : 'অপরিবর্তিত'; ?>, MCQ ১ম: <?php echo $custom_english_mcq1 !== null ? $custom_english_mcq1 : 'অপরিবর্তিত'; ?>, MCQ ২য়: <?php echo $custom_english_mcq2 !== null ? $custom_english_mcq2 : 'অপরিবর্তিত'; ?>, মোট: <?php echo $custom_english_total !== null ? $custom_english_total : 'অপরিবর্তিত'; ?>) <?php echo $show_english_avg ? '(গড় প্রদর্শন)' : '(মোট প্রদর্শন)'; ?>
        </div>
        <?php endif; ?>
        <div class="text-center mb-3 no-print">
            <button onclick="window.print()" class="btn btn-success"><i class="fas fa-print"></i> <?php echo !empty($selected_students) ? 'নির্বাচিতগুলো প্রিন্ট করুন' : 'সবগুলো প্রিন্ট করুন'; ?></button>
            <a href="bulk_print_marksheets.php" class="btn btn-primary no-print"><i class="fas fa-search"></i> নতুন অনুসন্ধান</a>
            <a href="../index.php" class="btn btn-secondary no-print"><i class="fas fa-home"></i> হোম</a>
        </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="banglaToggleBulk" style="margin: 0; font-weight: 500;">বাংলা:</label>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="banglaToggleBulk" <?php echo $show_bangla_avg ? '' : 'checked'; ?> style="cursor: pointer; width: 50px; height: 25px;">
                    <label class="form-check-label" for="banglaToggleBulk" style="cursor: pointer;">
                        <span id="banglaToggleTextBulk"><?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="englishToggleBulk" style="margin: 0; font-weight: 500;">ইংরেজি:</label>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="englishToggleBulk" <?php echo $show_english_avg ? '' : 'checked'; ?> style="cursor: pointer; width: 50px; height: 25px;">
                    <label class="form-check-label" for="englishToggleBulk" style="cursor: pointer;">
                        <span id="englishToggleTextBulk"><?php echo $show_english_avg ? 'গড়' : 'মোট'; ?></span>
                    </label>
                </div>
            </div>
            <!-- Dropdown for Merit Position Sorting -->
            <div class="d-flex align-items-center gap-2" style="background: #f8f9fa; padding: 10px 15px; border-radius: 5px; border: 1px solid #dee2e6;">
                <label for="meritSortSelect" style="margin: 0; font-weight: 500;">মেরিট সর্ট:</label>
                <select id="meritSortSelect" class="form-select" style="width: auto; cursor: pointer;">
                    <option value="total_marks" selected>টোটাল মার্ক্স</option>
                    <option value="gpa">জিপিএ</option>
                    <option value="total_points">মুল বিষয় পয়েন্ট + ৪র্থ বিষয় পয়েন্ট</option>
                </select>
            </div>
            <!-- Toggle for Merit Position Visibility -->
            <div class="d-flex align-items-center gap-2" style="background: #f8f9fa; padding: 10px 15px; border-radius: 5px; border: 1px solid #dee2e6;">
                <label for="showMeritToggle" style="margin: 0; font-weight: 500;">মেরিট দেখান:</label>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="showMeritToggle" <?php echo $show_merit_position ? 'checked' : ''; ?> style="cursor: pointer; width: 50px; height: 25px;">
                    <label class="form-check-label" for="showMeritToggle" style="cursor: pointer;">
                        <span id="showMeritToggleText"><?php echo $show_merit_position ? 'হ্যাঁ' : 'না'; ?></span>
                    </label>
                </div>
            </div>
        </div>
        
        <?php foreach ($all_students_data as $index => $student_data):
            $student = $student_data['student'];
            $results = $student_data['results'];

            // Add student counter for debugging
            $student_number = $index + 1;

            // Recalculate total_marks and total_obtained based on toggle state for display
            $total_marks_recalc = 0;
            $total_obtained_recalc = 0;
            foreach ($results as $result) {
                // For combined Bengali and English subjects, calculate full_marks based on toggle
                $marks_for_total_calculation = $result['full_marks'];
                if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                    isset($result['full_marks']) && $result['full_marks'] > 0) {
                    // Check which toggle to use based on subject
                    $use_avg = false;
                    if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                        $use_avg = $show_bangla_avg;
                    } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                        $use_avg = $show_english_avg;
                    }
                    
                    // If showing total, multiply by number of papers
                    if (!$use_avg) {
                        $paper_count = 2; // Default to 2 papers for combined subjects
                        if (isset($result['cq_marks_array'])) {
                            $paper_count = count($result['cq_marks_array']);
                        }
                        $marks_for_total_calculation = $result['full_marks'] * $paper_count;
                    }
                }
                $total_marks_recalc += $marks_for_total_calculation;
                
                // For combined Bengali and English subjects, calculate obtained marks based on toggle
                $marks_for_total = $result['marks_obtained'];
                if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                    isset($result['cq_marks_array']) && isset($result['mcq_marks_array'])) {
                    // Check which toggle to use based on subject
                    $use_avg = false;
                    if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                        $use_avg = $show_bangla_avg;
                    } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                        $use_avg = $show_english_avg;
                    }
                    
                    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;
                    }
                }
                $total_obtained_recalc += $marks_for_total;
            }
            $total_marks = $total_marks_recalc;
            $total_obtained = $total_obtained_recalc;
            
            // Recalculate percentage based on new total_obtained and total_marks
            $percentage = $total_marks > 0 ? round(($total_obtained / $total_marks) * 100, 2) : 0;
            
            $gpa = $student_data['gpa'];
            $passed_subjects = $student_data['passed_subjects'];
            $total_subjects = $student_data['total_subjects'];
            $merit_position = $student_data['merit_position'] ?? null;
            
            // Check if this is the last student to avoid adding page break after the last one
            $is_last_student = ($index === count($all_students_data) - 1);

            // For print all together, never add page breaks
            $add_page_break = !$is_last_student;
        ?>
        <div class="page-break-container" style="page-break-inside: avoid; <?php if ($add_page_break) echo 'page-break-after: always;'; ?> min-height: 900px; margin-bottom: 200px;">

        <!-- Force page break div with large margin -->
        <?php if ($add_page_break): ?>
        <div style="page-break-after: always; clear: both; height: 50px; margin: 100px 0; padding: 0; border: 1px solid transparent;"></div>
        <?php endif; ?>
        <div class="marksheet">
            <div class="school-header">
                
                
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <!-- School Logo - Left -->
                    <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>
                    
                    <!-- Institution Name and Address - Center -->
                    <div style="text-align: center; flex-grow: 1; padding: 0 20px;">
                        <h3 style="font-size: 24px; margin: 0 0 5px 0;"><?php echo htmlspecialchars($site_name); ?></h3>
                        <p style="color: #7f8c8d; margin: 0 0 5px 0; font-size: 14px;"><?php echo htmlspecialchars($site_address); ?></p>
                        <h4 style="font-size: 18px; margin: 0;">একাডেমিক মার্কশীট</h4>
                    </div>
                    
                    <!-- Student Photo - Right -->
                    <div style="text-align: right;" class="student-photo">
                        <?php if (!empty($student['photo']) && file_exists(__DIR__ . '/' . $student['photo'])): ?>
                            <img src="<?php echo htmlspecialchars($student['photo']); ?>" alt="Student Photo" class="student-photo-print" style="max-width: 100px; max-height: 120px; border: 2px solid #3498db; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                        <?php else: ?>
                            <div style="width: 100px; height: 120px; border: 2px dashed #3498db; border-radius: 5px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa;">
                                <i class="fas fa-user" style="font-size: 36px; color: #3498db;"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Watermark Logos -->
            <?php if ($logo_image): ?>
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(45deg); opacity: 0.05; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 3); ?>px; height: <?php echo ($logo_size * 3); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; top: 20%; left: 20%; transform: rotate(30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; top: 20%; right: 20%; transform: rotate(-30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; bottom: 20%; left: 20%; transform: rotate(-30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; bottom: 20%; right: 20%; transform: rotate(30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
            <?php endif; ?>
            
            <div class="student-info">
                <div>
                    <div class="info-row">
                        <div class="info-label">শিক্ষার্থী আইডি</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['student_id']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পিতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['father_name'] ?? ''); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">মাতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['mother_name'] ?? ''); ?></div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">রোল নম্বর</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['roll_number']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শ্রেণী</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['class_name'] . ' ' . $student['section']); ?><?php if (!empty($student['group_name'])): ?> <strong>(<?php echo htmlspecialchars($student['group_name']); ?>)</strong><?php endif; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">সেশন</div>
                        <div class="info-value"><?php echo htmlspecialchars($session); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পরীক্ষার ধরন</div>
                        <div class="info-value"><?php echo htmlspecialchars(ucfirst($exam_type)); ?></div>
                    </div>
                </div>
            </div>
            
            <table class="marks-table">
                <thead>
                    <tr>
                        <th rowspan="2">বিষয়</th>
                        <th colspan="5">প্রাপ্ত নম্বর</th>
                        <th rowspan="2">প্রাপ্ত<br>নম্বর</th>
                        <th rowspan="2">পাস<br>নম্বর</th>
                        <th rowspan="2">গ্রেড</th>
                        <th rowspan="2">জিপি</th>
                    </tr>
                    <tr>
                        <th>সৃজনশীল</th>
                        <th>বহুনির্বাচনি</th>
                        <th>ব্যবহারিক</th>
                        <th>অ্যাসাইনমেন্ট</th>
                        <th>শ্রেণিতে<br>সর্বোচ্চ</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    // Initialize fourth subject data
                    $fourth_subject_info = null;
                    $main_subjects_total_points = 0; // Total points from main subjects (excluding 4th subject)
                    
                    foreach ($results as $result): 
                        // Check if this is the fourth subject
                        if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                            // Store fourth subject data for display at bottom
                            $fourth_subject_grade_point = $result['grade_point'] ?? 0.00;
                            // Calculate bonus points: grade_point - 2.00 (if > 2.00), otherwise 0
                            $bonus_points = ($fourth_subject_grade_point > 2.00) ? ($fourth_subject_grade_point - 2.00) : 0;
                            $fourth_subject_info = [
                                'name' => htmlspecialchars($result['subject_name']),
                                'code' => !empty($result['subject_code']) ? htmlspecialchars($result['subject_code']) : '',
                                'cq_marks' => $result['cq_marks'] ?? 0,
                                'mcq_marks' => $result['mcq_marks'] ?? 0,
                                'practical_marks' => $result['practical_marks'] ?? 0,
                                'assignment_marks' => $result['assignment_marks'] ?? 0,
                                'attendance_marks' => $result['attendance_marks'] ?? 0,
                                'obtained_marks' => $result['marks_obtained'] ?? 0,
                                'pass_marks' => $result['pass_marks'] ?? 33,
                                'grade' => $result['grade'] ?? 'F',
                                'grade_point' => number_format($fourth_subject_grade_point, 2),
                                'bonus_points' => number_format($bonus_points, 2)
                            ];
                            
                            // Include 4th subject in total calculation
                            $total_marks += $result['full_marks'] ?? 100;
                            $total_obtained += $result['marks_obtained'] ?? 0;
                            
                            continue; // Skip displaying in main table
                        }
                        
                        // Add to main subjects total points (only for non-4th subjects)
                        if (!isset($result['is_fourth_subject']) || !$result['is_fourth_subject']) {
                            $main_subjects_total_points += $result['grade_point'] ?? 0.00;
                        }
                    ?>
                    <tr>
                        <td style="text-align: left; padding-left: 15px; font-weight: 500;"><?php echo htmlspecialchars($result['subject_name']); ?></td>
                        <td class="cq-marks-cell" data-subject="<?php echo htmlspecialchars($result['subject_name']); ?>">
                            <?php 
                            // For combined subjects, show individual CQ marks and average/total based on toggle
                            if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && isset($result['cq_marks_array'])) {
                                // Show individual marks
                                $individual_marks = [];
                                foreach ($result['cq_marks_array'] as $mark) {
                                    $individual_marks[] = floor($mark);
                                }
                                
                                // Check which toggle to use based on subject
                                $use_avg = false;
                                if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                                    $use_avg = $show_bangla_avg;
                                } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                                    $use_avg = $show_english_avg;
                                }
                                
                                if ($use_avg) {
                                    // Calculate average and remove fractional part
                                    $avg_cq = array_sum($result['cq_marks_array']) / count($result['cq_marks_array']);
                                    echo implode(', ', $individual_marks) . ' (গড়: ' . floor($avg_cq) . ')';
                                } else {
                                    // Calculate total
                                    $total_cq = array_sum($result['cq_marks_array']);
                                    echo implode(', ', $individual_marks) . ' (মোট: ' . floor($total_cq) . ')';
                                }
                            } else {
                                echo htmlspecialchars(floor($result['cq_marks']) ?: '-');
                            }
                            ?>
                        </td>
                        <td class="mcq-marks-cell" data-subject="<?php echo htmlspecialchars($result['subject_name']); ?>">
                            <?php 
                            // For combined subjects, show individual MCQ marks and average/total based on toggle
                            if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && isset($result['mcq_marks_array'])) {
                                // Show individual marks
                                $individual_marks = [];
                                foreach ($result['mcq_marks_array'] as $mark) {
                                    $individual_marks[] = floor($mark);
                                }
                                
                                // Check which toggle to use based on subject
                                $use_avg = false;
                                if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                                    $use_avg = $show_bangla_avg;
                                } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                                    $use_avg = $show_english_avg;
                                }
                                
                                if ($use_avg) {
                                    // Calculate average and remove fractional part
                                    $avg_mcq = array_sum($result['mcq_marks_array']) / count($result['mcq_marks_array']);
                                    echo implode(', ', $individual_marks) . ' (গড়: ' . floor($avg_mcq) . ')';
                                } else {
                                    // Calculate total
                                    $total_mcq = array_sum($result['mcq_marks_array']);
                                    echo implode(', ', $individual_marks) . ' (মোট: ' . floor($total_mcq) . ')';
                                }
                            } else {
                                echo htmlspecialchars(floor($result['mcq_marks']) ?: '-');
                            }
                            ?>
                        </td>
                        <td><?php echo htmlspecialchars(floor($result['practical_marks']) ?: '-'); ?></td>
                        <td><?php echo htmlspecialchars($result['assignment_marks'] ?: '-'); ?></td>
                        <td class="class-max-marks-cell" data-subject="<?php echo htmlspecialchars($result['subject_name']); ?>">
                            <?php 
                            // For combined subjects, calculate class_max_marks based on toggle
                            if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                                isset($result['class_max_marks']) && $result['class_max_marks'] > 0) {
                                // Check which toggle to use based on subject
                                $use_avg = false;
                                if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                                    $use_avg = $show_bangla_avg;
                                } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                                    $use_avg = $show_english_avg;
                                }
                                
                                // If showing average, divide by number of papers; if showing total, use as is
                                // Note: class_max_marks is already calculated based on average, so if showing total, multiply by count
                                if (!$use_avg) {
                                    // If showing total, multiply by number of papers
                                    $paper_count = 2; // Default to 2 papers for combined subjects
                                    if (isset($result['cq_marks_array'])) {
                                        $paper_count = count($result['cq_marks_array']);
                                    }
                                    echo htmlspecialchars(sprintf('%.0f', $result['class_max_marks'] * $paper_count));
                                } else {
                                    echo htmlspecialchars(sprintf('%.0f', $result['class_max_marks']));
                                }
                            } else {
                                echo ($result['class_max_marks'] !== null && $result['class_max_marks'] >= 0) ? htmlspecialchars(sprintf('%.0f', $result['class_max_marks'])) : '-';
                            }
                            ?>
                        </td>
                        <td class="obtained-marks-cell" data-subject="<?php echo htmlspecialchars($result['subject_name']); ?>" style="font-weight: 600;">
                            <?php 
                            // For combined subjects, calculate obtained marks based on toggle (average or total)
                            if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && 
                                isset($result['cq_marks_array']) && isset($result['mcq_marks_array'])) {
                                // Check which toggle to use based on subject
                                $use_avg = false;
                                if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                                    $use_avg = $show_bangla_avg;
                                } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                                    $use_avg = $show_english_avg;
                                }
                                
                                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']);
                                    $obtained_marks = $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']);
                                    $obtained_marks = $total_cq + $total_mcq;
                                }
                                echo htmlspecialchars(floor($obtained_marks));
                            } else {
                                echo htmlspecialchars(floor($result['marks_obtained']));
                            }
                            ?>
                        </td>
                        <td><?php echo htmlspecialchars($result['pass_marks']); ?></td>
                        <td style="font-weight: 700; 
                            <?php 
                            switch ($result['grade']) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo htmlspecialchars($result['grade']); ?>
                        </td>
                        <td><?php echo number_format($result['grade_point'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    
                    <!-- Display Fourth Subject above GPA row -->
                    <?php if (!empty($fourth_subject_info)): ?>
                    <tr style="background-color: #e3f2fd;">
                        <td style="text-align: left; padding-left: 15px; font-weight: 500;"><?php echo $fourth_subject_info['name']; ?><?php if (!empty($fourth_subject_info['code'])): ?> <small>(<?php echo $fourth_subject_info['code']; ?>)</small><?php endif; ?></td>
                        <td><?php echo floor($fourth_subject_info['cq_marks']); ?></td>
                        <td><?php echo floor($fourth_subject_info['mcq_marks']); ?></td>
                        <td><?php echo floor($fourth_subject_info['practical_marks']); ?></td>
                        <td><?php echo $fourth_subject_info['assignment_marks']; ?></td>
                        <td>-</td>
                        <td style="font-weight: 600;"><?php echo $fourth_subject_info['obtained_marks']; ?></td>
                        <td><?php echo $fourth_subject_info['pass_marks']; ?></td>
                        <td style="font-weight: 700; 
                            <?php 
                            switch ($fourth_subject_info['grade']) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>
                            ">
                            <?php echo $fourth_subject_info['grade']; ?>
                        </td>
                        <td><?php echo $fourth_subject_info['grade_point']; ?></td>
                    </tr>
                    <tr style="background-color: #f0f8ff;">
                        <td colspan="10" style="text-align: left; padding-left: 15px; font-style: italic; color: #2980b9;">
                            <strong>মূল বিষয়গুলোর মোট পয়েন্ট:</strong> <?php echo number_format($main_subjects_total_points, 2); ?> 
                            <strong style="margin-left: 20px;">+ ৪র্থ বিষয় থেকে অতিরিক্ত পয়েন্ট:</strong> <?php echo $fourth_subject_info['bonus_points']; ?> 
                            <strong style="margin-left: 20px;">= মোট:</strong> <?php echo number_format($main_subjects_total_points + floatval($fourth_subject_info['bonus_points']), 2); ?>
                        </td>
                    </tr>
                    <?php endif; ?>
                    
                    <!-- GPA Summary Row -->
                    <tr style="background-color: #e3f2fd; font-weight: bold;">
                        <td colspan="9" style="text-align: right; padding-right: 15px;">জিপিএ (Grade Point Average):</td>
                        <td><?php echo number_format($gpa, 2); ?></td>
                    </tr>
                </tbody>
            </table>
            
            <div class="result-summary">
                <div>
                    <div class="info-row">
                        <div class="info-label">মোট নম্বর</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo $total_obtained; ?>/<?php echo $total_marks; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শতাংশ</div>
                        <div class="info-value" style="font-weight: 700; color: #3498db;"><?php echo $percentage; ?>%</div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">গ্রেড</div>
                        <div class="info-value" style="font-weight: 700; font-size: 18px; 
                            <?php 
                            // Calculate grade based on GPA instead of percentage
                            $gpa_based_grade = calculateGradeFromGPA($gpa);
                            switch ($gpa_based_grade) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo $gpa_based_grade; ?>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">জিপিএ</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo number_format($gpa, 2); ?></div>
                    </div>
                    <?php if ($merit_position && $show_merit_position): ?>
                    <div class="info-row">
                        <div class="info-label">মেরিট</div>
                        <div class="info-value" style="font-weight: 700; 
                            <?php 
                            if ($merit_position == 1) {
                                echo 'color: #f1c40f; font-size: 20px;';
                            } elseif ($merit_position <= 3) {
                                echo 'color: #9b59b6; font-size: 18px;';
                            } else {
                                echo 'color: #3498db;';
                            }
                            ?>">
                            <!-- <?php echo $merit_position; ?> -->
                            <?php if ($merit_position == 1): ?>
                                <i class="fas fa-trophy" style="color: #f1c40f;"></i>
                            <?php elseif ($merit_position == 2): ?>
                                <i class="fas fa-medal" style="color: #aaa;"></i>
                            <?php elseif ($merit_position == 3): ?>
                                <i class="fas fa-medal" style="color: #cd7f32;"></i>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="signature-section">
                <div>
                    <div class="signature-box" style="font-weight: 600; color: #2c3e50;">প্রধান শিক্ষকের স্বাক্ষর</div>
                </div>
                <div>
                    <div class="signature-box" style="font-weight: 600; color: #2c3e50;">পরীক্ষা কমিটির স্বাক্ষর</div>
                </div>
                <div>
                    <div class="signature-box" style="font-weight: 600; color: #2c3e50;">শ্রেণি শিক্ষকের স্বাক্ষর</div>
                </div>
            </div>
            

        </div>
        </div>
        <?php endforeach; ?>
        <?php elseif ($show_student_list): ?>
        <!-- Student List View -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4 class="card-title mb-0">শিক্ষার্থী নির্বাচন করুন</h4>
                <div>
                    <a href="all_subjects_marksheet.php" class="btn btn-secondary btn-sm me-2">
                        <i class="fas fa-arrow-left"></i> পিছনে
                    </a>
                    <a href="../index.php" class="btn btn-secondary btn-sm">
                        <i class="fas fa-home"></i> হোম
                    </a>
                </div>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <h5>শ্রেণী: 
                            <?php 
                            $selected_class = array_filter($classes, function($c) use ($class_id) { return $c['id'] == $class_id; });
                            echo !empty($selected_class) ? htmlspecialchars(reset($selected_class)['name'] . ' ' . reset($selected_class)['section']) : '';
                            ?>
                        </h5>
                    </div>
                    <div class="col-md-6">
                        <h5>সেশন: <?php echo htmlspecialchars($session); ?> | পরীক্ষার ধরন: <?php echo htmlspecialchars(ucfirst($exam_type)); ?></h5>
                    </div>
                </div>
                
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" id="student-search" class="form-control" placeholder="শিক্ষার্থী খুঁজুন (নাম, রোল, আইডি)" value="<?php echo htmlspecialchars($student_search); ?>">
                            <button class="btn btn-outline-secondary" type="button" id="search-btn">
                                <i class="fas fa-search"></i> খুঁজুন
                            </button>
                        </div>
                    </div>
                    <?php
                    if (!empty($students_in_class)):
                    ?>
                    <div class="col-md-6 text-end">
                        <button class="btn btn-success no-print" id="bulk-print-btn">
                            <i class="fas fa-print"></i> বাল্ক প্রিন্ট
                        </button>
                        <button class="btn btn-info no-print ms-2" id="print-selected-btn">
                            <i class="fas fa-check-square"></i> নির্বাচিতগুলো প্রিন্ট করুন
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="table-responsive" id="student-table-container">
                    <?php if (empty($students_in_class)): ?>
                        <div class="alert alert-info text-center">
                            <i class="fas fa-info-circle"></i> কোন তথ্য পাওয়া যায়নি
                        </div>
                    <?php else: ?>
                        <table class="student-list-table">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" id="select-all-students"></th>
                                    <th>রোল</th>
                                    <th>শিক্ষার্থী আইডি</th>
                                    <th>নাম</th>
                                    <th>কার্যক্রম</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($students_in_class as $student_item): ?>
                                <tr>
                                    <td><input type="checkbox" class="student-checkbox" value="<?php echo $student_item['id']; ?>"></td>
                                    <td><?php echo htmlspecialchars($student_item['roll_number']); ?></td>
                                    <td><?php echo htmlspecialchars($student_item['student_id']); ?></td>
                                    <td><?php echo htmlspecialchars($student_item['first_name'] . ' ' . $student_item['last_name']); ?></td>
                                    <td>
                                        <a href="?selected_students=<?php echo $student_item['id']; ?>&class_id=<?php echo urlencode($class_id); ?>&session=<?php echo urlencode($session); ?>&exam_type=<?php echo urlencode($exam_type); ?>" class="btn btn-primary btn-sm">
                                            <i class="fas fa-eye"></i> ফলাফল দেখুন
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                // This ensures the DOM is fully loaded before attaching event listeners

                // Handle 'Select All' checkbox
                const selectAllCheckbox = document.getElementById('select-all-students');
                if (selectAllCheckbox) {
                    selectAllCheckbox.addEventListener('change', function() {
                        const checkboxes = document.querySelectorAll('.student-checkbox');
                        checkboxes.forEach(checkbox => {
                            checkbox.checked = this.checked;
                        });
                    });
                }

                // Handle Print Selected button click
                const printSelectedBtn = document.getElementById('print-selected-btn');
                if (printSelectedBtn) {
                    printSelectedBtn.addEventListener('click', function() {
                        const selectedStudents = [];
                        const checkedCheckboxes = document.querySelectorAll('.student-checkbox:checked');
                        
                        checkedCheckboxes.forEach(checkbox => {
                            selectedStudents.push(checkbox.value);
                        });

                        if (selectedStudents.length === 0) {
                            alert('অনুগ্রহ করে অন্তত একজন শিক্ষার্থী নির্বাচন করুন।');
                            return;
                        }

                        const url = new URL(window.location.href);
                        url.searchParams.set('selected_students', selectedStudents.join(','));
                        url.searchParams.delete('bulk_print_all'); // Ensure bulk_print_all is not set
                        url.searchParams.delete('student_id');
                        window.location.href = url.toString();
                    });
                }
            });

            // Handle search button click
            document.getElementById('search-btn').addEventListener('click', function() {
                performSearch();
            });
            
            // Handle Enter key in search box
            document.getElementById('student-search').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    performSearch();
                }
            });
            
            // Make search dynamic with AJAX
            let searchTimeout;
            document.getElementById('student-search').addEventListener('input', function() {
                const searchTerm = this.value;
                // Clear previous timeout
                clearTimeout(searchTimeout);
                
                // Set new timeout
                searchTimeout = setTimeout(function() {
                    if (searchTerm.length >= 2 || searchTerm.length === 0) {
                        performSearch();
                    }
                }, 300); // 300ms delay
            });
            
            function performSearch() {
                const searchTerm = document.getElementById('student-search').value;
                const classId = '<?php echo $class_id; ?>';
                const session = '<?php echo $session; ?>';
                const examType = '<?php echo $exam_type; ?>';
                
                // Show loading indicator
                const container = document.getElementById('student-table-container');
                container.innerHTML = '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">লোড হচ্ছে...</span></div></div>';
                
                // Add CSS for spinner if not already present
                if (!document.getElementById('spinner-styles')) {
                    const style = document.createElement('style');
                    style.id = 'spinner-styles';
                    style.innerHTML = `
                        .spinner-border {
                            display: inline-block;
                            width: 2rem;
                            height: 2rem;
                            vertical-align: -0.125em;
                            border: 0.25em solid currentColor;
                            border-right-color: transparent;
                            border-radius: 50%;
                            animation: spinner-border 0.75s linear infinite;
                        }
                        @keyframes spinner-border {
                            to {
                                transform: rotate(360deg);
                            }
                        }
                        .text-primary {
                            color: #0d6efd;
                        }
                        .visually-hidden {
                            position: absolute;
                            width: 1px;
                            height: 1px;
                            padding: 0;
                            margin: -1px;
                            overflow: hidden;
                            clip: rect(0, 0, 0, 0);
                            white-space: nowrap;
                            border: 0;
                        }
                    `;
                    document.head.appendChild(style);
                }
                
                // For dynamic search, we'll use AJAX to update the table without page reload
                fetch(`marksheet_search.php?class_id=${classId}&session=${session}&exam_type=${examType}&student_search=${encodeURIComponent(searchTerm)}`)
                    .then(response => response.text())
                    .then(data => {
                        container.innerHTML = data;
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        container.innerHTML = '<div class="alert alert-danger text-center">ত্রুটি দেখা দিয়েছে, অনুগ্রহ করে আবার চেষ্টা করুন</div>';
                    });
            }
            
            function selectStudent(studentId) {
                const session = '<?php echo $session; ?>';
                const examType = '<?php echo $exam_type; ?>';
                window.location.href = `?student_id=${studentId}&session=${session}&exam_type=${examType}`;
            }
        </script>
        <!-- Initial Search Form -->
        <div class="card no-print">
            <div class="card-header">
                <h4 class="card-title">সকল বিষয়ের মার্কশীট অনুসন্ধান করুন</h4>
            </div>
            <div class="card-body">
                <form method="GET" action="" class="row g-3">
                    <div class="col-md-4">
                        <label for="class_id" class="form-label">শ্রেণী</label>
                        <select id="class_id" name="class_id" class="form-select" required>
                            <option value="">শ্রেণী নির্বাচন করুন</option>
                            <?php foreach ($classes as $class_item): ?>
                                <option value="<?php echo htmlspecialchars($class_item['id']); ?>">
                                    <?php echo htmlspecialchars($class_item['name'] . ' ' . $class_item['section']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="session" class="form-label">সেশন</label>
                        <select id="session" name="session" class="form-select" required>
                            <option value="">সেশন নির্বাচন করুন</option>
                            <?php foreach ($sessions as $session_item): ?>
                                <option value="<?php echo htmlspecialchars($session_item['session']); ?>">
                                    <?php echo htmlspecialchars($session_item['session']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="exam_type" class="form-label">পরীক্ষার ধরন</label>
                        <select id="exam_type" name="exam_type" class="form-select" required>
                            <option value="">পরীক্ষা নির্বাচন করুন</option>
                            <?php foreach ($exam_types as $exam_type_item): ?>
                                <option value="<?php echo htmlspecialchars($exam_type_item['exam_type']); ?>">
                                    <?php echo htmlspecialchars($exam_type_item['exam_type']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-12 text-center mt-3">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i> শিক্ষার্থী তালিকা দেখুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Function to initialize toggle switches based on URL parameters
    function initializeToggles() {
        // Set toggle states based on URL parameters
        const urlParams = new URLSearchParams(window.location.search);
        const showBanglaAvg = urlParams.get('show_bangla_avg') === 'true';
        const showEnglishAvg = urlParams.get('show_english_avg') === 'true';
        
        // Set the toggle switches (only if they exist)
        const showBanglaAvgElement = document.getElementById('showBanglaAvg');
        const showEnglishAvgElement = document.getElementById('showEnglishAvg');
        if (showBanglaAvgElement) {
            showBanglaAvgElement.value = showBanglaAvg.toString();
        }
        if (showEnglishAvgElement) {
            showEnglishAvgElement.value = showEnglishAvg.toString();
        }
                    
        // Set merit sort toggle based on URL parameter
        const sortByGpa = urlParams.get('sort_by_gpa') === 'true';
        const meritSortToggle = document.getElementById('meritSortToggle');
        if (meritSortToggle) {
            meritSortToggle.checked = sortByGpa;
            // Update text based on state
            const meritSortText = document.getElementById('meritSortText');
            if (meritSortText) {
                meritSortText.textContent = sortByGpa ? 'জিপিএ' : 'টোটাল মার্ক্স';
            }
        }
    }
    
    // Call initializeToggles when the page loads
    document.addEventListener('DOMContentLoaded', function() {
        initializeToggles();
    });
    
    // Function to apply custom marks to the marksheet
    function applyCustomMarks() {
        // Get custom values from modal
        const customBanglaCq1 = parseFloat(document.getElementById('customBanglaCq1').value);
        const customBanglaCq2 = parseFloat(document.getElementById('customBanglaCq2').value);
        const customBanglaMcq1 = parseFloat(document.getElementById('customBanglaMcq1').value);
        const customBanglaMcq2 = parseFloat(document.getElementById('customBanglaMcq2').value);
        const customBanglaTotal = parseFloat(document.getElementById('customBanglaTotal').value);
        const customEnglishCq1 = parseFloat(document.getElementById('customEnglishCq1').value);
        const customEnglishCq2 = parseFloat(document.getElementById('customEnglishCq2').value);
        const customEnglishMcq1 = parseFloat(document.getElementById('customEnglishMcq1').value);
        const customEnglishMcq2 = parseFloat(document.getElementById('customEnglishMcq2').value);
        const customEnglishTotal = parseFloat(document.getElementById('customEnglishTotal').value);
        
        // Get toggle states
        const showBanglaAvg = document.getElementById('showBanglaAvg').value === 'true';
        const showEnglishAvg = document.getElementById('showEnglishAvg').value === 'true';
        
        // Calculate averages
        let customBanglaCqAvg = null;
        let customBanglaMcqAvg = null;
        let customBanglaCqTotal = null;
        let customBanglaMcqTotal = null;
        if (!isNaN(customBanglaCq1) && !isNaN(customBanglaCq2)) {
            customBanglaCqAvg = (customBanglaCq1 + customBanglaCq2) / 2;
            customBanglaCqTotal = customBanglaCq1 + customBanglaCq2;
        } else if (!isNaN(customBanglaCq1)) {
            customBanglaCqAvg = customBanglaCq1;
            customBanglaCqTotal = customBanglaCq1;
        } else if (!isNaN(customBanglaCq2)) {
            customBanglaCqAvg = customBanglaCq2;
            customBanglaCqTotal = customBanglaCq2;
        }
        
        if (!isNaN(customBanglaMcq1) && !isNaN(customBanglaMcq2)) {
            customBanglaMcqAvg = (customBanglaMcq1 + customBanglaMcq2) / 2;
            customBanglaMcqTotal = customBanglaMcq1 + customBanglaMcq2;
        } else if (!isNaN(customBanglaMcq1)) {
            customBanglaMcqAvg = customBanglaMcq1;
            customBanglaMcqTotal = customBanglaMcq1;
        } else if (!isNaN(customBanglaMcq2)) {
            customBanglaMcqAvg = customBanglaMcq2;
            customBanglaMcqTotal = customBanglaMcq2;
        }
        
        let customEnglishCqAvg = null;
        let customEnglishMcqAvg = null;
        let customEnglishCqTotal = null;
        let customEnglishMcqTotal = null;
        if (!isNaN(customEnglishCq1) && !isNaN(customEnglishCq2)) {
            customEnglishCqAvg = (customEnglishCq1 + customEnglishCq2) / 2;
            customEnglishCqTotal = customEnglishCq1 + customEnglishCq2;
        } else if (!isNaN(customEnglishCq1)) {
            customEnglishCqAvg = customEnglishCq1;
            customEnglishCqTotal = customEnglishCq1;
        } else if (!isNaN(customEnglishCq2)) {
            customEnglishCqAvg = customEnglishCq2;
            customEnglishCqTotal = customEnglishCq2;
        }
        
        if (!isNaN(customEnglishMcq1) && !isNaN(customEnglishMcq2)) {
            customEnglishMcqAvg = (customEnglishMcq1 + customEnglishMcq2) / 2;
            customEnglishMcqTotal = customEnglishMcq1 + customEnglishMcq2;
        } else if (!isNaN(customEnglishMcq1)) {
            customEnglishMcqAvg = customEnglishMcq1;
            customEnglishMcqTotal = customEnglishMcq1;
        } else if (!isNaN(customEnglishMcq2)) {
            customEnglishMcqAvg = customEnglishMcq2;
            customEnglishMcqTotal = customEnglishMcq2;
        }
        
        // Update Bangla subject in the table if exists
        if (!isNaN(customBanglaCq1) || !isNaN(customBanglaCq2) || !isNaN(customBanglaMcq1) || !isNaN(customBanglaMcq2) || !isNaN(customBanglaTotal)) {
            const banglaRows = document.querySelectorAll('tr td:first-child');
            for (let i = 0; i < banglaRows.length; i++) {
                if (banglaRows[i].textContent.includes('বাংলা(একত্রে)') || 
                    banglaRows[i].textContent.includes('বাংলা (১ম ও ২য় পত্র)')) {
                    const row = banglaRows[i].parentElement;
                    
                    // Update CQ marks (second column) - show based on toggle
                    let cqDisplay = '';
                    if (!isNaN(customBanglaCq1) && !isNaN(customBanglaCq2)) {
                        if (showBanglaAvg) {
                            cqDisplay = Math.floor(customBanglaCq1) + ', ' + Math.floor(customBanglaCq2) + ' (গড়: ' + Math.floor(customBanglaCqAvg) + ')';
                        } else {
                            cqDisplay = Math.floor(customBanglaCq1) + ', ' + Math.floor(customBanglaCq2) + ' (মোট: ' + Math.floor(customBanglaCqTotal) + ')';
                        }
                    } else if (!isNaN(customBanglaCq1)) {
                        cqDisplay = Math.floor(customBanglaCq1);
                    } else if (!isNaN(customBanglaCq2)) {
                        cqDisplay = Math.floor(customBanglaCq2);
                    } else if (!isNaN(customBanglaCqAvg)) {
                        if (showBanglaAvg) {
                            cqDisplay = Math.floor(customBanglaCqAvg);
                        } else {
                            cqDisplay = Math.floor(customBanglaCqTotal);
                        }
                    }
                    
                    if (cqDisplay) {
                        row.cells[1].textContent = cqDisplay;
                    }
                    
                    // Update MCQ marks (third column) - show based on toggle
                    let mcqDisplay = '';
                    if (!isNaN(customBanglaMcq1) && !isNaN(customBanglaMcq2)) {
                        if (showBanglaAvg) {
                            mcqDisplay = Math.floor(customBanglaMcq1) + ', ' + Math.floor(customBanglaMcq2) + ' (গড়: ' + Math.floor(customBanglaMcqAvg) + ')';
                        } else {
                            mcqDisplay = Math.floor(customBanglaMcq1) + ', ' + Math.floor(customBanglaMcq2) + ' (মোট: ' + Math.floor(customBanglaMcqTotal) + ')';
                        }
                    } else if (!isNaN(customBanglaMcq1)) {
                        mcqDisplay = Math.floor(customBanglaMcq1);
                    } else if (!isNaN(customBanglaMcq2)) {
                        mcqDisplay = Math.floor(customBanglaMcq2);
                    } else if (!isNaN(customBanglaMcqAvg)) {
                        if (showBanglaAvg) {
                            mcqDisplay = Math.floor(customBanglaMcqAvg);
                        } else {
                            mcqDisplay = Math.floor(customBanglaMcqTotal);
                        }
                    }
                    
                    if (mcqDisplay) {
                        row.cells[2].textContent = mcqDisplay;
                    }
                    
                    // Update total marks (8th column, obtained marks)
                    if (!isNaN(customBanglaTotal)) {
                        row.cells[7].textContent = Math.floor(customBanglaTotal);
                        
                        // Also update the marks_obtained in the PHP variable if possible
                        // Since we can't directly modify PHP variables after page load, 
                        // we'll need to update the displayed total marks
                        updateTotalMarks();
                    }
                    
                    break;
                }
            }
        }
        
        // Update English subject in the table if exists
        if (!isNaN(customEnglishCq1) || !isNaN(customEnglishCq2) || !isNaN(customEnglishMcq1) || !isNaN(customEnglishMcq2) || !isNaN(customEnglishTotal)) {
            const englishRows = document.querySelectorAll('tr td:first-child');
            for (let i = 0; i < englishRows.length; i++) {
                if (englishRows[i].textContent.includes('ইংরেজি(একত্রে)') || 
                    englishRows[i].textContent.includes('ইংরেজি (১ম ও ২য় পত্র)')) {
                    const row = englishRows[i].parentElement;
                    
                    // Update CQ marks (second column) - show based on toggle
                    let cqDisplay = '';
                    if (!isNaN(customEnglishCq1) && !isNaN(customEnglishCq2)) {
                        if (showEnglishAvg) {
                            cqDisplay = Math.floor(customEnglishCq1) + ', ' + Math.floor(customEnglishCq2) + ' (গড়: ' + Math.floor(customEnglishCqAvg) + ')';
                        } else {
                            cqDisplay = Math.floor(customEnglishCq1) + ', ' + Math.floor(customEnglishCq2) + ' (মোট: ' + Math.floor(customEnglishCqTotal) + ')';
                        }
                    } else if (!isNaN(customEnglishCq1)) {
                        cqDisplay = Math.floor(customEnglishCq1);
                    } else if (!isNaN(customEnglishCq2)) {
                        cqDisplay = Math.floor(customEnglishCq2);
                    } else if (!isNaN(customEnglishCqAvg)) {
                        if (showEnglishAvg) {
                            cqDisplay = Math.floor(customEnglishCqAvg);
                        } else {
                            cqDisplay = Math.floor(customEnglishCqTotal);
                        }
                    }
                    
                    if (cqDisplay) {
                        row.cells[1].textContent = cqDisplay;
                    }
                    
                    // Update MCQ marks (third column) - show based on toggle
                    let mcqDisplay = '';
                    if (!isNaN(customEnglishMcq1) && !isNaN(customEnglishMcq2)) {
                        if (showEnglishAvg) {
                            mcqDisplay = Math.floor(customEnglishMcq1) + ', ' + Math.floor(customEnglishMcq2) + ' (গড়: ' + Math.floor(customEnglishMcqAvg) + ')';
                        } else {
                            mcqDisplay = Math.floor(customEnglishMcq1) + ', ' + Math.floor(customEnglishMcq2) + ' (মোট: ' + Math.floor(customEnglishMcqTotal) + ')';
                        }
                    } else if (!isNaN(customEnglishMcq1)) {
                        mcqDisplay = Math.floor(customEnglishMcq1);
                    } else if (!isNaN(customEnglishMcq2)) {
                        mcqDisplay = Math.floor(customEnglishMcq2);
                    } else if (!isNaN(customEnglishMcqAvg)) {
                        if (showEnglishAvg) {
                            mcqDisplay = Math.floor(customEnglishMcqAvg);
                        } else {
                            mcqDisplay = Math.floor(customEnglishMcqTotal);
                        }
                    }
                    
                    if (mcqDisplay) {
                        row.cells[2].textContent = mcqDisplay;
                    }
                    
                    // Update total marks (8th column, obtained marks)
                    if (!isNaN(customEnglishTotal)) {
                        row.cells[7].textContent = Math.floor(customEnglishTotal);
                        
                        // Update the total marks
                        updateTotalMarks();
                    }
                    
                    break;
                }
            }
        }
        
        // Close modal
        const modal = bootstrap.Modal.getInstance(document.getElementById('customMarksModal'));
        if (modal) {
            modal.hide();
        }
        
        // Create URL with custom parameters and redirect to refresh with new values
        let url = new URL(window.location);
        if (!isNaN(customBanglaCq1)) url.searchParams.set('custom_bangla_cq1', customBanglaCq1);
        if (!isNaN(customBanglaCq2)) url.searchParams.set('custom_bangla_cq2', customBanglaCq2);
        if (!isNaN(customBanglaMcq1)) url.searchParams.set('custom_bangla_mcq1', customBanglaMcq1);
        if (!isNaN(customBanglaMcq2)) url.searchParams.set('custom_bangla_mcq2', customBanglaMcq2);
        if (!isNaN(customBanglaTotal)) url.searchParams.set('custom_bangla_total', customBanglaTotal);
        if (!isNaN(customEnglishCq1)) url.searchParams.set('custom_english_cq1', customEnglishCq1);
        if (!isNaN(customEnglishCq2)) url.searchParams.set('custom_english_cq2', customEnglishCq2);
        if (!isNaN(customEnglishMcq1)) url.searchParams.set('custom_english_mcq1', customEnglishMcq1);
        if (!isNaN(customEnglishMcq2)) url.searchParams.set('custom_english_mcq2', customEnglishMcq2);
        if (!isNaN(customEnglishTotal)) url.searchParams.set('custom_english_total', customEnglishTotal);
        
        // Add toggle parameters
        url.searchParams.set('show_bangla_avg', showBanglaAvg);
        url.searchParams.set('show_english_avg', showEnglishAvg);
        
        // Redirect to the same page with custom parameters
        window.location.href = url.toString();
    }
    
    // Function to update total marks in the summary
    function updateTotalMarks() {
        // This would require recalculating the total marks and updating the summary
        // Since we can't modify PHP variables after page load, this is a client-side update only
    }
    
    // Add bulk print functionality
    document.addEventListener('DOMContentLoaded', function() {
        // Select all checkbox functionality
        const selectAllCheckbox = document.getElementById('select-all-checkbox');
        const studentCheckboxes = document.querySelectorAll('.student-checkbox');
        
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', function() {
                studentCheckboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });
        }
        
        // Individual checkbox functionality
        studentCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                // If any checkbox is unchecked, uncheck the select all checkbox
                if (!this.checked) {
                    selectAllCheckbox.checked = false;
                }
                // If all checkboxes are checked, check the select all checkbox
                else if (Array.from(studentCheckboxes).every(cb => cb.checked)) {
                    selectAllCheckbox.checked = true;
                }
            });
        });
        
        const bulkPrintBtn = document.getElementById('bulk-print-btn');
        if (bulkPrintBtn) {
            bulkPrintBtn.addEventListener('click', function() {
                // Get current search parameters
                const urlParams = new URLSearchParams(window.location.search);
                const classId = urlParams.get('class_id');
                const session = urlParams.get('session');
                const examType = urlParams.get('exam_type');
                const studentSearch = urlParams.get('student_search') || '';
                const showBanglaAvg = urlParams.get('show_bangla_avg') !== null ? urlParams.get('show_bangla_avg') : 'true';
                const showEnglishAvg = urlParams.get('show_english_avg') !== null ? urlParams.get('show_english_avg') : 'true';
                const sortByGpa = urlParams.get('sort_by_gpa');
                const sortByTotalPoints = urlParams.get('sort_by_total_points');
                
                // Build URL with all necessary parameters
                let bulkPrintUrl = `bulk_print_marksheets.php?class_id=${encodeURIComponent(classId)}&session=${encodeURIComponent(session)}&exam_type=${encodeURIComponent(examType)}&bulk_print_all=1&show_bangla_avg=${showBanglaAvg}&show_english_avg=${showEnglishAvg}`;
                
                // Include student search if present
                if (studentSearch) {
                    bulkPrintUrl += `&student_search=${encodeURIComponent(studentSearch)}`;
                }
                
                // Include merit position sorting if present
                if (sortByGpa) {
                    bulkPrintUrl += `&sort_by_gpa=${sortByGpa}`;
                }
                if (sortByTotalPoints) {
                    bulkPrintUrl += `&sort_by_total_points=${sortByTotalPoints}`;
                }
                
                window.open(bulkPrintUrl, '_blank');
            });
        }


        // Print separately functionality (all students with page breaks between each)
        const printSeparatelyBtn = document.getElementById('print-separately-btn');
        if (printSeparatelyBtn) {
            printSeparatelyBtn.addEventListener('click', function() {
                // Get current search parameters
                const urlParams = new URLSearchParams(window.location.search);
                const classId = urlParams.get('class_id');
                const session = urlParams.get('session');
                const examType = urlParams.get('exam_type');
                const studentSearch = urlParams.get('student_search') || '';
                const showBanglaAvg = urlParams.get('show_bangla_avg') !== null ? urlParams.get('show_bangla_avg') : 'true';
                const showEnglishAvg = urlParams.get('show_english_avg') !== null ? urlParams.get('show_english_avg') : 'true';
                const sortByGpa = urlParams.get('sort_by_gpa');
                const sortByTotalPoints = urlParams.get('sort_by_total_points');
                
                // Build URL with all necessary parameters and separate_print flag
                let separatePrintUrl = `bulk_print_marksheets.php?class_id=${encodeURIComponent(classId)}&session=${encodeURIComponent(session)}&exam_type=${encodeURIComponent(examType)}&bulk_print_all=1&separate_print=1&show_bangla_avg=${showBanglaAvg}&show_english_avg=${showEnglishAvg}`;
                
                // Include student search if present
                if (studentSearch) {
                    separatePrintUrl += `&student_search=${encodeURIComponent(studentSearch)}`;
                }
                
                // Include merit position sorting if present
                if (sortByGpa) {
                    separatePrintUrl += `&sort_by_gpa=${sortByGpa}`;
                }
                if (sortByTotalPoints) {
                    separatePrintUrl += `&sort_by_total_points=${sortByTotalPoints}`;
                }
                
                window.open(separatePrintUrl, '_blank');
            });
        }
        
        // Print selected students functionality
        const printSelectedBtn = document.getElementById('print-selected-btn');
        if (printSelectedBtn) {
            printSelectedBtn.addEventListener('click', function() {
                // Get selected student IDs
                const selectedCheckboxes = document.querySelectorAll('.student-checkbox:checked');
                if (selectedCheckboxes.length === 0) {
                    alert('দয়া করে অন্তত একজন শিক্ষার্থী নির্বাচন করুন');
                    return;
                }
                
                const selectedStudentIds = Array.from(selectedCheckboxes).map(cb => cb.dataset.studentId);
                
                // Get current search parameters
                const urlParams = new URLSearchParams(window.location.search);
                const classId = urlParams.get('class_id');
                const session = urlParams.get('session');
                const examType = urlParams.get('exam_type');
                const showBanglaAvg = urlParams.get('show_bangla_avg') !== null ? urlParams.get('show_bangla_avg') : 'true';
                const showEnglishAvg = urlParams.get('show_english_avg') !== null ? urlParams.get('show_english_avg') : 'true';
                const sortByGpa = urlParams.get('sort_by_gpa');
                const sortByTotalPoints = urlParams.get('sort_by_total_points');
                
                // Redirect to bulk print page with selected student IDs
                const selectedStudentsParam = selectedStudentIds.join(',');
                let bulkPrintUrl = `bulk_print_marksheets.php?class_id=${encodeURIComponent(classId)}&session=${encodeURIComponent(session)}&exam_type=${encodeURIComponent(examType)}&selected_students=${encodeURIComponent(selectedStudentsParam)}&show_bangla_avg=${showBanglaAvg}&show_english_avg=${showEnglishAvg}`;
                
                // Include merit position sorting if present
                if (sortByGpa) {
                    bulkPrintUrl += `&sort_by_gpa=${sortByGpa}`;
                }
                if (sortByTotalPoints) {
                    bulkPrintUrl += `&sort_by_total_points=${sortByTotalPoints}`;
                }
                
                window.open(bulkPrintUrl, '_blank');
            });
        }
        
        // 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 total (মোট), Unchecked = show average (গড়)
                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 total (false), unchecked means show average (true)
                urlParams.set(paramName, this.checked ? 'false' : 'true');
                
                // Reload page with new parameters
                window.location.search = urlParams.toString();
            });
        }
        
        // Handle Bengali toggle (individual view)
        handleToggleChange('banglaToggle', 'banglaToggleText', 'show_bangla_avg');
        
        // Handle English toggle (individual view)
        handleToggleChange('englishToggle', 'englishToggleText', 'show_english_avg');
        
        // Handle Bengali toggle (bulk view)
        handleToggleChange('banglaToggleBulk', 'banglaToggleTextBulk', 'show_bangla_avg');
        
        // Handle English toggle (bulk view)
        handleToggleChange('englishToggleBulk', 'englishToggleTextBulk', 'show_english_avg');
        
        // Handle Merit Position Sorting dropdown (bulk view)
        const meritSortSelect = document.getElementById('meritSortSelect');
        if (meritSortSelect) {
            // Initialize dropdown based on URL parameters
            const urlParams = new URLSearchParams(window.location.search);
            const sortByGpa = urlParams.get('sort_by_gpa');
            const sortByTotalPoints = urlParams.get('sort_by_total_points');
            
            if (sortByTotalPoints === 'true') {
                meritSortSelect.value = 'total_points';
            } else if (sortByGpa === 'true') {
                meritSortSelect.value = 'gpa';
            } else {
                meritSortSelect.value = 'total_marks'; // default
            }
            
            meritSortSelect.addEventListener('change', function() {
                // Get current URL parameters
                const urlParams = new URLSearchParams(window.location.search);
                
                // Clear existing sort parameters
                urlParams.delete('sort_by_gpa');
                urlParams.delete('sort_by_total_points');
                
                // Set the appropriate parameter based on selection
                if (this.value === 'gpa') {
                    urlParams.set('sort_by_gpa', 'true');
                } else if (this.value === 'total_points') {
                    urlParams.set('sort_by_total_points', 'true');
                }
                // For 'total_marks', no parameter is needed (it's the default)
                
                // Reload page with new parameters
                window.location.search = urlParams.toString();
            });
        }
        
        // Handle Merit Position Visibility Toggle
        function updateMeritToggleText(toggleId, textId) {
            const toggle = document.getElementById(toggleId);
            const text = document.getElementById(textId);
            if (toggle && text) {
                // Checked = show merit position (হ্যাঁ), Unchecked = hide merit position (না)
                text.textContent = toggle.checked ? 'হ্যাঁ' : 'না';
            }
        }
        
        const showMeritToggle = document.getElementById('showMeritToggle');
        if (showMeritToggle) {
            // Initialize toggle text based on current state
            updateMeritToggleText('showMeritToggle', 'showMeritToggleText');
            
            showMeritToggle.addEventListener('change', function() {
                // Update toggle text
                updateMeritToggleText('showMeritToggle', 'showMeritToggleText');
                
                // Get current URL parameters
                const urlParams = new URLSearchParams(window.location.search);
                
                // Set the parameter: checked means show merit position (true), unchecked means hide (false)
                urlParams.set('show_merit_position', this.checked ? 'true' : 'false');
                
                // Reload page with new parameters
                window.location.search = urlParams.toString();
            });
        }
    });
    </script>
</body>
</html>
