<?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: Total subjects for calculation = regular subjects only (excluding 4th subject)
    // Final GPA = (sum of regular subjects' points + 4th subject additional points) / regular subjects count
    if ($fourth_subject_found) {
        // When 4th subject exists, divide by number of regular subjects (gpa_subjects)
        // The 4th subject contributes bonus points but is not counted as an additional subject in the division
        $gpa = $total_grade_points / $gpa_subjects;
    } else {
        // Normal calculation - divide by number of regular subjects
        $gpa = $total_grade_points / $gpa_subjects;
    }
    
    // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
    if ($gpa > 5.00) {
        $gpa = 5.00;
    }
    
    return round($gpa, 2);
}

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

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

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

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

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

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

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

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

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

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

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

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

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


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

        foreach ($students_in_class as $student_item) {

            // Get student details
            $stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section FROM students s JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
            $stmt->execute([$student_item['id']]);
            $student_data = $stmt->fetch();
            
            // Also get the group name for display
            $group_stmt = $pdo->prepare("SELECT group_name FROM students WHERE id = ?");
            $group_stmt->execute([$student_item['id']]);
            $group_data = $group_stmt->fetch();
            if ($group_data && !empty($group_data['group_name'])) {
                $student_data['group_name'] = $group_data['group_name'];
            } else {
                $student_data['group_name'] = '';
            }
            
            if ($student_data) {
                // Get all subjects selected by the student from student_subjects table
                $stmt = $pdo->prepare("SELECT ss.subject_id, ss.is_fourth_subject, s.name as subject_name, s.code as subject_code FROM student_subjects ss JOIN subjects s ON ss.subject_id = s.id WHERE ss.student_id = ? AND s.status = 'active' ORDER BY s.name");
                $stmt->execute([$student_item['id']]);
                $all_student_subjects = $stmt->fetchAll();
                
                // Get results for the student - FIXED to avoid duplicates
                $stmt = $pdo->prepare("SELECT r.*, r.cq_marks, r.mcq_marks, 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])) {
                        $result = $results_map[$subject_id];
                        // Explicitly check student_subjects table to get correct is_fourth_subject value
                        $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                        $stmt->execute([$student_item['id'], $subject_id]);
                        $subject_info = $stmt->fetch();
                        $result['is_fourth_subject'] = $subject_info && isset($subject_info['is_fourth_subject']) ? $subject_info['is_fourth_subject'] : ($subject['is_fourth_subject'] ?? false);
                        $results[] = $result;
                    } 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' => getGradePoint('F'),
                            '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 - BUT WITHOUT COMBINING BANGLA/ENGLISH
                $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;
                
                // For this new marksheet, we'll keep Bangla and English subjects separate (not combined)
                $separate_subjects = [];
                
                // Add Bangla subjects separately (without combining)
                foreach ($bangla_results as $bangla_result) {
                    $separate_subjects[] = $bangla_result;
                }
                
                // Add English subjects separately (without combining)
                foreach ($english_results as $english_result) {
                    $separate_subjects[] = $english_result;
                }
                
                // 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 (separate) -> 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 separate Bangla/English subjects with the rest of the subjects
                $results = array_merge($separate_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 subjects have required fields
                foreach ($results as &$result) {
                    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
                        }
                    }
                    
                    // Apply custom grading for Bangla and English subjects
                    $effective_grade = $result['grade'];
                    $subject_name = $result['subject_name'] ?? '';
                    
                    if (stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'Bangla') !== false) {
                        // For Bangla: Check average of CQ marks + MCQ marks
                        $cq_marks_array = [$result['cq_marks']]; // Simplified - in real system, this would be an array of individual CQ marks
                        $effective_grade = calculateBanglaGrade($cq_marks_array, $result['mcq_marks'], $result['full_marks'], $result['pass_marks']);
                    } else if (stripos($subject_name, 'ইংরেজি') !== false || stripos($subject_name, 'English') !== false) {
                        // For English: Check CQ marks average
                        $cq_marks_array = [$result['cq_marks']]; // Simplified - in real system, this would be an array of individual CQ marks
                        $effective_grade = calculateEnglishGrade($cq_marks_array, $result['full_marks'], $result['pass_marks']);
                    }
                    
                    // Add subject-based GP (Grade Point) based on effective grade
                    $result['grade_point'] = getGradePoint($effective_grade);
                    
                    // Get maximum obtained marks for this subject in the class
                    $stmt = $pdo->prepare("SELECT MAX(marks_obtained) 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
                    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: " . $e->getMessage());
                        $result['is_fourth_subject'] = false;
                    }
                }
                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
                        // Total subjects for calculation = regular subjects only (excluding 4th subject)
                        // Final GPA = (sum of regular subjects' points + 4th subject additional points) / regular subjects count
                        if ($fourth_subject_found) {
                            // When fourth subject exists, divide by gpa_subjects (regular subjects count)
                            // The bonus points are already added to total_grade_points
                            if ($gpa_subjects > 0) {
                                $gpa = round($total_grade_points / $gpa_subjects, 2);
                            } else {
                                $gpa = 0.00;
                            }
                        } else {
                            // Normal calculation
                            $gpa = round($total_grade_points / $gpa_subjects, 2);
                        }
                    } else {
                        $gpa = 0.00; // GPA is 0.00 if all subjects are failed
                    }
                    
                    // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
                    if ($gpa > 5.00) {
                        $gpa = 5.00;
                    }
                }
                
                // Add student data to the array
                $all_students_data[] = [
                    'student' => $student_data,
                    'results' => $results,
                    'total_marks' => $total_marks,
                    'total_obtained' => $total_obtained,
                    'percentage' => $percentage,
                    'gpa' => $gpa,
                    'passed_subjects' => $passed_subjects,
                    'total_subjects' => $total_subjects
                ];
            }
        }
    }
}

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

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

