<?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;

// 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) : true;
$show_english_avg = isset($_GET['show_english_avg']) ? filter_var($_GET['show_english_avg'], FILTER_VALIDATE_BOOLEAN) : 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) {
    // Only show student list if not doing bulk print
    if (!($bulk_print_all || $separate_print || !empty($selected_students))) {
        $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, get all students in class
        // If specific students are selected, we'll filter them later
        $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]);
    }
    $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 {
        // If specific students are selected, get those specific students regardless of results
        if (!empty($selected_students)) {
            $selected_student_ids = explode(',', $selected_students);
            // Get specific selected students
            $placeholders = str_repeat('?,', count($selected_student_ids) - 1) . '?';
            $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 s.id IN ($placeholders)
                ORDER BY s.roll_number, s.first_name, s.last_name
            ");
            $params = array_merge([$class_id], $selected_student_ids);
            $stmt->execute($params);
            $students_in_class = $stmt->fetchAll();
        } else {
            // Apply search filter only when not bulk printing and no specific students selected
            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 (($bulk_print_all || $separate_print || !empty($selected_students)) && !empty($students_in_class)) {
        // Ensure we're processing all selected students
        $students_to_process = $students_in_class; // Use the filtered students_in_class array
        foreach ($students_to_process 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)) {
                    // 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 = $middle_subjects; // Apply custom layout function here if needed
                        
                // 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, $custom_bangla_cq1, $custom_bangla_cq2, $custom_bangla_mcq1, $custom_bangla_mcq2, $custom_bangla_total);
                                    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, $custom_english_cq1, $custom_english_cq2, $custom_english_mcq1, $custom_english_mcq2, $custom_english_total);
                                    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 with the correct logic
$merit_positions = [];

if (!empty($all_students_data)) {
    // Create an array of student data for merit calculation
    $student_merit_data = [];
    foreach ($all_students_data as $index => $student_data) {
        $student_merit_data[$student_data['student']['id']] = [
            'total_obtained' => $student_data['total_obtained'],
            'gpa' => $student_data['gpa'],
            'index' => $index // Store original index to update the right student in all_students_data
        ];
    }
    
    // Sort students by GPA (descending), then by total marks (descending) for tie-breaking
    uasort($student_merit_data, function($a, $b) {
        // First, sort by GPA (descending)
        if ($a['gpa'] != $b['gpa']) {
            return $b['gpa'] <=> $a['gpa'];
        }
        // If GPAs are equal, sort by total obtained marks (descending)
        return $b['total_obtained'] <=> $a['total_obtained'];
    });
    
    // Create an array of merit positions
    $position = 1;
    foreach ($student_merit_data as $student_id => $data) {
        // Assign merit position to all students (including those with GPA 0)
        $merit_positions[$student_id] = $position++;
    }
    
    // Update the all_students_data array with merit positions
    foreach ($all_students_data as $index => &$student_data) {
        $student_id = $student_data['student']['id'];
        if (isset($merit_positions[$student_id])) {
            $all_students_data[$index]['merit_position'] = $merit_positions[$student_id];
        } else {
            $all_students_data[$index]['merit_position'] = null;
        }
    }
    unset($student_data); // Remove reference
}

// 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 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 to get grade point
function getGradePoint($grade) {
    switch ($grade) {
        case 'A+': return 5.00;
        case 'A': return 4.00;
        case 'A-': return 3.50;
        case 'B': return 3.00;
        case 'C': return 2.00;
        case 'D': return 1.00;
        default: return 0.00;
    }
}

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

// Function to calculate English subject grade based on new criteria
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';
    }
}

// Function to calculate overall grade
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';
}

