<?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)
    $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 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) {
        return 0.00;
    }
    
    // Calculate GPA (Grade Point Average) with Jessore Board rules
    // For Jessore Board: when 4th subject exists, divide by (number of subjects - 1)
    // because 4th subject's extra points are added but the subject itself is not counted in division
    if ($fourth_subject_found) {
        // When 4th subject exists, divide by (gpa_subjects - 1)
        // because 4th subject is not counted in the division
        // Prevent division by zero when student has only one subject which is a fourth subject
        $divisor = ($gpa_subjects - 1) > 0 ? ($gpa_subjects - 1) : 1;
        $gpa = $total_grade_points / $divisor;
    } else {
        // Normal calculation
        $gpa = $total_grade_points / $gpa_subjects;
    }
    
    // Apply Jessore Board 4th subject rule: If 4th subject exists and GPA > 5.00, cap it at 5.00
    if ($fourth_subject_found && $gpa > 5.00) {
        $gpa = 5.00;
    }
    
    // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
    if ($gpa > 5.00) {
        $gpa = 5.00;
    }
    
    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'] ?? '';

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

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

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

if ($class_id && $session && $exam_type) {
    $show_student_list = true;
    
    // Get students based on class, session, and exam type
    $stmt = $pdo->prepare("
        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
        FROM students s 
        WHERE s.class_id = ? AND s.status = 'active'
        AND EXISTS (
            SELECT 1 FROM results r 
            WHERE r.student_id = s.id 
            AND r.session = ? 
            AND r.exam_type = ?
        )
        ORDER BY s.roll_number, s.first_name, s.last_name
    ");
    $stmt->execute([$class_id, $session, $exam_type]);
    $all_students_in_class = $stmt->fetchAll();
    
    // Filter students based on search term
    if (!empty($student_search)) {
        $students_in_class = array_filter($all_students_in_class, function($student) use ($student_search) {
            $search_term = strtolower($student_search);
            return strpos(strtolower($student['first_name']), $search_term) !== false ||
                   strpos(strtolower($student['last_name']), $search_term) !== false ||
                   strpos($student['roll_number'], $search_term) !== false ||
                   strpos($student['student_id'], $search_term) !== false;
        });
    } else {
        $students_in_class = $all_students_in_class;
    }
    
    // If specific students are selected, filter to only those students
    if (!empty($selected_students)) {
        $selected_student_ids = explode(',', $selected_students);
        $students_in_class = array_filter($students_in_class, function($student) use ($selected_student_ids) {
            return in_array($student['id'], $selected_student_ids);
        });
    }
    
    // If bulk printing all students, prepare data for all students
    if (($bulk_print_all || !empty($selected_students)) && !empty($students_in_class)) {
        foreach ($students_in_class as $student_item) {
            // Get student details
            $stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section FROM students s JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
            $stmt->execute([$student_item['id']]);
            $student_data = $stmt->fetch();
            
            // Also get the group name for display
            $group_stmt = $pdo->prepare("SELECT group_name FROM students WHERE id = ?");
            $group_stmt->execute([$student_item['id']]);
            $group_data = $group_stmt->fetch();
            if ($group_data && !empty($group_data['group_name'])) {
                $student_data['group_name'] = $group_data['group_name'];
            } else {
                $student_data['group_name'] = '';
            }
            
            if ($student_data) {
                // Get all subjects selected by the student from student_subjects table
                $stmt = $pdo->prepare("SELECT ss.subject_id, ss.is_fourth_subject, s.name as subject_name, s.code as subject_code FROM student_subjects ss JOIN subjects s ON ss.subject_id = s.id WHERE ss.student_id = ? AND s.status = 'active' ORDER BY s.name");
                $stmt->execute([$student_item['id']]);
                $all_student_subjects = $stmt->fetchAll();
                
                // Get results for the student - FIXED to avoid duplicates
                $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name, sub.code as subject_code FROM results r LEFT JOIN subjects sub ON r.subject_id = sub.id WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ? AND r.id IN (SELECT MAX(id) FROM results WHERE student_id = ? AND session = ? AND exam_type = ? GROUP BY subject_id) ORDER BY sub.name");
                $stmt->execute([$student_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 - TOTAL instead of average
                if (!empty($bangla_results)) {
                    // Combine Bangla and Bangla Grammar into one subject - TOTAL instead of average
                    $combined_bangla = combineBanglaSubjectsTotal($bangla_results);
                    $top_subjects[] = $combined_bangla;
                }
                
                // Process English subjects as a combined subject - TOTAL instead of average
                if (!empty($english_results)) {
                    // Combine English and English Grammar into one subject - TOTAL instead of average
                    $combined_english = combineEnglishSubjectsTotal($english_results);
                    $top_subjects[] = $combined_english;
                }
                
                // Sort Science/Math/ICT subjects by name to match subject list ordering
                usort($science_math_ict_subjects, function($a, $b) {
                    return strcmp($a['subject_name'], $b['subject_name']);
                });
                
                // Sort Economics subjects by name to match subject list ordering
                usort($economics_subjects, function($a, $b) {
                    return strcmp($a['subject_name'], $b['subject_name']);
                });
                
                // Apply custom layout only to middle subjects (excluding Science/Math/ICT and Economics)
                $ordered_middle_subjects = applyCustomLayout($middle_subjects);
                        
                // Combine all subjects in the required order
                // Order: Bangla/English (combined) -> Science/Math/ICT -> Other subjects (with custom layout) -> Economics -> Career Edu -> Agricultural Edu
                $combined_middle = array_merge($science_math_ict_subjects, $ordered_middle_subjects, $economics_subjects);
                        
                // Sort Career Education subjects by name to match subject list ordering
                usort($career_edu, function($a, $b) {
                    return strcmp($a['subject_name'], $b['subject_name']);
                });
                
                // Add Career Education if it exists
                if (!empty($career_edu)) {
                    $combined_middle = array_merge($combined_middle, $career_edu);
                }
                        
                // Sort Agricultural Education subjects by name to match subject list ordering
                usort($agri_edu, function($a, $b) {
                    return strcmp($a['subject_name'], $b['subject_name']);
                });
                
                // Add Agricultural Education at the very end if it exists
                if (!empty($agri_edu)) {
                    $combined_middle = array_merge($combined_middle, $agri_edu);
                }
                
                // Debug: Show counts
                        
                // Combine the top subjects with the rest of the subjects
                $results = array_merge($top_subjects, $combined_middle);
                
                // Move fourth subject to the end of the list
                $normal_subjects = [];
                $fourth_subjects = [];
                
                foreach ($results as $result) {
                    if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                        $fourth_subjects[] = $result;
                    } else {
                        $normal_subjects[] = $result;
                    }
                }
                
                // Combine subjects with fourth subject at the end
                $results = array_merge($normal_subjects, $fourth_subjects);
                
                // Ensure combined subjects have required fields
                foreach ($results as &$result) {
                    if ($result['subject_id'] == 'combined_bangla' || $result['subject_id'] == 'combined_english') {
                        // For combined subjects, try to get actual marks from subject_mark_distribution
                        // Use a generic subject ID to fetch the passing marks (we'll use the first Bangla/English subject ID)
                        $combined_subject_id = null;
                        if ($result['subject_id'] == 'combined_bangla' && !empty($original_bangla_results)) {
                            $combined_subject_id = $original_bangla_results[0]['subject_id'];
                        } else if ($result['subject_id'] == 'combined_english' && !empty($original_english_results)) {
                            $combined_subject_id = $original_english_results[0]['subject_id'];
                        }
                        
                        if ($combined_subject_id) {
                            $stmt = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                            $stmt->execute([$combined_subject_id, $student_data['class_id'], $session, $exam_type]);
                            $smd = $stmt->fetch();
                            
                            if ($smd) {
                                $result['full_marks'] = $smd['total_marks'];
                                $result['pass_marks'] = $smd['overall_pass_marks'];
                            } else {
                                // Fallback to defaults
                                if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                                    $result['full_marks'] = 100;
                                }
                                if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                                    $result['pass_marks'] = 40;
                                }
                            }
                        } else {
                            // Fallback to defaults
                            if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                                $result['full_marks'] = 100;
                            }
                            if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                                $result['pass_marks'] = 40;
                            }
                        }
                    }
                }
                
                // Enhance results with subject-specific marks distribution and GP
                foreach ($results as &$result) {
                    // Try to get subject-specific mark distribution
                    $stmt = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                    $stmt->execute([$result['subject_id'], $student_data['class_id'], $session, $exam_type]);
                    $smd = $stmt->fetch();
                    
                    if ($smd) {
                        $result['full_marks'] = $smd['total_marks'];
                        $result['pass_marks'] = $smd['overall_pass_marks'];
                    } else {
                        // Fallback to mark_distributions
                        $stmt = $pdo->prepare("SELECT total_marks, pass_marks as overall_pass_marks FROM mark_distributions WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                        $stmt->execute([$result['subject_id'], $student_data['class_id'], $session, $exam_type]);
                        $md = $stmt->fetch();
                        
                        if ($md) {
                            $result['full_marks'] = $md['total_marks'];
                            $result['pass_marks'] = $md['overall_pass_marks'];
                        } else {
                            // Default values
                            $result['full_marks'] = 100;
                            $result['pass_marks'] = 33; // Use 40 as default passing marks as requested
                        }
                    }
                    
                    // Add subject-based GP (Grade Point)
                    $result['grade_point'] = getGradePoint($result['grade']);
                    
                    // Get maximum obtained marks for this subject in the class
                    if ($result['subject_id'] == 'combined_bangla') {
                        // For combined Bangla, we need to find the maximum combined marks across all students in the class
                        // First, get all Bangla subject IDs
                        $bangla_ids = array_column($original_bangla_results, 'subject_id');
                        if (!empty($bangla_ids)) {
                            // Get all students in the class
                            $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                            $stmt->execute([$student_data['class_id']]);
                            $students = $stmt->fetchAll();
                                            
                            $max_combined_marks = 0;
                            foreach ($students as $student_row) {
                                $student_id_tmp = $student_row['id'];
                                                
                                // Get results for this student in all Bangla subjects - FIXED to avoid duplicates
                                $placeholders = str_repeat('?,', count($bangla_ids) - 1) . '?';
                                $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name FROM results r LEFT JOIN subjects sub ON r.subject_id = sub.id WHERE r.student_id = ? AND r.subject_id IN ($placeholders) AND r.session = ? AND r.exam_type = ? AND r.id IN (SELECT MAX(id) FROM results WHERE student_id = ? AND subject_id IN ($placeholders) AND session = ? AND exam_type = ? GROUP BY subject_id)");
                                $params = array_merge([$student_id_tmp], $bangla_ids, [$session, $exam_type], [$student_id_tmp], $bangla_ids, [$session, $exam_type]);
                                $stmt->execute($params);
                                $student_results = $stmt->fetchAll();
                                                
                                if (!empty($student_results)) {
                                    // Combine Bangla subjects for this student using the same logic as combineBanglaSubjectsTotal
                                    $combined_for_student = combineBanglaSubjectsTotal($student_results);
                                    if ($combined_for_student && $combined_for_student['marks_obtained'] > $max_combined_marks) {
                                        $max_combined_marks = $combined_for_student['marks_obtained'];
                                    }
                                }
                            }
                                            
                            $result['class_max_marks'] = $max_combined_marks;
                        } else {
                            $result['class_max_marks'] = 0;
                        }
                    } else if ($result['subject_id'] == 'combined_english') {
                        // For combined English, we need to find the maximum combined marks across all students in the class
                        // First, get all English subject IDs
                        $english_ids = array_column($original_english_results, 'subject_id');
                        if (!empty($english_ids)) {
                            // Get all students in the class
                            $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                            $stmt->execute([$student_data['class_id']]);
                            $students = $stmt->fetchAll();
                                            
                            $max_combined_marks = 0;
                            foreach ($students as $student_row) {
                                $student_id_tmp = $student_row['id'];
                                                
                                // Get results for this student in all English subjects - FIXED to avoid duplicates
                                $placeholders = str_repeat('?,', count($english_ids) - 1) . '?';
                                $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name FROM results r LEFT JOIN subjects sub ON r.subject_id = sub.id WHERE r.student_id = ? AND r.subject_id IN ($placeholders) AND r.session = ? AND r.exam_type = ? AND r.id IN (SELECT MAX(id) FROM results WHERE student_id = ? AND subject_id IN ($placeholders) AND session = ? AND exam_type = ? GROUP BY subject_id)");
                                $params = array_merge([$student_id_tmp], $english_ids, [$session, $exam_type], [$student_id_tmp], $english_ids, [$session, $exam_type]);
                                $stmt->execute($params);
                                $student_results = $stmt->fetchAll();
                                                
                                if (!empty($student_results)) {
                                    // Combine English subjects for this student using the same logic as combineEnglishSubjectsTotal
                                    $combined_for_student = combineEnglishSubjectsTotal($student_results);
                                    if ($combined_for_student && $combined_for_student['marks_obtained'] > $max_combined_marks) {
                                        $max_combined_marks = $combined_for_student['marks_obtained'];
                                    }
                                }
                            }
                                            
                            $result['class_max_marks'] = $max_combined_marks;
                        } else {
                            $result['class_max_marks'] = 0;
                        }
                    } else {
                        // For regular subjects
                        $stmt = $pdo->prepare("SELECT MAX(cq_marks + mcq_marks) as max_marks FROM results WHERE subject_id = ? AND session = ? AND exam_type = ? AND student_id IN (SELECT id FROM students WHERE class_id = ? AND status = 'active')");
                        $stmt->execute([$result['subject_id'], $session, $exam_type, $student_data['class_id']]);
                        $max_result = $stmt->fetch();
                        $result['class_max_marks'] = $max_result['max_marks'] ?? 0;
                    }
                    
                    // Check if this subject is a fourth subject
                    if ($result['subject_id'] == 'combined_bangla') {
                        // For combined Bangla, check if any of the original Bangla subjects is a fourth subject
                        $is_fourth_subject = false;
                        foreach ($original_bangla_results as $bangla_result) {
                            try {
                                $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                                $stmt->execute([$student_item['id'], $bangla_result['subject_id']]);
                                $subject_info = $stmt->fetch();
                                if ($subject_info && isset($subject_info['is_fourth_subject']) && $subject_info['is_fourth_subject']) {
                                    $is_fourth_subject = true;
                                    break;
                                }
                            } catch (Exception $e) {
                                // Column might not exist, ignore error
                                error_log("Error checking is_fourth_subject for Bangla: " . $e->getMessage());
                            }
                        }
                        $result['is_fourth_subject'] = $is_fourth_subject;
                    } else if ($result['subject_id'] == 'combined_english') {
                        // For combined English, check if any of the original English subjects is a fourth subject
                        $is_fourth_subject = false;
                        foreach ($original_english_results as $english_result) {
                            try {
                                $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                                $stmt->execute([$student_item['id'], $english_result['subject_id']]);
                                $subject_info = $stmt->fetch();
                                if ($subject_info && isset($subject_info['is_fourth_subject']) && $subject_info['is_fourth_subject']) {
                                    $is_fourth_subject = true;
                                    break;
                                }
                            } catch (Exception $e) {
                                // Column might not exist, ignore error
                                error_log("Error checking is_fourth_subject for English: " . $e->getMessage());
                            }
                        }
                        $result['is_fourth_subject'] = $is_fourth_subject;
                    } else {
                        // For regular subjects
                        try {
                            $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                            $stmt->execute([$student_item['id'], $result['subject_id']]);
                            $subject_info = $stmt->fetch();
                            
                            $result['is_fourth_subject'] = $subject_info && isset($subject_info['is_fourth_subject']) && $subject_info['is_fourth_subject'] ? true : false;
                        } catch (Exception $e) {
                            // Column might not exist, ignore error
                            error_log("Error checking is_fourth_subject for regular subject: " . $e->getMessage());
                            $result['is_fourth_subject'] = false;
                        }
                    }
                    
                    // Apply custom grading for combined Bangla and English subjects
                    if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                        // For combined Bangla: CQ total > 44 AND MCQ total > 18 to pass (instead of average)
                        $custom_grade = calculateBanglaGradeTotal($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 total > 64 to pass (instead of average)
                        $custom_grade = calculateEnglishGradeTotal($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) {
                    $total_marks += $result['full_marks'];
                    $total_obtained += $result['marks_obtained'];
                    
                    // 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
                    }
                }
                
                // 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
                ];
            }
        }
    }
}

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