if (!empty($all_students_data)) {
    // Calculate merit positions based on ALL students in the class who have results
    // This ensures that when specific students are selected, their merit position
    // is calculated against all students in the class, not just the selected ones
    
    // Get ALL students in the class with results for merit calculation
    $stmt = $pdo->prepare(
        "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
        FROM students s 
        WHERE s.class_id = ? AND s.status = 'active'
        AND EXISTS (
            SELECT 1 FROM results r 
            WHERE r.student_id = s.id 
            AND r.session = ? 
            AND r.exam_type = ?
        )
        ORDER BY s.roll_number, s.first_name, s.last_name
    ");
    $stmt->execute([$class_id, $session, $exam_type]);
    $all_class_students_with_results = $stmt->fetchAll();
    
    // Calculate merit data for ALL students in class
    $all_class_merit_data = [];
    foreach ($all_class_students_with_results as $student_item) {
        // Get student results for GPA and total marks calculation
        $stmt = $pdo->prepare(
            "SELECT r.*, sub.name as subject_name, sub.code as subject_code, ss.is_fourth_subject 
            FROM results r 
            LEFT JOIN subjects sub ON r.subject_id = sub.id 
            LEFT JOIN student_subjects ss ON r.subject_id = ss.subject_id AND r.student_id = ss.student_id 
            WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ? 
            AND r.id IN (
                SELECT MAX(id) 
                FROM results 
                WHERE student_id = ? AND session = ? AND exam_type = ? 
                GROUP BY subject_id
            ) 
            ORDER BY sub.name"
        );
        $stmt->execute([$student_item['id'], $session, $exam_type, $student_item['id'], $session, $exam_type]);
        $results = $stmt->fetchAll();

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

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

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

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

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

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

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

        // Calculate total obtained marks for this student
        $total_obtained = 0;
        $gpa = 0.00; // Initialize GPA for this student
        $has_valid_marks = false; // Flag to check if student has at least some valid marks

        // Calculate GPA using the existing calculateGPA function
        $gpa = calculateGPA($results);
        
        // Calculate total obtained marks and check for valid marks
        foreach ($results as $result) {
            $total_obtained += $result['marks_obtained'] ?? 0;
            if ($result['marks_obtained'] > 0 || $result['cq_marks'] > 0 || $result['mcq_marks'] > 0) {
                $has_valid_marks = true;
            }
        }
        
        $all_class_merit_data[$student_item['id']] = [
            'total_obtained' => $total_obtained,
            'gpa' => $gpa,
            'has_valid_marks' => $has_valid_marks
        ];
    }

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

if ($student_id && $session && $exam_type) {
    // Get student details
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, c.section 
        FROM students s 
        JOIN classes c ON s.class_id = c.id 
        WHERE s.id = ?
    ");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    if ($student) {
        // Get all subjects selected by the student from student_subjects table
        $stmt = $pdo->prepare("
            SELECT ss.subject_id, s.name as subject_name, s.code as subject_code
            FROM student_subjects ss
            JOIN subjects s ON ss.subject_id = s.id
            WHERE ss.student_id = ? AND s.status = 'active'
            ORDER BY s.name
        ");
        $stmt->execute([$student_id]);
        $all_student_subjects = $stmt->fetchAll();
        
        // Get results for the student - FIXED to avoid duplicates
        $stmt = $pdo->prepare(
            "SELECT r.*, r.cq_marks, r.mcq_marks, 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])) {
                $result = $results_map[$subject_id];
                // Explicitly check student_subjects table to get correct is_fourth_subject value
                $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                $stmt->execute([$student_id, $subject_id]);
                $subject_info = $stmt->fetch();
                $result['is_fourth_subject'] = $subject_info && isset($subject_info['is_fourth_subject']) ? $subject_info['is_fourth_subject'] : ($subject['is_fourth_subject'] ?? false);
                $results[] = $result;
            } 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' => getGradePoint('F'),
                    '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 - BUT WITHOUT COMBINING BANGLA/ENGLISH
        $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;
        
        // For this new marksheet, we'll keep Bangla and English subjects separate (not combined)
        $separate_subjects = [];
        
        // Add Bangla subjects separately (without combining)
        foreach ($bangla_results as $bangla_result) {
            $separate_subjects[] = $bangla_result;
        }
        
        // Add English subjects separately (without combining)
        foreach ($english_results as $english_result) {
            $separate_subjects[] = $english_result;
        }
        
        // 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 (separate) -> 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 separate Bangla/English subjects with the rest of the subjects
        $results = array_merge($separate_subjects, $combined_middle);
        
        // Ensure subjects have required fields
        foreach ($results as &$result) {
            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
                }
            }
            
            // Apply custom grading for Bangla and English subjects
            $effective_grade = $result['grade'];
            $subject_name = $result['subject_name'] ?? '';
            
            if (stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'Bangla') !== false) {
                // For Bangla: Check average of CQ marks + MCQ marks
                $cq_marks_array = [$result['cq_marks']]; // Simplified - in real system, this would be an array of individual CQ marks
                $effective_grade = calculateBanglaGrade($cq_marks_array, $result['mcq_marks'], $result['full_marks'], $result['pass_marks']);
            } else if (stripos($subject_name, 'ইংরেজি') !== false || stripos($subject_name, 'English') !== false) {
                // For English: Check CQ marks average
                $cq_marks_array = [$result['cq_marks']]; // Simplified - in real system, this would be an array of individual CQ marks
                $effective_grade = calculateEnglishGrade($cq_marks_array, $result['full_marks'], $result['pass_marks']);
            }
            
            // Add subject-based GP (Grade Point) based on effective grade
            $result['grade_point'] = getGradePoint($effective_grade);
            
            // Get maximum obtained marks for this subject in the class
            $stmt = $pdo->prepare("SELECT MAX(marks_obtained) 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
            $result['is_fourth_subject'] = $result['is_fourth_subject'] ?? false;
        }
        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
                // Total subjects for calculation = regular subjects only (excluding 4th subject)
                // Final GPA = (sum of regular subjects' points + 4th subject additional points) / regular subjects count
                if ($fourth_subject_found) {
                    // When fourth subject exists, divide by gpa_subjects (regular subjects count)
                    // The bonus points are already added to total_grade_points
                    if ($gpa_subjects > 0) {
                        $gpa = round($total_grade_points / $gpa_subjects, 2);
                    } else {
                        $gpa = 0.00;
                    }
                } else {
                    // Normal calculation
                    $gpa = round($total_grade_points / $gpa_subjects, 2);
                }
            } else {
                $gpa = 0.00; // GPA is 0.00 if all subjects are failed
            }
            
            // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
            if ($gpa > 5.00) {
                $gpa = 5.00;
            }
        }
        
        // Calculate merit position based on total marks (primary) and GPA (secondary)
        if ($student && $session && $exam_type) {
            // Get all students in the same class with their total marks and GPA for merit calculation
            $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
            $stmt->execute([$student['class_id']]);
            $all_student_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            // Calculate total marks and GPA for each student
            $student_data = [];
            foreach ($all_student_ids as $sid) {
                // Get student results - FIXED to avoid duplicates
                $stmt = $pdo->prepare("SELECT r.*, r.cq_marks, r.mcq_marks, sub.name as subject_name 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)");
                $stmt->execute([$sid, $session, $exam_type, $sid, $session, $exam_type]);
                $student_results = $stmt->fetchAll();
                
                // Enhance each result with the correct is_fourth_subject value
                foreach ($student_results as &$result_item) {
                    $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                    $stmt->execute([$sid, $result_item['subject_id']]);
                    $subject_info = $stmt->fetch();
                    $result_item['is_fourth_subject'] = $subject_info && isset($subject_info['is_fourth_subject']) ? $subject_info['is_fourth_subject'] : false;
                }
                unset($result_item); // Break the reference

                if (empty($student_results)) {
                    $student_data[$sid] = ['total_marks' => 0, 'gpa' => 0.00];
                    continue;
                }

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

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

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

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

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

                    $result['grade'] = $effective_grade;
                    $result['grade_point'] = getGradePoint($effective_grade);
                }
                unset($result); // Break the reference

                $total_marks = 0;
                $total_grade_points = 0;
                $gpa_subjects = 0;
                $student_failed = false;
                $fourth_subject_found = false;
                
                // Process each result to calculate total marks and GPA
                foreach ($student_results as $result) {
                    // Add to total marks
                    $total_marks += $result['marks_obtained'] ?? 0;
                    
                    // Get subject name for proper grading
                    $stmt = $pdo->prepare("SELECT name FROM subjects WHERE id = ?");
                    $stmt->execute([$result['subject_id']]);
                    $subject_data = $stmt->fetch();
                    $subject_name = $subject_data ? $subject_data['name'] : '';
                    
                    // Check if this subject is a fourth subject
                    $is_fourth_subject = $result['is_fourth_subject'] ?? false;
                    
                    // Apply custom grading for Bangla and English subjects
                    $subject_grade = $result['grade'];
                    if (stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'Bangla') !== false) {
                        // For Bangla: Check average of 2 CQ marks + MCQ marks
                        $cq_marks_array = [$result['cq_marks']]; // Simplified - in real system, this would be an array of individual CQ marks
                        $custom_grade = calculateBanglaGrade($cq_marks_array, $result['mcq_marks'], 100, 40); // Assuming 100 total marks and 40 pass marks
                        $subject_grade = $custom_grade;
                    } else if (stripos($subject_name, 'ইংরেজি') !== false || stripos($subject_name, 'English') !== false) {
                        // For English: Check CQ marks average
                        $cq_marks_array = [$result['cq_marks']]; // Simplified - in real system, this would be an array of individual CQ marks
                        $custom_grade = calculateEnglishGrade($cq_marks_array, 100, 40); // Assuming 100 total marks and 40 pass marks
                        $subject_grade = $custom_grade;
                    }
                    
                    if ($subject_grade == 'F') {
                        // Check if student failed in this subject and it's not a fourth subject
                        if (!$is_fourth_subject) {
                            $student_failed = true;
                        }
                    } else {
                        // Add grade point for GPA calculation (only for passed subjects)
                        if ($is_fourth_subject) {
                            $fourth_subject_found = true;
                            $fourth_subject_grade_point = getGradePoint($subject_grade);
                            // For 4th subject: add bonus points (grade_point - 2.00 if > 2.00, otherwise 0)
                            $bonus_points = ($fourth_subject_grade_point > 2.00) ? ($fourth_subject_grade_point - 2.00) : 0;
                            $total_grade_points += $bonus_points;
                            // Fourth subject does NOT count toward subject total for GPA calculation
                        } else {
                            // Regular subject - add full grade point
                            $total_grade_points += getGradePoint($subject_grade);
                            $gpa_subjects++; // Count regular subjects for GPA calculation
                        }
                    }
                }
                
                // Calculate final GPA for this student using the calculateGPA function
                if ($student_failed) {
                    $student_data[$sid] = ['total_marks' => $total_marks, 'gpa' => 0.00];
                } else {
                    // Use the calculateGPA function which correctly implements Jessore Board rules
                    $gpa = calculateGPA($student_results);
                    $student_data[$sid] = ['total_marks' => $total_marks, 'gpa' => $gpa];
                }
            }
            
            // 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;
        }
    }
}

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

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

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

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