// Generate PDF if requested
if (isset($_GET['generate_pdf']) && $class_id && $session && $exam_type) {
    // Set headers to download PDF
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="merit_position_bulk_print_' . $class_id . '_' . $session . '_' . $exam_type . '.pdf"');
    header('Cache-Control: private, no-cache, must-revalidate');
    header('Pragma: no-cache');
    
    // Generate HTML content for PDF conversion
    ob_start();
    ?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>মেরিট পজিশন সহ মার্কশীট - <?php echo htmlspecialchars($site_name); ?></title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap');
        body {
            font-family: 'Hind Siliguri', sans-serif;
            font-size: 12px;
            margin: 0;
            padding: 0;
        }
        .marksheet {
            border: 2px solid #2c3e50;
            padding: 15px;
            margin: 15px auto;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            max-width: 800px;
            position: relative;
            overflow: hidden;
            page-break-inside: avoid;
        }
        .school-header {
            text-align: center;
            border-bottom: 2px double #3498db;
            padding-bottom: 10px;
            margin-bottom: 15px;
            background: linear-gradient(to right, #ffffff, #e3f2fd, #ffffff);
            border-radius: 6px 6px 0 0;
            margin-left: -15px;
            margin-right: -15px;
            padding-left: 15px;
            padding-right: 15px;
            position: relative;
        }
        .school-logo {
            width: 80px;
            height: 80px;
            border: 2px solid #3498db;
            border-radius: 50%;
            display: block;
            margin: 0 auto 10px;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 40px;
            color: #3498db;
        }
        .school-name {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
            margin: 0;
            text-transform: uppercase;
        }
        .school-address {
            font-size: 14px;
            color: #7f8c8d;
            margin: 5px 0 0;
        }
        .exam-title {
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
            margin: 15px 0;
            text-transform: uppercase;
            border: 1px solid #3498db;
            padding: 8px;
            border-radius: 5px;
            background: #e3f2fd;
        }
        .student-info {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-bottom: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        .info-item {
            margin-bottom: 5px;
        }
        .info-label {
            font-weight: bold;
            color: #2c3e50;
        }
        .subject-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
            font-size: 11px;
        }
        .subject-table th, .subject-table td {
            border: 1px solid #bdc3c7;
            padding: 6px;
            text-align: center;
        }
        .subject-table th {
            background: #3498db;
            color: white;
            font-weight: bold;
        }
        .subject-table .subject-name {
            text-align: left;
        }
        .results-summary {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin: 15px 0;
            padding: 10px;
            background: #e8f4f8;
            border-radius: 5px;
        }
        .summary-item {
            text-align: center;
        }
        .summary-label {
            font-weight: bold;
            color: #2c3e50;
        }
        .summary-value {
            font-size: 16px;
            font-weight: bold;
            color: #e74c3c;
        }
        .pdf-controls {
            text-align: center;
            margin: 20px 0;
        }
        .btn {
            padding: 10px 20px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin: 0 5px;
        }
        .btn:hover {
            background: #2980b9;
        }
        .btn-print {
            background: #27ae60;
        }
        .btn-print:hover {
            background: #219653;
        }
        .btn-download {
            background: #e74c3c;
        }
        .btn-download:hover {
            background: #c0392b;
        }
        @media print {
            .pdf-controls {
                display: none;
            }
            body {
                margin: 0;
                padding: 10px;
            }
            .marksheet {
                border: 2px solid #2c3e50;
                box-shadow: none;
                margin: 0;
            }
        }
    </style>
</head>
<body>
    <div id="pdfContent">
        <?php if ($bulk_print_all || $separate_print || !empty($selected_students)) : ?>
            <?php foreach ($all_students_data as $student_data) : 
                $student = $student_data['student'];
                $results = $student_data['results'];
                $gpa = $student_data['gpa'];
                $merit_position = $student_data['merit_position'] ?? null;
            ?> 
                <div class="marksheet">
                    <div class="school-header">
                        <?php if ($logo_image) : ?>
                            <div class="school-logo">
                                <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="School Logo" style="max-width: 80px; max-height: 80px;">
                            </div>
                        <?php endif; ?>
                        <h2 class="school-name"><?php echo htmlspecialchars($site_name); ?></h2>
                        <p class="school-address"><?php echo htmlspecialchars($site_address); ?></p>
                    </div>
                    
                    <h3 class="exam-title">
                        <?php echo htmlspecialchars($student['class_name'] . ' ' . $student['section'] . ' - ' . $exam_type . ' পরীক্ষা ' . $session); ?>
                    </h3>
                    
                    <div class="student-info">
                        <div class="info-item">
                            <span class="info-label">নাম:</span>
                            <span><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">রোল:</span>
                            <span><?php echo htmlspecialchars($student['roll_number']); ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">শিক্ষার্থী আইডি:</span>
                            <span><?php echo htmlspecialchars($student['student_id']); ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">গ্রুপ:</span>
                            <span><?php echo htmlspecialchars($student['group_name'] ?? 'N/A'); ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">GPA:</span>
                            <span><?php echo number_format($gpa, 2); ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">মেরিট পজিশন:</span>
                            <span><?php echo $merit_position ? $merit_position : 'N/A'; ?></span>
                        </div>
                    </div>
                    
                    <table class="subject-table">
                        <thead>
                            <tr>
                                <th>বিষয়</th>
                                <th>পূর্ণ নম্বর</th>
                                <th>প্রাপ্ত নম্বর</th>
                                <th>গ্রেড</th>
                                <th>জিপিএ</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($results as $result) : ?>
                            <tr>
                                <td class="subject-name"><?php echo htmlspecialchars($result['subject_name']); ?></td>
                                <td><?php echo $result['full_marks']; ?></td>
                                <td>
                                    <?php 
                                    if ($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') {
                                        // For combined subjects, show average or total based on toggle
                                        if (($result['subject_name'] == 'বাংলা(একত্রে)' && $show_bangla_avg) || 
                                            ($result['subject_name'] == 'ইংরেজি(একত্রে)' && $show_english_avg)) {
                                            // Show 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']);
                                            echo number_format($avg_cq + $avg_mcq, 2);
                                        } else {
                                            // Show total: total_cq + total_mcq
                                            $total_cq = array_sum($result['cq_marks_array']);
                                            $total_mcq = array_sum($result['mcq_marks_array']);
                                            echo number_format($total_cq + $total_mcq, 2);
                                        }
                                    } else {
                                        echo $result['marks_obtained'];
                                    }
                                    ?>
                                </td>
                                <td><?php echo $result['grade']; ?></td>
                                <td><?php echo $result['grade_point']; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <div class="results-summary">
                        <div class="summary-item">
                            <div class="summary-label">মোট নম্বর</div>
                            <div class="summary-value"><?php echo $student_data['total_obtained']; ?></div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">পরীক্ষার্থী</div>
                            <div class="summary-value"><?php echo $student_data['total_subjects']; ?></div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">পাশ</div>
                            <div class="summary-value"><?php echo $student_data['passed_subjects']; ?></div>
                        </div>
                        <div class="summary-item">
                            <div class="summary-label">জিপিএ</div>
                            <div class="summary-value"><?php echo number_format($gpa, 2); ?></div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <p>কোনো শিক্ষার্থী নির্বাচন করা হয়নি।</p>
        <?php endif; ?>
    </div>
    
    <div class="pdf-controls">
        <button class="btn btn-print" onclick="window.print()">প্রিন্ট করুন</button>
        <button class="btn btn-download" onclick="generatePDF()">পিডিএফ ডাউনলোড করুন</button>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    
    <script>
        function generatePDF() {
            const { jsPDF } = window.jspdf;
            
            html2canvas(document.getElementById('pdfContent')).then(canvas => {
                const imgData = canvas.toDataURL('image/png');
                const pdf = new jsPDF('p', 'mm', 'a4');
                const imgWidth = 210; // A4 width in mm
                const pageHeight = 297; // A4 height in mm
                const imgHeight = canvas.height * imgWidth / canvas.width;
                
                let heightLeft = imgHeight;
                let position = 0;
                
                pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;
                
                while (heightLeft >= 0) {
                    position = heightLeft - imgHeight;
                    pdf.addPage();
                    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                    heightLeft -= pageHeight;
                }
                
                pdf.save('merit_position_bulk_print_<?php echo $class_id . '_' . $session . '_' . $exam_type; ?>.pdf');
            });
        }
    </script>
</body>
</html>
<?php
        $html_content = ob_get_contents();
        ob_end_clean();
        echo $html_content;
        exit();
    }
else {
    // If not generating PDF, show the regular page
    // Form for selecting students
    ?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>মেরিট পজিশন সহ মার্কশীট - <?php echo htmlspecialchars($site_name); ?></title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap');
        body {
            font-family: 'Hind Siliguri', sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .btn {
            background: #3498db;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn:hover {
            background: #2980b9;
        }
        .btn-print {
            background: #27ae60;
        }
        .btn-print:hover {
            background: #219653;
        }
        .btn-pdf {
            background: #e74c3c;
        }
        .btn-pdf:hover {
            background: #c0392b;
        }
        .student-list {
            margin-top: 20px;
        }
        .student-item {
            padding: 10px;
            border: 1px solid #ddd;
            margin-bottom: 5px;
            border-radius: 4px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .selected-students {
            margin-top: 20px;
            padding: 15px;
            background: #e8f4f8;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>মেরিট পজিশন সহ মার্কশীট</h1>
        
        <form method="GET" action="">
            <div class="form-group">
                <label for="class_id">ক্লাস:</label>
                <select name="class_id" id="class_id" required onchange="this.form.submit()">
                    <option value="">ক্লাস নির্বাচন করুন</option>
                    <?php foreach ($classes as $class) : ?>
                        <option value="<?php echo $class['id']; ?>" <?php echo $class_id == $class['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($class['name'] . ' ' . $class['section']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <?php if ($class_id) : ?>
            <div class="form-group">
                <label for="session">সেশন:</label>
                <select name="session" id="session" required onchange="this.form.submit()">
                    <option value="">সেশন নির্বাচন করুন</option>
                    <?php for ($i = date('Y') - 5; $i <= date('Y') + 1; $i++) : ?>
                        <option value="<?php echo $i; ?>" <?php echo $session == $i ? 'selected' : ''; ?>>
                            <?php echo $i; ?>
                        </option>
                    <?php endfor; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label for="exam_type">পরীক্ষার ধরন:</label>
                <select name="exam_type" id="exam_type" required onchange="this.form.submit()">
                    <option value="">পরীক্ষার ধরন নির্বাচন করুন</option>
                    <option value="first_term" <?php echo $exam_type == 'first_term' ? 'selected' : ''; ?>>প্রথম টার্ম</option>
                    <option value="second_term" <?php echo $exam_type == 'second_term' ? 'selected' : ''; ?>>দ্বিতীয় টার্ম</option>
                    <option value="final" <?php echo $exam_type == 'final' ? 'selected' : ''; ?>>ফাইনাল</option>
                </select>
            </div>
            
            <?php if ($class_id && $session && $exam_type) : ?>
            <div class="form-group">
                <label for="student_search">শিক্ষার্থী অনুসন্ধান (নাম, রোল, আইডি):</label>
                <input type="text" name="student_search" id="student_search" value="<?php echo htmlspecialchars($student_search); ?>" placeholder="নাম, রোল বা আইডি দিয়ে অনুসন্ধান করুন" onchange="this.form.submit()">
            </div>
            
            <?php if ($show_student_list && !empty($students_in_class)) : ?>
            <h3>শিক্ষার্থী তালিকা</h3>
            <div class="student-list">
                <?php foreach ($students_in_class as $student) : ?>
                <div class="student-item">
                    <div>
                        <strong><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></strong>
                        (রোল: <?php echo $student['roll_number']; ?>, আইডি: <?php echo $student['student_id']; ?>)
                    </div>
                    <a href="?class_id=<?php echo $class_id; ?>&session=<?php echo $session; ?>&exam_type=<?php echo $exam_type; ?>&selected_students=<?php echo $student['id']; ?>" class="btn btn-print">মার্কশীট দেখুন</a>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div style="margin-top: 20px;">
                <a href="?class_id=<?php echo $class_id; ?>&session=<?php echo $session; ?>&exam_type=<?php echo $exam_type; ?>&bulk_print_all=1" class="btn btn-print">সকল শিক্ষার্থীর মার্কশীট প্রিন্ট করুন</a>
                <a href="?class_id=<?php echo $class_id; ?>&session=<?php echo $session; ?>&exam_type=<?php echo $exam_type; ?>&bulk_print_all=1&generate_pdf=1" class="btn btn-pdf">সকল শিক্ষার্থীর মার্কশীট PDF হিসেবে ডাউনলোড করুন</a>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($selected_students)) : 
                $selected_student_ids = explode(',', $selected_students);
            ?>
            <div class="selected-students">
                <h3>নির্বাচিত শিক্ষার্থী</h3>
                <p>মোট শিক্ষার্থী: <?php echo count($selected_student_ids); ?></p>
                <div style="margin-top: 10px;">
                    <a href="?class_id=<?php echo $class_id; ?>&session=<?php echo $session; ?>&exam_type=<?php echo $exam_type; ?>&selected_students=<?php echo $selected_students; ?>" class="btn btn-print">মার্কশীট দেখুন</a>
                    <a href="?class_id=<?php echo $class_id; ?>&session=<?php echo $session; ?>&exam_type=<?php echo $exam_type; ?>&selected_students=<?php echo $selected_students; ?>&generate_pdf=1" class="btn btn-pdf">PDF ডাউনলোড করুন</a>
                </div>
            </div>
            <?php endif; ?>
            
            <?php endif; ?>
            <?php endif; ?>
        </form>
        
        <?php if (($bulk_print_all || $separate_print || !empty($selected_students)) && !empty($all_students_data)) : ?>
        <div style="margin-top: 20px; text-align: center;">
            <a href="?class_id=<?php echo $class_id; ?>&session=<?php echo $session; ?>&exam_type=<?php echo $exam_type; ?>&bulk_print_all=1" class="btn btn-print">সকল শিক্ষার্থীর মার্কশীট প্রিন্ট করুন</a>
            <a href="?class_id=<?php echo $class_id; ?>&session=<?php echo $session; ?>&exam_type=<?php echo $exam_type; ?>&bulk_print_all=1&generate_pdf=1" class="btn btn-pdf">সকল শিক্ষার্থীর মার্কশীট PDF হিসেবে ডাউনলোড করুন</a>
        </div>
        
        <div id="marksheetContainer">
            <?php foreach ($all_students_data as $student_data) : 
                $student = $student_data['student'];
                $results = $student_data['results'];
                $gpa = $student_data['gpa'];
                $merit_position = $student_data['merit_position'] ?? null;
            ?> 
                <div class="marksheet" style="border: 2px solid #2c3e50; padding: 15px; margin: 15px auto; background: #fff; border-radius: 8px; max-width: 800px;">
                    <div style="text-align: center; border-bottom: 2px double #3498db; padding-bottom: 10px; margin-bottom: 15px;">
                        <h2 style="margin: 0; color: #2c3e50; font-size: 24px; text-transform: uppercase;"> <?php echo htmlspecialchars($site_name); ?></h2>
                        <p style="margin: 5px 0 0; color: #7f8c8d; font-size: 14px;"> <?php echo htmlspecialchars($site_address); ?></p>
                    </div>
                    
                    <h3 style="text-align: center; font-size: 18px; font-weight: bold; color: #2c3e50; margin: 15px 0; text-transform: uppercase; border: 1px solid #3498db; padding: 8px; border-radius: 5px; background: #e3f2fd;">
                        <?php echo htmlspecialchars($student['class_name'] . ' ' . $student['section'] . ' - ' . $exam_type . ' পরীক্ষা ' . $session); ?>
                    </h3>
                    
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 15px; padding: 10px; background: #f8f9fa; border-radius: 5px;">
                        <div style="margin-bottom: 5px;"><strong style="color: #2c3e50;">নাম:</strong> <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></div>
                        <div style="margin-bottom: 5px;"><strong style="color: #2c3e50;">রোল:</strong> <?php echo htmlspecialchars($student['roll_number']); ?></div>
                        <div style="margin-bottom: 5px;"><strong style="color: #2c3e50;">শিক্ষার্থী আইডি:</strong> <?php echo htmlspecialchars($student['student_id']); ?></div>
                        <div style="margin-bottom: 5px;"><strong style="color: #2c3e50;">গ্রুপ:</strong> <?php echo htmlspecialchars($student['group_name'] ?? 'N/A'); ?></div>
                        <div style="margin-bottom: 5px;"><strong style="color: #2c3e50;">GPA:</strong> <?php echo number_format($gpa, 2); ?></div>
                        <div style="margin-bottom: 5px;"><strong style="color: #2c3e50;">মেরিট পজিশন:</strong> <?php echo $merit_position ? $merit_position : 'N/A'; ?></div>
                    </div>
                    
                    <table style="width: 100%; border-collapse: collapse; margin: 15px 0; font-size: 11px;">
                        <thead>
                            <tr style="background: #3498db; color: white;">
                                <th style="border: 1px solid #bdc3c7; padding: 6px; text-align: center;">বিষয়</th>
                                <th style="border: 1px solid #bdc3c7; padding: 6px; text-align: center;">পূর্ণ নম্বর</th>
                                <th style="border: 1px solid #bdc3c7; padding: 6px; text-align: center;">প্রাপ্ত নম্বর</th>
                                <th style="border: 1px solid #bdc3c7; padding: 6px; text-align: center;">গ্রেড</th>
                                <th style="border: 1px solid #bdc3c7; padding: 6px; text-align: center;">জিপিএ</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($results as $result) : ?>
                            <tr>
                                <td style="border: 1px solid #bdc3c7; padding: 6px; text-align: left;"><?php echo htmlspecialchars($result['subject_name']); ?></td>
                                <td style="border: 1px solid #bdc3c7; padding: 6px; text-align: center;"><?php echo $result['full_marks']; ?></td>
                                <td style="border: 1px solid #bdc3c7; padding: 6px; text-align: center;">
                                    <?php 
                                    if ($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') {
                                        // For combined subjects, show average or total based on toggle
                                        if (($result['subject_name'] == 'বাংলা(একত্রে)' && $show_bangla_avg) || 
                                            ($result['subject_name'] == 'ইংরেজি(একত্রে)' && $show_english_avg)) {
                                            // Show 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']);
                                            echo number_format($avg_cq + $avg_mcq, 2);
                                        } else {
                                            // Show total: total_cq + total_mcq
                                            $total_cq = array_sum($result['cq_marks_array']);
                                            $total_mcq = array_sum($result['mcq_marks_array']);
                                            echo number_format($total_cq + $total_mcq, 2);
                                        }
                                    } else {
                                        echo $result['marks_obtained'];
                                    }
                                    ?>
                                </td>
                                <td style="border: 1px solid #bdc3c7; padding: 6px; text-align: center;"><?php echo $result['grade']; ?></td>
                                <td style="border: 1px solid #bdc3c7; padding: 6px; text-align: center;"><?php echo $result['grade_point']; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin: 15px 0; padding: 10px; background: #e8f4f8; border-radius: 5px;">
                        <div style="text-align: center;">
                            <div style="font-weight: bold; color: #2c3e50;">মোট নম্বর</div>
                            <div style="font-size: 16px; font-weight: bold; color: #e74c3c;"><?php echo $student_data['total_obtained']; ?></div>
                        </div>
                        <div style="text-align: center;">
                            <div style="font-weight: bold; color: #2c3e50;">পরীক্ষার্থী</div>
                            <div style="font-size: 16px; font-weight: bold; color: #e74c3c;"><?php echo $student_data['total_subjects']; ?></div>
                        </div>
                        <div style="text-align: center;">
                            <div style="font-weight: bold; color: #2c3e50;">পাশ</div>
                            <div style="font-size: 16px; font-weight: bold; color: #e74c3c;"><?php echo $student_data['passed_subjects']; ?></div>
                        </div>
                        <div style="text-align: center;">
                            <div style="font-weight: bold; color: #2c3e50;">জিপিএ</div>
                            <div style="font-size: 16px; font-weight: bold; color: #e74c3c;"><?php echo number_format($gpa, 2); ?></div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div style="margin-top: 20px; text-align: center;">
            <button class="btn btn-print" onclick="window.print()">প্রিন্ট করুন</button>
            <button class="btn btn-pdf" onclick="generatePDF()">পিডিএফ ডাউনলোড করুন</button>
        </div>
        
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
        
        <script>
            function generatePDF() {
                const { jsPDF } = window.jspdf;
                
                html2canvas(document.getElementById('marksheetContainer')).then(canvas => {
                    const imgData = canvas.toDataURL('image/png');
                    const pdf = new jsPDF('p', 'mm', 'a4');
                    const imgWidth = 210; // A4 width in mm
                    const pageHeight = 297; // A4 height in mm
                    const imgHeight = canvas.height * imgWidth / canvas.width;
                    
                    let heightLeft = imgHeight;
                    let position = 0;
                    
                    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                    heightLeft -= pageHeight;
                    
                    while (heightLeft >= 0) {
                        position = heightLeft - imgHeight;
                        pdf.addPage();
                        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
                        heightLeft -= pageHeight;
                    }
                    
                    pdf.save('merit_position_bulk_print_<?php echo $class_id . '_' . $session . '_' . $exam_type; ?>.pdf');
                });
            }
        </script>
        <?php endif; ?>
    </div>
</body>
</html>
<?php
}