function calculateOverallGrade($percentage, $passed_subjects, $total_subjects) {
    // If failed in any subject, overall grade is F
    if ($passed_subjects < $total_subjects) {
        return 'F';
    }
    
    if ($percentage >= 80) return 'A+';
    elseif ($percentage >= 70) return 'A';
    elseif ($percentage >= 60) return 'A-';
    elseif ($percentage >= 50) return 'B';
    elseif ($percentage >= 40) return 'C';
    elseif ($percentage >= 33) return 'D';
    else return 'F';
}

// New function to calculate grade based on GPA
function calculateGradeFromGPA($gpa) {
    if ($gpa >= 5.00) return 'A+';
    elseif ($gpa >= 4.00) return 'A';
    elseif ($gpa >= 3.50) return 'A-';
    elseif ($gpa >= 3.00) return 'B';
    elseif ($gpa >= 2.00) return 'C';
    elseif ($gpa >= 1.00) return 'D';
    else return 'F';
}

// Function to combine Bangla subjects with TOTAL instead of average
function combineBanglaSubjectsTotal($bangla_results) {
    if (empty($bangla_results)) return null;
    
    // If only one Bangla subject, return it as is but mark it as combined
    if (count($bangla_results) == 1) {
        $result = $bangla_results[0];
        $result['subject_name'] = 'বাংলা(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_bangla';
        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 totaling
    $considered_results = array_slice($bangla_results, 0, 2);

    // Sum up other marks from all Bangla subjects
    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);
    }
    
    // Sum CQ and MCQ based on first 2 papers (instead of averaging)
    $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
    }
    
    $combined['cq_marks'] = $cq_total;
    $combined['mcq_marks'] = $mcq_total;
    
    // Calculate obtained marks as sum of total CQ and MCQ
    $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
    
    return $combined;
}

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

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