function getGradePoint($grade) {
    switch ($grade) {
        case 'A+': return 5.00;
        case 'A': return 4.00;
        case 'A-': return 3.50;
        case 'B': return 3.00;
        case 'C': return 2.00;
        case 'D': return 1.00;
        case 'F': return 0.00;
        default: return 0.00;
    }
}

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

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

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

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>সকল বিষয়ের মার্কশীট (বিষয় একত্রীকরণ ছাড়া) - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            font-size: 12px; /* Reduced from default */
        }
        
        .marksheet {
            border: 2px solid #2c3e50;
            padding: 12px; /* Reduced from 20px for better A4 fit */
            margin: 10px auto; /* Reduced from 20px for better A4 fit */
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            border-radius: 8px; /* Reduced from 12px */
            max-width: 210mm; /* A4 width */
            width: calc(210mm - 20px); /* Account for padding */
            position: relative;
            overflow: hidden;
        }
        
        .school-header {
            text-align: center;
            border-bottom: 2px double #3498db;
            padding-bottom: 10px; /* Reduced from 15px */
            margin-bottom: 15px; /* Reduced from 20px */
            background: linear-gradient(to right, #ffffff, #e3f2fd, #ffffff);
            border-radius: 6px 6px 0 0; /* Reduced from 8px */
            margin-left: -15px; /* Reduced from -20px */
            margin-right: -15px; /* Reduced from -20px */
            padding-left: 15px; /* Reduced from 20px */
        }
        
        .school-logo {
            max-width: 60px; /* Reduced from 80px */
            max-height: 60px; /* Reduced from 80px */
            margin: 0 10px; /* Reduced from 15px */
        }
        
        .student-info {
            background: linear-gradient(to right, #f8f9fa, #e9ecef, #f8f9fa);
            padding: 8px; /* Reduced from 12px */
            border-radius: 5px; /* Reduced from 8px */
            margin-bottom: 12px; /* Reduced from 15px */
            border: 1px solid #dee2e6;
        }
        
        .subject-table {
            width: 100%;
            border-collapse: collapse;
            margin: 10px 0; /* Reduced from 15px */
            font-size: 11px; /* Reduced from 12px */
            border: 1px solid #2c3e50;
        }
        
        .subject-table th,
        .subject-table td {
            border: 1px solid #2c3e50;
            padding: 4px 6px; /* Reduced from 6px 8px */
            text-align: center;
        }
        
        .subject-table th {
            background: linear-gradient(to bottom, #3498db, #2980b9);
            color: white;
            font-weight: 600;
        }
        
        .subject-table .subject-name {
            text-align: left;
            min-width: 100px; /* Reduced from 120px */
        }
        
        .result-summary {
            background: linear-gradient(to right, #e8f5e8, #d4edda, #e8f5e8);
            padding: 8px; /* Reduced from 12px */
            border-radius: 5px; /* Reduced from 8px */
            margin-top: 12px; /* Reduced from 15px */
            border: 1px solid #c3e6cb;
        }
        
        .signature-section {
            margin-top: 20px;
        }
        
        .signature-box {
            width: 150px; /* Reduced from 200px */
            padding: 5px;
            border-top: 1px solid #000;
            font-size: 10px; /* Reduced from 12px */
        }
        
        .marks-toggle {
            margin-bottom: 10px;
            text-align: center;
        }
        
        .print-btn {
            position: fixed;
            top: 10px;
            right: 10px;
            z-index: 1000;
        }
        
        @media print {
            .print-btn {
                display: none;
            }
            
            .marksheet {
                border: 2px solid #2c3e50;
                box-shadow: none;
                margin: 0;
                padding: 8px; /* Reduced from 12px */
            }
            
            /* Ensure each marksheet is on a separate page */
            .marksheet {
                page-break-after: always;
            }
            
            /* Don't break the last marksheet */
            .marksheet:last-child {
                page-break-after: avoid;
            }
        }
        
        /* Additional responsive styles */
        @media (max-width: 768px) {
            .marksheet {
                margin: 5px;
                padding: 8px;
            }
            
            .subject-table {
                font-size: 10px; /* Further reduced for small screens */
            }
            
            .school-header {
                flex-direction: column;
            }
            
            .logo-section {
                order: 1;
                text-align: center;
                margin-bottom: 10px;
            }
            
            .text-center.flex-grow-1.mx-3 {
                order: 2;
                margin: 0 !important;
                padding: 10px 0;
            }
            
            .student-photo-section {
                order: 3;
                margin-top: 10px;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            .d-flex.align-items-center.justify-content-between {
                display: flex !important;
                flex-direction: column;
                align-items: center !important;
                text-align: center;
            }
            
            .student-info .row > div {
                text-align: center;
            }
        }
        
        @media (max-width: 480px) {
            .subject-table {
                font-size: 9px;
                display: block;
                overflow-x: auto;
                white-space: nowrap;
            }
            
            .marksheet {
                width: 100%;
                min-width: 300px;
            }
            
            .school-logo, .student-photo {
                max-width: 50px !important;
                max-height: 50px !important;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <button class="btn btn-primary print-btn" onclick="window.print()">
            <i class="fas fa-print"></i> প্রিন্ট করুন
        </button>
        
        <!-- Student list for bulk printing -->
        <?php if ($show_student_list && ($bulk_print_all || $separate_print || !empty($selected_students)) && !empty($students_in_class)): ?> 
            <?php foreach ($all_students_data as $student_data): ?>
                <div class="marksheet mb-4">
                    <?php $student = $student_data['student']; ?>
                    <?php $results = $student_data['results']; ?>
                    <?php $total_marks = $student_data['total_marks']; ?>
                    <?php $total_obtained = $student_data['total_obtained']; ?>
                    <?php $percentage = $student_data['percentage']; ?>
                    <?php $gpa = $student_data['gpa']; ?>
                    <?php $passed_subjects = $student_data['passed_subjects']; ?>
                    <?php $total_subjects = $student_data['total_subjects']; ?>
                    
                    <!-- School Header -->
                    <div class="school-header">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="logo-section">
                                <?php if ($logo_image): ?>
                                    <?php 
                                        // Try multiple possible paths for the logo
                                        $logo_paths = [
                                            "../uploads/logos/$logo_image",
                                            "uploads/logos/$logo_image",
                                            "../$logo_image",
                                            "$logo_image"
                                        ];
                                        $logo_found = false;
                                        foreach ($logo_paths as $path) {
                                            if (file_exists($path)) {
                                                $logo_src = $path;
                                                $logo_found = true;
                                                break;
                                            }
                                        }
                                    ?>
                                    <?php if ($logo_found): ?>
                                        <img src="<?= $logo_src ?>" alt="Logo" class="school-logo">
                                    <?php else: ?>
                                        <!-- Default logo placeholder if no logo is found -->
                                        <div class="default-logo-placeholder" style="width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa; border-radius: 50%; border: 2px solid #3498db;">
                                            <i class="fas fa-school" style="font-size: 24px; color: #3498db;"></i>
                                        </div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <!-- Default logo placeholder if no logo is set -->
                                    <div class="default-logo-placeholder" style="width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa; border-radius: 50%; border: 2px solid #3498db;">
                                        <i class="fas fa-school" style="font-size: 24px; color: #3498db;"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="text-center flex-grow-1 mx-3">
                                <h3 class="mb-1"><?= htmlspecialchars($site_name) ?></h3>
                                <p class="mb-1"><?= htmlspecialchars($site_address) ?></p>
                                <h5 class="mb-1">শিক্ষাক্রমের ফলাফল</h5>
                                <p class="mb-0">পরীক্ষার নাম: <?= htmlspecialchars(ucfirst($exam_type)) ?>, সেশন: <?= htmlspecialchars($session) ?></p>
                            </div>
                            <div class="student-photo-section" style="margin-right: 15px;">
                                <?php if (!empty($student['photo'])): ?>
                                    <?php 
                                        // Try multiple possible paths for the student photo
                                        $student_photo_paths = [
                                            "../uploads/students/" . $student['photo'],
                                            "uploads/students/" . $student['photo'],
                                            "../" . $student['photo'],
                                            $student['photo']
                                        ];
                                        $student_photo_found = false;
                                        foreach ($student_photo_paths as $path) {
                                            if (file_exists($path)) {
                                                $student_photo_src = $path;
                                                $student_photo_found = true;
                                                break;
                                            }
                                        }
                                    ?>
                                    <?php if ($student_photo_found): ?>
                                        <img src="<?= $student_photo_src ?>" alt="Student Photo" class="student-photo" style="width: 56px; height: 56px; border-radius: 50%; border: 2px solid #3498db; object-fit: contain; display: block; margin: auto;">
                                    <?php else: ?>
                                        <div class="no-photo" style="width: 60px; height: 60px; border-radius: 50%; border: 2px solid #3498db; background-color: #f8f9fa; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-user" style="font-size: 24px; color: #6c757d;"></i>
                                        </div>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <div class="no-photo" style="width: 60px; height: 60px; border-radius: 50%; border: 2px solid #3498db; background-color: #f8f9fa; display: flex; align-items: center; justify-content: center;">
                                        <i class="fas fa-user" style="font-size: 24px; color: #6c757d;"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Student Information -->
                    <div class="student-info">
                        <div class="row g-2">
                            <div class="col-md-3">
                                <strong>ছাত্র/ছাত্রীর নাম:</strong><br>
                                <?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?>
                            </div>
                            <div class="col-md-2">
                                <strong>রোল:</strong><br>
                                <?= htmlspecialchars($student['roll_number']) ?>
                            </div>
                            <div class="col-md-2">
                                <strong>শ্রেণি:</strong><br>
                                <?= htmlspecialchars($student['class_name']) ?>
                            </div>
                            <div class="col-md-2">
                                <strong>শাখা:</strong><br>
                                <?= htmlspecialchars($student['section']) ?>
                            </div>
                            <div class="col-md-3">
                                <strong>গ্রুপ:</strong><br>
                                <?= htmlspecialchars($student['group_name'] ?? '') ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Subject Results Table -->
                    <div class="table-responsive">
                        <table class="subject-table">
                            <thead>
                                <tr>
                                    <th>ক্রমিক নং</th>
                                    <th>বিষয়ের নাম</th>
                                    <th>পূর্ণ নম্বর</th>
                                    <th>প্রাপ্ত নম্বর</th>
                                    <th>গ্রেড</th>
                                    <th>জিপিএ</th>
                                    <th>ক্লাস টপার</th>
                                    <th>চতুর্থ বিষয়</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                    // Separate 4th subjects from main subjects
                                    $main_subjects = [];
                                    $fourth_subjects = [];
                                    
                                    foreach ($results as $result) {
                                        if ($result['is_fourth_subject']) {
                                            $fourth_subjects[] = $result;
                                        } else {
                                            $main_subjects[] = $result;
                                        }
                                    }
                                    
                                    // Display main subjects first
                                    foreach ($main_subjects as $index => $result): 
                                ?>
                                <tr>
                                    <td><?= $index + 1 ?></td>
                                    <td class="subject-name"><?= htmlspecialchars($result['subject_name']) ?></td>
                                    <td><?= $result['full_marks'] ?></td>
                                    <td><?php if ($result['practical_marks'] > 0) { if ($result['mcq_marks'] > 0) { echo round($result['cq_marks']) . ' + ' . round($result['mcq_marks']) . ' + ' . round($result['practical_marks']) . ' = ' . round($result['marks_obtained']); } else { echo round($result['cq_marks']) . ' + ' . round($result['practical_marks']) . ' = ' . round($result['marks_obtained']); } } else { if ($result['mcq_marks'] > 0) { echo round($result['cq_marks']) . ' + ' . round($result['mcq_marks']) . ' = ' . round($result['marks_obtained']); } else { echo round($result['cq_marks']) . ' = ' . round($result['marks_obtained']); } } ?></td>
                                    <td><?= $result['grade'] ?></td>
                                    <td><?= number_format($result['grade_point'], 2) ?></td>
                                    <td><?= $result['class_max_marks'] ?></td>
                                    <td><?= $result['is_fourth_subject'] ? 'হ্যাঁ' : 'না' ?></td>
                                </tr>
                                <?php endforeach; ?>
                                
                                <?php 
                                    // Display 4th subjects after main subjects
                                    $fourth_subject_start_index = count($main_subjects);
                                    foreach ($fourth_subjects as $index => $result): 
                                ?>
                                <tr style="background-color: #e8f4f8;">
                                    <td><?= $fourth_subject_start_index + $index + 1 ?></td>
                                    <td class="subject-name" style="font-weight: bold;"><?= htmlspecialchars($result['subject_name']) ?></td>
                                    <td><?= $result['full_marks'] ?></td>
                                    <td><?php if ($result['practical_marks'] > 0) { if ($result['mcq_marks'] > 0) { echo round($result['cq_marks']) . ' + ' . round($result['mcq_marks']) . ' + ' . round($result['practical_marks']) . ' = ' . round($result['marks_obtained']); } else { echo round($result['cq_marks']) . ' + ' . round($result['practical_marks']) . ' = ' . round($result['marks_obtained']); } } else { if ($result['mcq_marks'] > 0) { echo round($result['cq_marks']) . ' + ' . round($result['mcq_marks']) . ' = ' . round($result['marks_obtained']); } else { echo round($result['cq_marks']) . ' = ' . round($result['marks_obtained']); } } ?></td>
                                    <td><?= $result['grade'] ?></td>
                                    <td><?= number_format($result['grade_point'], 2) ?></td>
                                    <td><?= $result['class_max_marks'] ?></td>
                                    <td><?= $result['is_fourth_subject'] ? 'হ্যাঁ' : 'না' ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Result Summary -->
                    <div class="result-summary">
                        <div class="row g-2">
                            <div class="col-md-3">
                                <strong>মোট নম্বর:</strong><br>
                                <?= $total_obtained ?>/<?= $total_marks ?> (<?= $percentage ?>%)
                            </div>
                            <div class="col-md-2">
                                <strong>জিপিএ:</strong><br>
                                <?= number_format($gpa, 2) ?>
                            </div>
                            <div class="col-md-2">
                                <strong>গ্রেড:</strong><br>
                                <?= calculateGradeFromGPA($gpa) ?>
                            </div>
                            <div class="col-md-2">
                                <strong>পাশ:</strong><br>
                                <?= $passed_subjects ?>/<?= $total_subjects ?>
                            </div>
                            <div class="col-md-3">
                                <strong>মেধাক্রম:</strong><br>
                                <?php if (isset($student_data['merit_position'])): ?>
                                    <?= $student_data['merit_position'] ?>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- GPA Calculation Breakdown -->
                        <?php 
                            // Calculate main subjects GPA and additional points from 4th subject
                            $main_subjects_points = 0;
                            $main_subjects_count = 0;
                            $fourth_subject_points = 0;
                            $fourth_subject_bonus = 0;
                            
                            foreach ($results as $result) {
                                if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                                    // This is a 4th subject
                                    $fourth_subject_points = $result['grade_point'];
                                    // Calculate bonus points: if grade point > 2.00, bonus = grade_point - 2.00, else 0
                                    $fourth_subject_bonus = ($fourth_subject_points > 2.00) ? ($fourth_subject_points - 2.00) : 0;
                                } else {
                                    // This is a main subject
                                    $main_subjects_points += $result['grade_point'];
                                    $main_subjects_count++;
                                }
                            }
                            
                            // Calculate main subjects average if there are main subjects
                            $main_subjects_gpa = ($main_subjects_count > 0) ? ($main_subjects_points / $main_subjects_count) : 0;
                            // Final GPA = (main subjects average + 4th subject bonus) / number of main subjects for division
                            // Actually, final GPA is calculated differently according to the calculateGPA function
                            
                            // Recalculate according to the same logic as calculateGPA function
                            $total_grade_points = 0;
                            $gpa_subjects = 0;
                            $has_failed_in_non_fourth_subject = false;
                            $fourth_subject_grade_point = 0;
                            $fourth_subject_found = false;
                            
                            foreach ($results as $result) {
                                if (($result['grade'] ?? '') != 'F') {
                                    $grade_point = $result['grade_point'] ?? 0.00;
                                    
                                    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
                                        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;
                                    }
                                }
                            }
                            
                            $calculated_gpa = 0.00;
                            if (!$has_failed_in_non_fourth_subject && $gpa_subjects > 0) {
                                if ($fourth_subject_found) {
                                    $calculated_gpa = $total_grade_points / $gpa_subjects;
                                } else {
                                    $calculated_gpa = $total_grade_points / $gpa_subjects;
                                }
                                
                                if ($calculated_gpa > 5.00) {
                                    $calculated_gpa = 5.00;
                                }
                            }
                        ?>
                        <div class="row g-2 mt-2">
                            <div class="col-md-4">
                                <strong>মুল বিষয়ের জিপি:</strong><br>
                                <?php 
                                    $main_points = 0;
                                    foreach ($results as $result) {
                                        if (empty($result['is_fourth_subject']) || !($result['is_fourth_subject'] ?? false)) {
                                            $main_points += $result['grade_point'];
                                        }
                                    }
                                    echo number_format($main_points, 2);
                                ?>
                            </div>
                            <div class="col-md-4">
                                <strong>৪র্থ বিষয়ের অতিরিক্ত জিপি:</strong><br>
                                <?php 
                                    $fourth_bonus = 0;
                                    foreach ($results as $result) {
                                        if (!empty($result['is_fourth_subject']) && ($result['is_fourth_subject'] ?? false)) {
                                            $gp = $result['grade_point'];
                                            $bonus = ($gp > 2.00) ? ($gp - 2.00) : 0;
                                            $fourth_bonus += $bonus;
                                        }
                                    }
                                    echo number_format($fourth_bonus, 2);
                                ?>
                            </div>
                            <div class="col-md-4">
                                <strong>সর্বমোট জিপি:</strong><br>
                                <?php 
                                    $total_points = 0;
                                    $has_failed_main = false;
                                    
                                    foreach ($results as $result) {
                                        if (($result['grade'] ?? '') != 'F') {
                                            if (!empty($result['is_fourth_subject']) && ($result['is_fourth_subject'] ?? false)) {
                                                // 4th subject bonus points
                                                $gp = $result['grade_point'];
                                                $total_points += ($gp > 2.00) ? ($gp - 2.00) : 0;
                                            } else {
                                                // Main subject points
                                                $total_points += $result['grade_point'];
                                            }
                                        } else {
                                            if (empty($result['is_fourth_subject']) || !($result['is_fourth_subject'] ?? false)) {
                                                $has_failed_main = true;
                                            }
                                        }
                                    }
                                    
                                    if ($has_failed_main) {
                                        echo "0.00";
                                    } else {
                                        echo number_format($total_points, 2);
                                    }
                                ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Signature Section -->
                    <div class="signature-section">
                        <div class="d-flex justify-content-between">
                            <div class="signature-box text-start">প্রধান শিক্ষক</div>
                            <div class="signature-box text-center">শ্রেণি শিক্ষক</div>
                            <div class="signature-box text-end">অভিভাবক</div>
                        </div>
                    </div>
                </div>
                
                <?php if (!$bulk_print_all && !$separate_print): ?>
                    <!-- Add page break between students when not bulk printing -->
                    <div style="page-break-after: always;"></div>
                <?php endif; ?>
            <?php endforeach; ?>
        
        <!-- Individual student view -->
        <?php elseif ($student_id && $session && $exam_type): ?>
            <?php if ($student && !empty($results)): ?>
            <div class="marksheet">
                <!-- School Header -->
                <div class="school-header">
                    <div class="d-flex align-items-center justify-content-between">
                        <div class="logo-section">
                            <?php if ($logo_image): ?>
                                <?php 
                                    // Try multiple possible paths for the logo
                                    $logo_paths = [
                                        "../uploads/logos/$logo_image",
                                        "uploads/logos/$logo_image",
                                        "../$logo_image",
                                        "$logo_image"
                                    ];
                                    $logo_found = false;
                                    foreach ($logo_paths as $path) {
                                        if (file_exists($path)) {
                                            $logo_src = $path;
                                            $logo_found = true;
                                            break;
                                        }
                                    }
                                ?>
                                <?php if ($logo_found): ?>
                                    <img src="<?= $logo_src ?>" alt="Logo" class="school-logo">
                                <?php else: ?>
                                    <!-- Default logo placeholder if no logo is found -->
                                    <div class="default-logo-placeholder" style="width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa; border-radius: 50%; border: 2px solid #3498db;">
                                        <i class="fas fa-school" style="font-size: 24px; color: #3498db;"></i>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <!-- Default logo placeholder if no logo is set -->
                                <div class="default-logo-placeholder" style="width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa; border-radius: 50%; border: 2px solid #3498db;">
                                    <i class="fas fa-school" style="font-size: 24px; color: #3498db;"></i>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="text-center flex-grow-1 mx-3">
                            <h3 class="mb-1"><?= htmlspecialchars($site_name) ?></h3>
                            <p class="mb-1"><?= htmlspecialchars($site_address) ?></p>
                            <h5 class="mb-1">শিক্ষাক্রমের ফলাফল</h5>
                            <p class="mb-0">পরীক্ষার নাম: <?= htmlspecialchars(ucfirst($exam_type)) ?>, সেশন: <?= htmlspecialchars($session) ?></p>
                        </div>
                        <div class="student-photo-section" style="margin-right: 15px;">
                            <?php if (!empty($student['photo'])): ?>
                                <?php 
                                    // Try multiple possible paths for the student photo
                                    $student_photo_paths = [
                                        "../uploads/students/" . $student['photo'],
                                        "uploads/students/" . $student['photo'],
                                        "../" . $student['photo'],
                                        $student['photo']
                                    ];
                                    $student_photo_found = false;
                                    foreach ($student_photo_paths as $path) {
                                        if (file_exists($path)) {
                                            $student_photo_src = $path;
                                            $student_photo_found = true;
                                            break;
                                        }
                                    }
                                ?>
                                <?php if ($student_photo_found): ?>
                                    <img src="<?= $student_photo_src ?>" alt="Student Photo" class="student-photo" style="width: 56px; height: 56px; border-radius: 50%; border: 2px solid #3498db; object-fit: contain; display: block; margin: auto;">
                                <?php else: ?>
                                    <div class="no-photo" style="width: 60px; height: 60px; border-radius: 50%; border: 2px solid #3498db; background-color: #f8f9fa; display: flex; align-items: center; justify-content: center;">
                                        <i class="fas fa-user" style="font-size: 24px; color: #6c757d;"></i>
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <div class="no-photo" style="width: 60px; height: 60px; border-radius: 50%; border: 2px solid #3498db; background-color: #f8f9fa; display: flex; align-items: center; justify-content: center;">
                                    <i class="fas fa-user" style="font-size: 24px; color: #6c757d;"></i>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Student Information -->
                <div class="student-info">
                    <div class="row g-2">
                        <div class="col-md-3">
                            <strong>ছাত্র/ছাত্রীর নাম:</strong><br>
                            <?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?>
                        </div>
                        <div class="col-md-2">
                            <strong>রোল:</strong><br>
                            <?= htmlspecialchars($student['roll_number']) ?>
                        </div>
                        <div class="col-md-2">
                            <strong>শ্রেণি:</strong><br>
                            <?= htmlspecialchars($student['class_name']) ?>
                        </div>
                        <div class="col-md-2">
                            <strong>শাখা:</strong><br>
                            <?= htmlspecialchars($student['section']) ?>
                        </div>
                        <div class="col-md-3">
                            <strong>গ্রুপ:</strong><br>
                            <?= htmlspecialchars($student['group_name'] ?? '') ?>
                        </div>
                    </div>
                </div>
                
                <!-- Subject Results Table -->
                <div class="table-responsive">
                    <table class="subject-table">
                        <thead>
                            <tr>
                                <th>ক্রমিক নং</th>
                                <th>বিষয়ের নাম</th>
                                <th>পূর্ণ নম্বর</th>
                                <th>প্রাপ্ত নম্বর</th>
                                <th>গ্রেড</th>
                                <th>জিপিএ</th>
                                <th>ক্লাস টপার</th>
                                <th>চতুর্থ বিষয়</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                                // Separate 4th subjects from main subjects
                                $main_subjects = [];
                                $fourth_subjects = [];
                                
                                foreach ($results as $result) {
                                    if ($result['is_fourth_subject']) {
                                        $fourth_subjects[] = $result;
                                    } else {
                                        $main_subjects[] = $result;
                                    }
                                }
                                
                                // Display main subjects first
                                foreach ($main_subjects as $index => $result): 
                            ?>
                            <tr>
                                <td><?= $index + 1 ?></td>
                                <td class="subject-name"><?= htmlspecialchars($result['subject_name']) ?></td>
                                <td><?= $result['full_marks'] ?></td>
                                <td><?php if ($result['practical_marks'] > 0) { if ($result['mcq_marks'] > 0) { echo round($result['cq_marks']) . ' + ' . round($result['mcq_marks']) . ' + ' . round($result['practical_marks']) . ' = ' . round($result['marks_obtained']); } else { echo round($result['cq_marks']) . ' + ' . round($result['practical_marks']) . ' = ' . round($result['marks_obtained']); } } else { if ($result['mcq_marks'] > 0) { echo round($result['cq_marks']) . ' + ' . round($result['mcq_marks']) . ' = ' . round($result['marks_obtained']); } else { echo round($result['cq_marks']) . ' = ' . round($result['marks_obtained']); } } ?></td>
                                <td><?= $result['grade'] ?></td>
                                <td><?= number_format($result['grade_point'], 2) ?></td>
                                <td><?= $result['class_max_marks'] ?></td>
                                <td><?= $result['is_fourth_subject'] ? 'হ্যাঁ' : 'না' ?></td>
                            </tr>
                            <?php endforeach; ?>
                            
                            <?php 
                                // Display 4th subjects after main subjects
                                $fourth_subject_start_index = count($main_subjects);
                                foreach ($fourth_subjects as $index => $result): 
                            ?>
                            <tr style="background-color: #e8f4f8;">
                                <td><?= $fourth_subject_start_index + $index + 1 ?></td>
                                <td class="subject-name" style="font-weight: bold;">
                                    <?= htmlspecialchars($result['subject_name']) ?>
                                </td>
                                <td><?= $result['full_marks'] ?></td>
                                <td><?php if ($result['practical_marks'] > 0) { if ($result['mcq_marks'] > 0) { echo round($result['cq_marks']) . ' + ' . round($result['mcq_marks']) . ' + ' . round($result['practical_marks']) . ' = ' . round($result['marks_obtained']); } else { echo round($result['cq_marks']) . ' + ' . round($result['practical_marks']) . ' = ' . round($result['marks_obtained']); } } else { if ($result['mcq_marks'] > 0) { echo round($result['cq_marks']) . ' + ' . round($result['mcq_marks']) . ' = ' . round($result['marks_obtained']); } else { echo round($result['cq_marks']) . ' = ' . round($result['marks_obtained']); } } ?></td>
                                <td><?= $result['grade'] ?></td>
                                <td><?= number_format($result['grade_point'], 2) ?></td>
                                <td><?= $result['class_max_marks'] ?></td>
                                <td><?= $result['is_fourth_subject'] ? 'হ্যাঁ' : 'না' ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Result Summary -->
                <div class="result-summary">
                    <div class="row g-2">
                        <div class="col-md-3">
                            <strong>মোট নম্বর:</strong><br>
                            <?= $total_obtained ?>/<?= $total_marks ?> (<?= $percentage ?>%)
                        </div>
                        <div class="col-md-2">
                            <strong>জিপিএ:</strong><br>
                            <?= number_format($gpa, 2) ?>
                        </div>
                        <div class="col-md-2">
                            <strong>গ্রেড:</strong><br>
                            <?= calculateGradeFromGPA($gpa) ?>
                        </div>
                        <div class="col-md-2">
                            <strong>পাশ:</strong><br>
                            <?= $passed_subjects ?>/<?= $total_subjects ?>
                        </div>
                        <div class="col-md-3">
                            <strong>মেধাক্রম:</strong><br>
                            <?php if ($merit_position): ?>
                                <?= $merit_position ?>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- GPA Calculation Breakdown -->
                    <?php 
                        // Calculate main subjects GPA and additional points from 4th subject
                        $main_subjects_points = 0;
                        $main_subjects_count = 0;
                        $fourth_subject_points = 0;
                        $fourth_subject_bonus = 0;
                        
                        foreach ($results as $result) {
                            if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                                // This is a 4th subject
                                $fourth_subject_points = $result['grade_point'];
                                // Calculate bonus points: if grade point > 2.00, bonus = grade_point - 2.00, else 0
                                $fourth_subject_bonus = ($fourth_subject_points > 2.00) ? ($fourth_subject_points - 2.00) : 0;
                            } else {
                                // This is a main subject
                                $main_subjects_points += $result['grade_point'];
                                $main_subjects_count++;
                            }
                        }
                        
                        // Calculate main subjects average if there are main subjects
                        $main_subjects_gpa = ($main_subjects_count > 0) ? ($main_subjects_points / $main_subjects_count) : 0;
                        // Final GPA = (main subjects average + 4th subject bonus) / number of main subjects for division
                        // Actually, final GPA is calculated differently according to the calculateGPA function
                        
                        // Recalculate according to the same logic as calculateGPA function
                        $total_grade_points = 0;
                        $gpa_subjects = 0;
                        $has_failed_in_non_fourth_subject = false;
                        $fourth_subject_grade_point = 0;
                        $fourth_subject_found = false;
                        
                        foreach ($results as $result) {
                            if (($result['grade'] ?? '') != 'F') {
                                $grade_point = $result['grade_point'] ?? 0.00;
                                
                                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
                                    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;
                                }
                            }
                        }
                        
                        $calculated_gpa = 0.00;
                        if (!$has_failed_in_non_fourth_subject && $gpa_subjects > 0) {
                            if ($fourth_subject_found) {
                                $calculated_gpa = $total_grade_points / $gpa_subjects;
                            } else {
                                $calculated_gpa = $total_grade_points / $gpa_subjects;
                            }
                            
                            if ($calculated_gpa > 5.00) {
                                $calculated_gpa = 5.00;
                            }
                        }
                    ?>
                    <div class="row g-2 mt-2">
                        <div class="col-md-4">
                            <strong>মুল বিষয়ের জিপি:</strong><br>
                            <?php 
                                $main_points = 0;
                                foreach ($results as $result) {
                                    if (empty($result['is_fourth_subject']) || !($result['is_fourth_subject'] ?? false)) {
                                        $main_points += $result['grade_point'];
                                    }
                                }
                                echo number_format($main_points, 2);
                            ?>
                        </div>
                        <div class="col-md-4">
                            <strong>৪র্থ বিষয়ের অতিরিক্ত জিপি:</strong><br>
                            <?php 
                                $fourth_bonus = 0;
                                foreach ($results as $result) {
                                    if (!empty($result['is_fourth_subject']) && ($result['is_fourth_subject'] ?? false)) {
                                        $gp = $result['grade_point'];
                                        $bonus = ($gp > 2.00) ? ($gp - 2.00) : 0;
                                        $fourth_bonus += $bonus;
                                    }
                                }
                                echo number_format($fourth_bonus, 2);
                            ?>
                        </div>
                        <div class="col-md-4">
                            <strong>সর্বমোট জিপি:</strong><br>
                            <?php 
                                $total_points = 0;
                                $has_failed_main = false;
                                
                                foreach ($results as $result) {
                                    if (($result['grade'] ?? '') != 'F') {
                                        if (!empty($result['is_fourth_subject']) && ($result['is_fourth_subject'] ?? false)) {
                                            // 4th subject bonus points
                                            $gp = $result['grade_point'];
                                            $total_points += ($gp > 2.00) ? ($gp - 2.00) : 0;
                                        } else {
                                            // Main subject points
                                            $total_points += $result['grade_point'];
                                        }
                                    } else {
                                        if (empty($result['is_fourth_subject']) || !($result['is_fourth_subject'] ?? false)) {
                                            $has_failed_main = true;
                                        }
                                    }
                                }
                                
                                if ($has_failed_main) {
                                    echo "0.00";
                                } else {
                                    echo number_format($total_points, 2);
                                }
                            ?>
                        </div>
                    </div>
                </div>
                
                <!-- Signature Section -->
                <div class="signature-section">
                    <div class="d-flex justify-content-between">
                        <div class="signature-box text-start">পরীক্ষার্থীর</div>
                        <div class="signature-box text-center">শিক্ষকের</div>
                        <div class="signature-box text-end">অভিভাবকের</div>
                    </div>
                </div>
            </div>
            <?php else: ?>
                <!-- Error message when student exists but has no results -->
                <div class="container-fluid">
                    <div class="alert alert-warning text-center">
                        <h4>⚠️ ফলাফল পাওয়া যায়নি</h4>
                        <?php if (!$student): ?>
                            <p>ছাত্র আইডি <strong><?= htmlspecialchars($student_id) ?></strong> সাথে কোন ছাত্র খুঁজে পাওয়া যায়নি।</p>
                        <?php else: ?>
                            <p>ছাত্র <strong><?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?></strong> এর জন্য <strong><?= htmlspecialchars($session) ?></strong> সেশনের <strong><?= htmlspecialchars(ucfirst($exam_type)) ?></strong> পরীক্ষার কোন ফলাফল পাওয়া যায়নি।</p>
                        <?php endif; ?>
                        <p><a href="?class_id=<?= $class_id ?>&session=<?= $session ?>&exam_type=<?= $exam_type ?>" class="btn btn-primary">ছাত্র তালিকা দেখুন</a></p>
                    </div>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <!-- Search form for individual student view -->
            <div class="container-fluid">
                <h3 class="mb-4 text-center">সকল বিষয়ের মার্কশীট (বিষয় একত্রীকরণ ছাড়া)</h3>
                
                <form method="GET" class="mb-4">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label for="class_id" class="form-label">শ্রেণি</label>
                            <select name="class_id" id="class_id" class="form-select" required>
                                <option value="">শ্রেণি নির্বাচন করুন</option>
                                <?php foreach ($classes as $class): ?>
                                    <option value="<?= $class['id'] ?>" <?= $class_id == $class['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($class['name']) ?> (<?= htmlspecialchars($class['section']) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="session" class="form-label">সেশন</label>
                            <select name="session" id="session" class="form-select" required>
                                <option value="">সেশন নির্বাচন করুন</option>
                                <?php foreach ($sessions as $sess): ?>
                                    <option value="<?= $sess['session'] ?>" <?= $session == $sess['session'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($sess['session']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="exam_type" class="form-label">পরীক্ষার ধরন</label>
                            <select name="exam_type" id="exam_type" class="form-select" required>
                                <option value="">পরীক্ষার ধরন নির্বাচন করুন</option>
                                <?php foreach ($exam_types as $et): ?>
                                    <option value="<?= $et['exam_type'] ?>" <?= $exam_type == $et['exam_type'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars(ucfirst($et['exam_type'])) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="student_search" class="form-label">ছাত্র অনুসন্ধান (ঐচ্ছিক)</label>
                            <input type="text" name="student_search" id="student_search" class="form-control" value="<?= htmlspecialchars($student_search) ?>" placeholder="নাম বা রোল দিয়ে অনুসন্ধান করুন">
                        </div>
                    </div>
                    
                    <div class="row g-3 mt-1">
                        <div class="col-md-3">
                            <label for="student_id" class="form-label">ছাত্র নির্বাচন করুন (ঐচ্ছিক)</label>
                            <select name="student_id" id="student_id" class="form-select">
                                <option value="">ছাত্র নির্বাচন করুন</option>
                                <?php if (!empty($students_in_class)): ?>
                                    <?php foreach ($students_in_class as $std): ?>
                                        <option value="<?= $std['id'] ?>" <?= $student_id == $std['id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($std['first_name'] . ' ' . $std['last_name']) ?> (রোল: <?= $std['roll_number'] ?>)
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="col-md-9 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="fas fa-search"></i> খুঁজুন
                            </button>
                            <button type="submit" name="bulk_print_all" value="1" class="btn btn-success me-2">
                                <i class="fas fa-print"></i> সবার মার্কশীট প্রিন্ট করুন
                            </button>
                            <button type="submit" name="separate_print" value="1" class="btn btn-info me-2">
                                <i class="fas fa-list"></i> পৃথক মার্কশীট প্রিন্ট করুন
                            </button>
                            <?php if (!empty($selected_students)): ?>
                                <a href="?class_id=<?= $class_id ?>&session=<?= $session ?>&exam_type=<?= $exam_type ?>&selected_students=<?= $selected_students ?>&bulk_print_all=1" class="btn btn-warning me-2">
                                    <i class="fas fa-print"></i> নির্বাচিত ছাত্রদের প্রিন্ট করুন';
                                </a>
                                <a href="?class_id=<?= $class_id ?>&session=<?= $session ?>&exam_type=<?= $exam_type ?>&selected_students=<?= $selected_students ?>&separate_print=1" class="btn btn-info">
                                    <i class="fas fa-list"></i> নির্বাচিত ছাত্রদের পৃথক প্রিন্ট করুন';
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </form>
                
                <?php if ($show_student_list && !empty($students_in_class)): ?>
                    <div class="card">
                        <div class="card-header">
                            <h5>ছাত্র তালিকা
                                <small class="text-muted">(মোট: <?= count($students_in_class) ?> জন)</small>
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>ক্রমিক নং</th>
                                            <th>ছাত্র আইডি</th>
                                            <th>নাম</th>
                                            <th>রোল</th>
                                            <th>ক্রিয়াকলাপ</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($students_in_class as $index => $std): ?>
                                        <tr>
                                            <td><?= $index + 1 ?></td>
                                            <td><?= htmlspecialchars($std['student_id']) ?></td>
                                            <td><?= htmlspecialchars($std['first_name'] . ' ' . $std['last_name']) ?></td>
                                            <td><?= $std['roll_number'] ?></td>
                                            <td>
                                                <a href="?class_id=<?= $class_id ?>&session=<?= $session ?>&exam_type=<?= $exam_type ?>&student_id=<?= $std['id'] ?>" class="btn btn-sm btn-primary">দেখুন</a>
                                                <a href="?class_id=<?= $class_id ?>&session=<?= $session ?>&exam_type=<?= $exam_type ?>&student_id=<?= $std['id'] ?>&print=1" class="btn btn-sm btn-success">প্রিন্ট</a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // JavaScript for additional functionality if needed
        document.addEventListener('DOMContentLoaded', function() {
            // Add any additional JavaScript functionality here
        });
    </script>
</body>
</html>