// Custom function to calculate Bangla subject grade based on TOTAL criteria
// For Bangla: CQ total > 44 AND MCQ total > 18 to pass
function calculateBanglaGradeTotal($cq_marks_array, $mcq_marks, $total_marks, $pass_marks) {
    // Calculate total of CQ marks
    $cq_total = 0;
    foreach ($cq_marks_array as $cq_mark) {
        $cq_total += $cq_mark;
    }
    
    // For Bangla: CQ total > 44 AND MCQ total > 18 to pass
    if ($cq_total > 44 && $mcq_marks > 18) {
        // Calculate overall marks
        $overall_marks = $cq_total + $mcq_marks;
        
        // Calculate percentage based on total marks
        $percentage = ($overall_marks / $total_marks) * 100;
        
        if ($percentage >= 80) return 'A+';
        elseif ($percentage >= 70) return 'A';
        elseif ($percentage >= 60) return 'A-';
        elseif ($percentage >= 50) return 'B';
        elseif ($percentage >= 40) return 'C';
        elseif ($percentage >= 33) return 'D';
        else return 'F';
    } else {
        // If criteria not met, return F
        return 'F';
    }
}

// Custom function to calculate English subject grade based on TOTAL criteria
// For English: CQ total > 64 to pass
function calculateEnglishGradeTotal($cq_marks_array, $total_marks, $pass_marks) {
    // Calculate total of CQ marks
    $cq_total = 0;
    foreach ($cq_marks_array as $cq_mark) {
        $cq_total += $cq_mark;
    }
    
    // For English: CQ total > 64 to pass
    if ($cq_total > 64) {
        // Calculate overall marks (CQ total only for English as per requirements)
        $overall_marks = $cq_total;
        
        // 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 combine English subjects with TOTAL instead of average
function combineEnglishSubjectsTotal($english_results) {
    if (empty($english_results)) return null;
    
    // If only one English subject, return it as is but mark it as combined
    if (count($english_results) == 1) {
        $result = $english_results[0];
        $result['subject_name'] = 'ইংরেজি(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        $result['mcq_marks_array'] = [$result['mcq_marks']]; // Convert to array for display
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_english';
        return $result;
    }
    
    // For multiple English subjects, combine them
    $combined = [
        'subject_name' => 'ইংরেজি(একত্রে)',
        'subject_code' => 'CENG',
        'subject_id' => 'combined_english',
        'cq_marks' => 0,
        'cq_marks_array' => [], // Store individual CQ marks for processing
        'mcq_marks' => 0,
        'mcq_marks_array' => [], // Store individual MCQ marks for display
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];
    
    // Sum up the marks from all English subjects
    foreach ($english_results as $result) {
        $combined['cq_marks'] += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $combined['mcq_marks'] += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual MCQ marks
        $combined['practical_marks'] += $result['practical_marks'];
        $combined['assignment_marks'] += $result['assignment_marks'];
        $combined['attendance_marks'] += $result['attendance_marks'];
        $combined['marks_obtained'] += $result['marks_obtained'];
        $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }
    
    // For English: obtained marks = CQ total + MCQ total (as per user requirement)
    $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
    
    return $combined;
}