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

// Debug: Show session variables
error_log('Session vars: ' . print_r($_SESSION, true));

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

// 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'] ?? '';
$layout = $_GET['layout'] ?? null;
$branch_id = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : 0;
$group_name = trim($_GET['group_name'] ?? '');

// Get branches
ensure_school_branches_schema($pdo);
$branches = get_active_school_branches($pdo);

// Get groups
try { $groups = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status='active' ORDER BY group_name")->fetchAll(); } catch(Exception $e) { $groups = []; }

// Debug: Show GET parameters
error_log('GET params: ' . print_r($_GET, 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;
if ($class_id && $session && $exam_type) {
    $show_student_list = true;
    
    // Get students based on class, session, and exam type
    $sql = "
        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.branch_id, s.group_name
        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 = ?
        )
    ";
    $params = [$class_id, $session, $exam_type];
    if ($branch_id > 0) {
        $sql .= " AND s.branch_id = ?";
        $params[] = $branch_id;
    }
    if ($group_name !== '') {
        $sql .= " AND s.group_name = ?";
        $params[] = $group_name;
    }
    $sql .= " ORDER BY s.roll_number, s.first_name, s.last_name";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $all_students_in_class = $stmt->fetchAll();
    
    // Filter students based on search term
    if (!empty($student_search)) {
        $students_in_class = array_filter($all_students_in_class, function($student) use ($student_search) {
            $search_term = strtolower($student_search);
            return strpos(strtolower($student['first_name']), $search_term) !== false ||
                   strpos(strtolower($student['last_name']), $search_term) !== false ||
                   strpos($student['roll_number'], $search_term) !== false ||
                   strpos($student['student_id'], $search_term) !== false;
        });
    } else {
        $students_in_class = $all_students_in_class;
    }
}

if ($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) {
        // All subjects will be fetched with results in the main query
        
        // Get results for the student - FIXED to include all selected subjects
        $stmt = $pdo->prepare("
            SELECT
                COALESCE(r.id, NULL) as result_id,
                COALESCE(r.marks_obtained, 0) as marks_obtained,
                COALESCE(r.cq_marks, 0) as cq_marks,
                COALESCE(r.mcq_marks, 0) as mcq_marks,
                COALESCE(r.practical_marks, 0) as practical_marks,
                COALESCE(r.assignment_marks, 0) as assignment_marks,
                COALESCE(r.attendance_marks, 0) as attendance_marks,
                COALESCE(r.grade, 'F') as grade,
                COALESCE(r.remarks, '') as remarks,
                ss.subject_id,
                sub.name as subject_name,
                sub.code as subject_code,
                ss.is_fourth_subject
            FROM student_subjects ss
            LEFT JOIN subjects sub ON ss.subject_id = sub.id
            LEFT JOIN (
                SELECT *
                FROM results
                WHERE student_id = ? AND session = ? AND exam_type = ?
                AND id IN (
                    SELECT MAX(id)
                    FROM results
                    WHERE student_id = ? AND session = ? AND exam_type = ?
                    GROUP BY subject_id
                )
            ) r ON ss.student_id = r.student_id AND ss.subject_id = r.subject_id
            WHERE ss.student_id = ? AND sub.status = 'active'
            ORDER BY CASE WHEN ss.is_fourth_subject = 1 THEN 1 ELSE 0 END, sub.name
        ");
        $stmt->execute([$student_id, $session, $exam_type, $student_id, $session, $exam_type, $student_id]);
        $results_with_marks = $stmt->fetchAll();
        
        // Process results - all subjects are already included in the query
        $results = [];
        $has_missing_marks = false;

        foreach ($results_with_marks as $result) {
            // Add cq_marks_array for Bangla/English processing
            $result['cq_marks_array'] = !empty($result['cq_marks']) ? [$result['cq_marks']] : [];

            // Check if marks are missing (result_id is null)
            if (empty($result['result_id'])) {
                $has_missing_marks = true;

                // Try to get subject-specific mark distribution for subjects without marks
                if (empty($result['full_marks'])) {
                    $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;
                        }
                    }
                }
            }

            $results[] = $result;
        }
        
        // Group subjects according to specific ordering requirements
        $bangla_results = [];
        $english_results = [];

        $science_math_subjects = []; // Science and Math (go at the top)
        $middle_subjects = [];       // Other subjects except special cases
        $ict_economics_subjects = []; // ICT and Economics (go at the bottom)
        $career_edu = null;          // Career Education
        $agri_edu = null;            // 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 1st/2nd Paper or Bangla Grammar, but not History subjects)
            $is_bangla = false;
            if ((stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) &&
                stripos($result['subject_name'], 'History') === false &&
                stripos($result['subject_name'], 'Introduction') === false) {
                $is_bangla = true;
            }
            if ($is_bangla) {
                $bangla_results[] = $result;
            }
            // Check if this is an English subject (English 1st/2nd Paper or English Grammar)
            else if ((stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) &&
                     stripos($result['subject_name'], 'Literature') === false) {
                $english_results[] = $result;
            }
            // Check for Science and Math 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) {
                $science_math_subjects[] = $result;
            }
            // Check for ICT and Economics subjects (go at the bottom)
            else if (strpos($subject_name, 'ict') !== false || 
                     strpos($subject_name, 'economics') !== false || strpos($subject_name, 'অর্থনীতি') !== false) {
                $ict_economics_subjects[] = $result;
            }
            // Check for Career Education
            else if (strpos($subject_name, 'career') !== false || strpos($subject_name, 'ক্যারিয়ার') !== false) {
                $career_edu = $result;
            }
            // Check for Agricultural Education
            else if (strpos($subject_name, 'agricultural') !== false || strpos($subject_name, 'কৃষি') !== false) {
                $agri_edu = $result;
            }
            // All other subjects
            else {
                $middle_subjects[] = $result;
            }
        }


        // Store the original results for use in maximum marks calculation
        $original_bangla_results = $bangla_results;
        $original_english_results = $english_results;
        
        // Process Bangla subjects as a combined subject
        $combined_subjects = [];
        if (!empty($bangla_results)) {
            // Combine Bangla and Bangla Grammar into one subject
            $combined_bangla = combineBanglaSubjects($bangla_results);
            // Use localized name for combined Bangla
            $combined_bangla['subject_name'] = 'বাংলা(একত্রে)';
            $combined_subjects[] = $combined_bangla;
        }

        // Process English subjects as a combined subject
        if (!empty($english_results)) {
            // Combine English and English Grammar into one subject
            $combined_english = combineEnglishSubjects($english_results);
            // Use localized name for combined English
            $combined_english['subject_name'] = 'ইংরেজি(একত্রে)';
            $combined_subjects[] = $combined_english;
        }
        
        // Apply custom layout only to middle subjects (excluding Science/Math and ICT/Economics)
        $ordered_middle_subjects = applyCustomLayout($middle_subjects, $layout);
        
        // Combine all subjects in the required order
        // Order: Bangla/English (combined) -> Science/Math -> Other subjects (with custom layout) -> ICT/Economics -> Career Edu -> Agricultural Edu
        $combined_middle = array_merge($science_math_subjects, $ordered_middle_subjects, $ict_economics_subjects);
        
        // Add Career Education if it exists
        if ($career_edu !== null) {
            $combined_middle[] = $career_edu;
        }
        
        // Add Agricultural Education at the very end if it exists
        if ($agri_edu !== null) {
            $combined_middle[] = $agri_edu;
        }
        
        // Combine subjects in Jessore Board SSC order: Bangla/English (combined) -> Other subjects
        $results = array_merge($combined_subjects, $combined_middle);
        
        // Ensure combined subjects have required fields
        foreach ($results as &$result) {
            if ($result['subject_id'] == 'combined_bangla' || $result['subject_id'] == 'combined_english') {
                // For combined subjects, try to get actual marks from subject_mark_distribution
                // Use a generic subject ID to fetch the passing marks (we'll use the first Bangla/English subject ID)
                $combined_subject_id = null;
                if ($result['subject_id'] == 'combined_bangla' && !empty($original_bangla_results)) {
                    $combined_subject_id = $original_bangla_results[0]['subject_id'];
                } else if ($result['subject_id'] == 'combined_english' && !empty($original_english_results)) {
                    $combined_subject_id = $original_english_results[0]['subject_id'];
                }
                
                if ($combined_subject_id) {
                    $stmt = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                    $stmt->execute([$combined_subject_id, $student['class_id'], $session, $exam_type]);
                    $smd = $stmt->fetch();
                    
                    if ($smd) {
                        $result['full_marks'] = $smd['total_marks'];
                        $result['pass_marks'] = $smd['overall_pass_marks'];
                    } else {
                        // Fallback to defaults
                        if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                            $result['full_marks'] = 100;
                        }
                        if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                            $result['pass_marks'] = 40;
                        }
                    }
                } else {
                    // Fallback to defaults
                    if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                        $result['full_marks'] = 100;
                    }
                    if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                        $result['pass_marks'] = 40;
                    }
                }
            }
        }
        
        // Enhance results with subject-specific marks distribution and GP
        foreach ($results as &$result) {
            // Try to get subject-specific mark distribution
            $stmt = $pdo->prepare("
                SELECT total_marks, overall_pass_marks 
                FROM subject_mark_distribution 
                WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                LIMIT 1
            ");
            $stmt->execute([
                $result['subject_id'], 
                $student['class_id'], 
                $session, 
                $exam_type
            ]);
            $smd = $stmt->fetch();
            
            if ($smd) {
                $result['full_marks'] = $smd['total_marks'];
                $result['pass_marks'] = $smd['overall_pass_marks'];
            } else {
                // Fallback to mark_distributions
                $stmt = $pdo->prepare("
                    SELECT total_marks, pass_marks as overall_pass_marks 
                    FROM mark_distributions 
                    WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                    LIMIT 1
                ");
                $stmt->execute([
                    $result['subject_id'], 
                    $student['class_id'], 
                    $session, 
                    $exam_type
                ]);
                $md = $stmt->fetch();
                
                if ($md) {
                    $result['full_marks'] = $md['total_marks'];
                    $result['pass_marks'] = $md['overall_pass_marks'];
                } else {
                    // Default values
                    $result['full_marks'] = 100;
                    $result['pass_marks'] = 33; // Use 40 as default passing marks as requested
                }
            }
            
            // Add subject-based GP (Grade Point)
            $result['grade_point'] = getGradePoint($result['grade']);
            
            // Get maximum obtained marks for this subject in the class
            if ($result['subject_id'] == 'combined_bangla') {
                // For combined Bangla, we need to find the maximum combined marks across all students in the class
                // First, get ALL possible Bangla subject IDs for this class and session
                $stmt = $pdo->prepare("SELECT DISTINCT r.subject_id FROM results r 
                                      JOIN subjects s ON r.subject_id = s.id 
                                      WHERE s.name LIKE ? AND s.name NOT LIKE ? AND s.name NOT LIKE ? 
                                      AND r.session = ? AND r.exam_type = ? AND r.student_id IN (SELECT id FROM students WHERE class_id = ?)");
                $stmt->execute(['%বাংলা%', '%History%', '%Introduction%', $session, $exam_type, $student['class_id']]);
                $all_bangla_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
                
                if (!empty($all_bangla_subjects)) {
                    // Get all students in the class
                    $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                    $stmt->execute([$student['class_id']]);
                    $students = $stmt->fetchAll();
                                    
                    $max_combined_marks = 0;
                    foreach ($students as $student_row) {
                        $student_id_tmp = $student_row['id'];
                                        
                        // Get results for this student in all possible Bangla subjects (only latest per subject)
                        $placeholders = str_repeat('?,', count($all_bangla_subjects) - 1) . '?';
                        $stmt = $pdo->prepare("
                            SELECT r.*, sub.name as subject_name
                            FROM results r
                            LEFT JOIN subjects sub ON r.subject_id = sub.id
                            WHERE r.student_id = ? AND r.subject_id IN ($placeholders) AND r.session = ? AND r.exam_type = ?
                            AND r.id IN (
                                SELECT MAX(r2.id)
                                FROM results r2
                                WHERE r2.student_id = r.student_id AND r2.subject_id = r.subject_id AND r2.session = r.session AND r2.exam_type = r.exam_type
                            )
                        ");
                        $params = array_merge([$student_id_tmp], $all_bangla_subjects, [$session, $exam_type]);
                        $stmt->execute($params);
                        $student_results = $stmt->fetchAll();
                                        
                        if (!empty($student_results)) {
                            // Combine Bangla subjects for this student using the same logic as combineBanglaSubjects
                            $combined_for_student = combineBanglaSubjects($student_results);
                            if ($combined_for_student && $combined_for_student['marks_obtained'] > $max_combined_marks) {
                                $max_combined_marks = $combined_for_student['marks_obtained'];
                            }
                        }
                    }
                                    
                    $result['class_max_marks'] = $max_combined_marks;
                } else {
                    $result['class_max_marks'] = 0;
                }
            } else if ($result['subject_id'] == 'combined_english') {
                // For combined English, we need to find the maximum combined marks across all students in the class
                // First, get ALL possible English subject IDs for this class and session
                $stmt = $pdo->prepare("SELECT DISTINCT r.subject_id FROM results r 
                                      JOIN subjects s ON r.subject_id = s.id 
                                      WHERE s.name LIKE ? AND s.name NOT LIKE ? 
                                      AND r.session = ? AND r.exam_type = ? AND r.student_id IN (SELECT id FROM students WHERE class_id = ?)");
                $stmt->execute(['%ইংরেজি%', '%Literature%', $session, $exam_type, $student['class_id']]);
                $all_english_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
                
                if (!empty($all_english_subjects)) {
                    // Get all students in the class
                    $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                    $stmt->execute([$student['class_id']]);
                    $students = $stmt->fetchAll();
                                    
                    $max_combined_marks = 0;
                    foreach ($students as $student_row) {
                        $student_id_tmp = $student_row['id'];
                                        
                        // Get results for this student in all possible English subjects (only latest per subject)
                        $placeholders = str_repeat('?,', count($all_english_subjects) - 1) . '?';
                        $stmt = $pdo->prepare("
                            SELECT r.*, sub.name as subject_name
                            FROM results r
                            LEFT JOIN subjects sub ON r.subject_id = sub.id
                            WHERE r.student_id = ? AND r.subject_id IN ($placeholders) AND r.session = ? AND r.exam_type = ?
                            AND r.id IN (
                                SELECT MAX(r2.id)
                                FROM results r2
                                WHERE r2.student_id = r.student_id AND r2.subject_id = r.subject_id AND r2.session = r.session AND r2.exam_type = r.exam_type
                            )
                        ");
                        $params = array_merge([$student_id_tmp], $all_english_subjects, [$session, $exam_type]);
                        $stmt->execute($params);
                        $student_results = $stmt->fetchAll();
                                        
                        if (!empty($student_results)) {
                            // Combine English subjects for this student using the same logic as combineEnglishSubjects
                            $combined_for_student = combineEnglishSubjects($student_results);
                            if ($combined_for_student && $combined_for_student['marks_obtained'] > $max_combined_marks) {
                                $max_combined_marks = $combined_for_student['marks_obtained'];
                            }
                        }
                    }
                                    
                    $result['class_max_marks'] = $max_combined_marks;
                } else {
                    $result['class_max_marks'] = 0;
                }
            } else {
                // For regular subjects
                $stmt = $pdo->prepare("SELECT MAX(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
            if ($result['subject_id'] == 'combined_bangla') {
                // For combined Bangla, check if any of the original Bangla subjects is a fourth subject
                $is_fourth_subject = false;
                foreach ($original_bangla_results as $bangla_result) {
                    $stmt = $pdo->prepare("
                        SELECT is_fourth_subject 
                        FROM student_subjects 
                        WHERE student_id = ? AND subject_id = ?
                        LIMIT 1
                    ");
                    $stmt->execute([$student_id, $bangla_result['subject_id']]);
                    $subject_info = $stmt->fetch();
                    if ($subject_info && $subject_info['is_fourth_subject']) {
                        $is_fourth_subject = true;
                        break;
                    }
                }
                $result['is_fourth_subject'] = $is_fourth_subject;
            } else if ($result['subject_id'] == 'combined_english') {
                // For combined English, check if any of the original English subjects is a fourth subject
                $is_fourth_subject = false;
                foreach ($original_english_results as $english_result) {
                    $stmt = $pdo->prepare("
                        SELECT is_fourth_subject 
                        FROM student_subjects 
                        WHERE student_id = ? AND subject_id = ?
                        LIMIT 1
                    ");
                    $stmt->execute([$student_id, $english_result['subject_id']]);
                    $subject_info = $stmt->fetch();
                    if ($subject_info && $subject_info['is_fourth_subject']) {
                        $is_fourth_subject = true;
                        break;
                    }
                }
                $result['is_fourth_subject'] = $is_fourth_subject;
            } else {
                // For regular subjects
                $stmt = $pdo->prepare("
                    SELECT is_fourth_subject 
                    FROM student_subjects 
                    WHERE student_id = ? AND subject_id = ?
                    LIMIT 1
                ");
                $stmt->execute([$student_id, $result['subject_id']]);
                $subject_info = $stmt->fetch();
                
                $result['is_fourth_subject'] = $subject_info && $subject_info['is_fourth_subject'] ? true : false;
            }
            
            // Apply custom grading for combined Bangla and English subjects
            if ($result['subject_name'] == 'বাংলা(একত্রে)') {
                // Debug
                error_log("Found combined Bangla subject: " . $result['subject_name']);
                // For combined Bangla: CQ average > 22 AND MCQ average > 9 to pass
                $custom_grade = calculateBanglaGrade($result['cq_marks_array'], $result['mcq_marks'], $result['full_marks'], $result['pass_marks']);
                $result['grade'] = $custom_grade;
                $result['grade_point'] = getGradePoint($custom_grade);
                // Debug
                error_log("Combined Bangla: Subject=" . $result['subject_name'] . ", CQ=" . json_encode($result['cq_marks_array']) . ", MCQ=" . $result['mcq_marks'] . ", Grade=$custom_grade");
            } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
                // Debug
                error_log("Found combined English subject: " . $result['subject_name']);
                // For combined English: CQ average > 32 to pass
                $custom_grade = calculateEnglishGrade($result['cq_marks_array'], $result['full_marks'], $result['pass_marks']);
                $result['grade'] = $custom_grade;
                $result['grade_point'] = getGradePoint($custom_grade);
                // Debug
                error_log("Combined English: Subject=" . $result['subject_name'] . ", CQ=" . json_encode($result['cq_marks_array']) . ", Grade=$custom_grade");
            }
        }
        unset($result); // Break the reference with the last element
        
        // Calculate totals and GPA with Jessore Board 4th subject rules
        $total_marks = 0;
        $total_obtained = 0;
        $total_subjects = count($results);
        $passed_subjects = 0;
        $total_grade_points = 0;
        $gpa_subjects = 0; // Subjects used for GPA calculation (excluding failed subjects)
        $has_failed_in_non_fourth_subject = false; // Track if student failed in any non-fourth subject
        $fourth_subject_grade_point = 0; // Track 4th subject grade point for adjustment
        $fourth_subject_found = false; // Track if 4th subject exists


        // Check if combined subjects exist
        $has_combined_bangla = false;
        $has_combined_english = false;
        foreach ($results as $check_result) {
            if ($check_result['subject_name'] == 'বাংলা(একত্রে)') {
                $has_combined_bangla = true;
            }
            if ($check_result['subject_name'] == 'ইংরেজি(একত্রে)') {
                $has_combined_english = true;
            }
        }

        foreach ($results as $result) {
            // Skip individual Bangla subjects if combined Bangla exists
            if ($has_combined_bangla && (stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) &&
                stripos($result['subject_name'], 'History') === false && stripos($result['subject_name'], 'Introduction') === false &&
                $result['subject_name'] != 'বাংলা(একত্রে)') {
                continue; // Skip individual Bangla subjects
            }

            // Skip individual English subjects if combined English exists
            if ($has_combined_english && (stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) &&
                stripos($result['subject_name'], 'Literature') === false && $result['subject_name'] != 'ইংরেজি(একত্রে)') {
                continue; // Skip individual English subjects
            }

            $total_marks += $result['full_marks'];
            $total_obtained += $result['marks_obtained'];

            // Check if this is a fourth subject
            $is_fourth = isset($result['is_fourth_subject']) && $result['is_fourth_subject'];

            // Check if student failed in this subject and it's not a fourth subject
            // Exclude subjects with no actual results (marks_obtained = 0 or null) from GPA failure check
            if ($result['grade'] == 'F' && !$is_fourth && isset($result['marks_obtained']) && $result['marks_obtained'] > 0) {
                $has_failed_in_non_fourth_subject = true;
                error_log("DEBUG: Failed in non-fourth subject: " . $result['subject_name']);
            }
            
            if ($result['grade'] != 'F') {
                $passed_subjects++;
                
                // Handle 4th subject GPA adjustment according to Jessore Board rules
                if ($is_fourth) {
                    $fourth_subject_found = true;
                    $fourth_subject_grade_point = $result['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 ($result['grade_point'] > 2.00) {
                        $total_grade_points += ($result['grade_point'] - 2.00);
                    }
                } else {
                    // Regular subject - add full grade point
                    $total_grade_points += $result['grade_point'];
                }
                $gpa_subjects++; // Count subjects for GPA calculation (including 4th subjects)
            }
        }
        
        $percentage = $total_marks > 0 ? round(($total_obtained / $total_marks) * 100, 2) : 0;
        
        // Debug output - disabled for production
        if (false) { // Set to true to debug - Temporary for troubleshooting
            error_log("GPA Debug: total_grade_points=$total_grade_points, gpa_subjects=$gpa_subjects, fourth_subject_found=$fourth_subject_found, has_failed_in_non_fourth_subject=$has_failed_in_non_fourth_subject");
            error_log("GPA Debug Details: total_subjects=".count($results).", passed_subjects=$passed_subjects, total_marks=$total_marks, total_obtained=$total_obtained");
            foreach ($results as $idx => $result) {
                $is_fourth = isset($result['is_fourth_subject']) && $result['is_fourth_subject'];
                error_log("Subject $idx: " . $result['subject_name'] . " - Grade: " . $result['grade'] . " - Grade Point: " . $result['grade_point'] . " - Is Fourth: $is_fourth");
            }
        }
        
        // If student failed in any non-fourth subject, overall grade is F and GPA is 0
        if ($has_failed_in_non_fourth_subject) {
            $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) {
                // For Jessore Board: when 4th subject exists, divide by (number of subjects - 1)
                // because 4th subject's extra points are added but the subject itself is not counted in division
                if ($fourth_subject_found) {
                    // When 4th subject exists, divide by (gpa_subjects - 1)
                    // because 4th subject is not counted in the division
                    // Prevent division by zero when student has only one subject which is a fourth subject
                    $divisor = ($gpa_subjects - 1) > 0 ? ($gpa_subjects - 1) : 1;
                    $gpa = $total_grade_points / $divisor;
                } else {
                    // Normal calculation
                    $gpa = $total_grade_points / $gpa_subjects;
                }
                
                // Apply Jessore Board 4th subject rule: If 4th subject exists and GPA > 5.00, cap it at 5.00
                if ($fourth_subject_found && $gpa > 5.00) {
                    $gpa = 5.00;
                }
                
                // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
                if ($gpa > 5.00) {
                    $gpa = 5.00;
                }

                
                $gpa = round($gpa, 2);
                $final_gpa = $gpa; // Store the calculated GPA
            } else {
                $gpa = 0.00; // GPA is 0.00 if all subjects are failed
                $final_gpa = $gpa;
            }

        }
        
        // Calculate merit position based on GPA
        if ($student && $session && $exam_type) {
            // Get all students in the same class (and branch if filtered) with their GPA for merit calculation
            $m_sql = "SELECT id FROM students WHERE class_id = ? AND status = 'active'";
            $m_params = [$student['class_id']];
            if ($branch_id > 0) {
                $m_sql .= " AND branch_id = ?";
                $m_params[] = $branch_id;
            }
            $stmt = $pdo->prepare($m_sql);
            $stmt->execute($m_params);
            $all_student_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            // Calculate GPA for each student
            $student_gpas = [];
            foreach ($all_student_ids as $sid) {
                // Get student results - only latest result per subject
                $stmt = $pdo->prepare("
                    SELECT r.*, sub.name as subject_name
                    FROM results r
                    LEFT JOIN subjects sub ON r.subject_id = sub.id
                    WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
                    AND r.id IN (
                        SELECT MAX(id)
                        FROM results
                        WHERE student_id = ? AND session = ? AND exam_type = ?
                        GROUP BY subject_id
                    )
                ");
                $stmt->execute([$sid, $session, $exam_type, $sid, $session, $exam_type]);
                $student_results = $stmt->fetchAll();
                
                if (empty($student_results)) {
                    $student_gpas[$sid] = 0.00;
                    continue;
                }
                
                $total_grade_points = 0;
                $gpa_subjects = 0;
                $student_failed = false;
                $fourth_subject_found = false;
                
                // Process each result to calculate GPA
                foreach ($student_results as $result) {
                    // Get subject name for proper grading
                    $stmt = $pdo->prepare("SELECT name FROM subjects WHERE id = ?");
                    $stmt->execute([$result['subject_id']]);
                    $subject_data = $stmt->fetch();
                    $subject_name = $subject_data ? $subject_data['name'] : '';
                    
                    // Check if this subject is a fourth subject
                    $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                    $stmt->execute([$sid, $result['subject_id']]);
                    $subject_info = $stmt->fetch();
                    $is_fourth_subject = $subject_info && $subject_info['is_fourth_subject'] ? true : false;
                    
                    // Apply custom grading for Bangla and English subjects
                    $subject_grade = $result['grade'];
                    if (stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'Bangla') !== false) {
                        // For Bangla: Check 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 only the bonus points (grade_point - 2.00) if grade_point > 2.00
                            // Otherwise, add 0 bonus points
                            if ($fourth_subject_grade_point > 2.00) {
                                $total_grade_points += ($fourth_subject_grade_point - 2.00);
                            }
                        } else {
                            // Regular subject - add full grade point
                            $total_grade_points += getGradePoint($subject_grade);
                        }
                        $gpa_subjects++;
                    }
                }
                
                // Calculate final GPA for this student using the same logic as for current student
                $has_failed_in_non_fourth_subject = $student_failed;
                if (false) { // Debug
                    error_log("Merit GPA Debug for student $sid: total_grade_points=$total_grade_points, gpa_subjects=$gpa_subjects, fourth_subject_found=$fourth_subject_found, student_failed=$student_failed");
                }
                if ($has_failed_in_non_fourth_subject) {
                    $student_gpas[$sid] = 0.00;
                } else {
                    if ($gpa_subjects > 0) {
                        // For Jessore Board: when 4th subject exists, divide by (number of subjects - 1)
                        // because 4th subject's extra points are added but the subject itself is not counted in division
                        if ($fourth_subject_found) {
                            // When 4th subject exists, divide by (gpa_subjects - 1)
                            // because 4th subject is not counted in the division
                            // Prevent division by zero when student has only one subject which is a fourth subject
                            $divisor = ($gpa_subjects - 1) > 0 ? ($gpa_subjects - 1) : 1;
                            $student_gpa = $total_grade_points / $divisor;
                        } else {
                            // Normal calculation
                            $student_gpa = $total_grade_points / $gpa_subjects;
                        }
                        
                        // Apply Jessore Board 4th subject rule: If 4th subject exists and GPA > 5.00, cap it at 5.00
                        if ($fourth_subject_found && $student_gpa > 5.00) {
                            $student_gpa = 5.00;
                        }
                        
                        // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
                        if ($student_gpa > 5.00) {
                            $student_gpa = 5.00;
                        }
                        
                        $student_gpas[$sid] = round($student_gpa, 2);
                    } else {
                        $student_gpas[$sid] = 0.00;
                    }
                }
            }
            
            // Sort students by GPA in descending order (highest GPA first)
            arsort($student_gpas);
            
            // Create an array of student IDs ordered by merit position
            $merit_order = [];
            $position = 1;
            foreach ($student_gpas as $sid => $gpa) {
                $merit_order[$sid] = $position++;
            }
            
            // Get merit position for current student
            $merit_position = isset($merit_order[$student_id]) ? $merit_order[$student_id] : null;
        }
    }
}

// Function to combine Bangla subjects
function combineBanglaSubjects($bangla_results) {
    if (empty($bangla_results)) return null;
    
    // If only one Bangla subject, return it as is but mark it as combined
    if (count($bangla_results) == 1) {
        $result = $bangla_results[0];
        $result['subject_name'] = 'বাংলা(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_bangla';
        return $result;
    }
    
    // For multiple Bangla subjects, combine them
    $combined = [
        'subject_name' => 'বাংলা(একত্রে)',
        'subject_code' => 'CBAN',
        'subject_id' => 'combined_bangla',
        'cq_marks' => 0,
        'cq_marks_array' => [], // Store individual CQ marks for processing
        'mcq_marks' => 0,
        'mcq_marks_array' => [], // Store individual MCQ marks for display
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];
    
    // Consider only first 2 Bangla papers for CQ/MCQ averaging
    $considered_results = array_slice($bangla_results, 0, 2);

    // Sum up other marks from all Bangla subjects; don't include CQ/MCQ here
    foreach ($bangla_results as $result) {
        $combined['practical_marks'] += $result['practical_marks'];
        $combined['assignment_marks'] += $result['assignment_marks'];
        $combined['attendance_marks'] += $result['attendance_marks'];
        $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }
    
    // Average CQ and MCQ based on first 2 papers
    $cq_total = 0;
    $mcq_total = 0;
    foreach ($considered_results as $result) {
        $cq_total += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $mcq_total += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual MCQ marks
    }
    
    $count = count($considered_results);
    if ($count > 0) {
        $combined['cq_marks'] = $cq_total / $count;
        $combined['mcq_marks'] = $mcq_total / $count;
    }
    
    // For Jessore Board SSC: Calculate obtained marks as total sum from both subjects
    // CQ and MCQ are averaged for grading, but marks_obtained shows total sum
    // Keep the original calculation for CQ/MCQ averaging, but calculate marks_obtained differently
    $total_marks_sum = 0;
    foreach ($bangla_results as $result) {
        $total_marks_sum += $result['marks_obtained'];
    }
    $combined['marks_obtained'] = $total_marks_sum; // Total sum from both subjects

    // Average full and pass marks over total Bangla results
    $total_count = count($bangla_results);
    if ($total_count > 0) {
        $combined['full_marks'] = $combined['full_marks'] / $total_count;
        $combined['pass_marks'] = $combined['pass_marks'] / $total_count;
    }
    
    return $combined;
}

// Function to combine English subjects
function combineEnglishSubjects($english_results) {
    if (empty($english_results)) return null;
    
    // If only one English subject, return it as is but mark it as combined
    if (count($english_results) == 1) {
        $result = $english_results[0];
        $result['subject_name'] = 'ইংরেজি(একত্রে)';
        $result['cq_marks_array'] = [$result['cq_marks']]; // Convert to array for processing
        $result['mcq_marks_array'] = [$result['mcq_marks']]; // Convert to array for display
        // Ensure all required keys are set
        if (!isset($result['full_marks'])) $result['full_marks'] = 100;
        if (!isset($result['pass_marks'])) $result['pass_marks'] = 33;
        if (!isset($result['subject_id'])) $result['subject_id'] = 'combined_english';
        return $result;
    }
    
    // For multiple English subjects, combine them
    $combined = [
        'subject_name' => 'ইংরেজি(একত্রে)',
        'subject_code' => 'CENG',
        'subject_id' => 'combined_english',
        'cq_marks' => 0,
        'cq_marks_array' => [], // Store individual CQ marks for processing
        'mcq_marks' => 0,
        'mcq_marks_array' => [], // Store individual MCQ marks for display
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'grade' => 'F',
        'grade_point' => 0.00
    ];
    
    // Sum up the marks from all English subjects
    foreach ($english_results as $result) {
        $combined['cq_marks'] += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $combined['mcq_marks'] += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual MCQ marks
        $combined['practical_marks'] += $result['practical_marks'];
        $combined['assignment_marks'] += $result['assignment_marks'];
        $combined['attendance_marks'] += $result['attendance_marks'];
        $combined['marks_obtained'] += $result['marks_obtained'];
        $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }
    
    // For Jessore Board SSC: Show total sum of marks_obtained from both English subjects
    // CQ and MCQ are averaged for grading, but marks_obtained shows total sum
    $count = count($english_results);
    if ($count > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $count; // Average for grading
        $combined['mcq_marks'] = $combined['mcq_marks'] / $count; // Average for grading
        // marks_obtained remains as total sum (not averaged)
        $combined['full_marks'] = $combined['full_marks'] / $count;
        $combined['pass_marks'] = $combined['pass_marks'] / $count;
    }
    
    return $combined;
}

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

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

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

// 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 CQ marks
    $cq_average = 0;
    if (!empty($cq_marks_array)) {
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);
    }

    // For Bangla: CQ average > 22 AND MCQ > 9 to pass
    // Note: $mcq_marks is already the average from combineBanglaSubjects
    if ($cq_average > 22 && $mcq_marks > 9) {
        // Calculate overall marks (CQ average + MCQ average)
        $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 CQ marks
    $cq_average = 0;
    if (!empty($cq_marks_array)) {
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);
    }

    // For English: CQ average > 32 to pass
    if ($cq_average > 32) {
        // Calculate overall marks (CQ average only for English as per requirements)
        $overall_marks = $cq_average;

        // Calculate percentage based on total marks
        $percentage = ($overall_marks / $total_marks) * 100;
        
        if ($percentage >= 80) return 'A+';
        elseif ($percentage >= 70) return 'A';
        elseif ($percentage >= 60) return 'A-';
        elseif ($percentage >= 50) return 'B';
        elseif ($percentage >= 40) return 'C';
        elseif ($percentage >= 33) return 'D';
        else return 'F';
    } else {
        // If criteria not met, return F
        return 'F';
    }
}

// Function to 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])) {
        // Debug: Show what layout is being applied
        error_log("Applying layout: $layout_source$actual_layout_name");
        error_log("Session data: " . print_r($_SESSION[$layout_source . $actual_layout_name], true));
        
        $saved_order = explode(',', $_SESSION[$layout_source . $actual_layout_name]);
        
        // Debug: Show the saved order
        error_log("Saved order: " . print_r($saved_order, true));
        error_log("Results count: " . count($results));
        $ordered_results = [];
        
        // First add subjects in the saved order
        // Debug: Show subject IDs in results
        $result_subject_ids = [];
        foreach ($results as $result) {
            if (isset($result['subject_id'])) {
                $result_subject_ids[] = (string)$result['subject_id'];
            }
        }
        error_log("Result subject IDs: " . print_r($result_subject_ids, true));
        
        foreach ($saved_order as $subject_id) {
            // Convert to string for consistent comparison
            $subject_id_str = (string)$subject_id;
            $matched = false;
            foreach ($results as $result) {
                if (isset($result['subject_id']) && (string)$result['subject_id'] === $subject_id_str) {
                    $ordered_results[] = $result;
                    $matched = true;
                    break;
                }
            }
            if (!$matched) {
                error_log("No match found for subject ID: $subject_id_str");
            }
        }
        
        // Then add any remaining subjects not in the saved order
        $added_count = count($ordered_results);
        foreach ($results as $result) {
            $found = false;
            foreach ($saved_order as $subject_id) {
                // Convert to string for consistent comparison
                $subject_id_str = (string)$subject_id;
                if (isset($result['subject_id']) && (string)$result['subject_id'] === $subject_id_str) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $ordered_results[] = $result;
            }
        }
        error_log("Added " . (count($ordered_results) - $added_count) . " remaining subjects");
        
        error_log("Final ordered results count: " . count($ordered_results));
        return $ordered_results;
    }
    
    // Return results sorted by subject name if no layout to apply (matches subject list default ordering)
    error_log("No layout applied, returning results sorted by subject name");
    usort($results, function($a, $b) {
        return strcmp($a['subject_name'], $b['subject_name']);
    });
    return $results;
}

// Get available sessions (from academic_sessions table, plus from results for fallback)
try {
    $sessions = $pdo->query("SELECT session_name AS session FROM academic_sessions WHERE status='active' ORDER BY session_name DESC")->fetchAll();
} catch(Exception $e) { $sessions = []; }
if (empty($sessions)) {
    try { $sessions = $pdo->query("SELECT DISTINCT session FROM results ORDER BY session DESC")->fetchAll(); } catch(Exception $e) { $sessions = []; }
}

// Get available exam types
try { $exam_types = $pdo->query("SELECT DISTINCT exam_type FROM results ORDER BY exam_type")->fetchAll(); } catch(Exception $e) { $exam_types = []; }
// Fallback: hardcoded common exam types if results table is empty
if (empty($exam_types)) {
    $exam_types = [
        ['exam_type' => 'midterm'],
        ['exam_type' => 'final'],
        ['exam_type' => 'test'],
        ['exam_type' => 'assignment'],
    ];
}
?>

<!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: 15px; /* Reduced from 20px */
            margin: 15px auto; /* Reduced from 20px */
            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: 800px; /* Reduced from 900px */
            position: relative;
            overflow: hidden;
        }
        
        .school-header {
            text-align: center;
            border-bottom: 2px double #3498db;
            padding-bottom: 10px; /* Reduced from 15px */
            margin-bottom: 15px; /* Reduced from 20px */
            background: linear-gradient(to right, #ffffff, #e3f2fd, #ffffff);
            border-radius: 6px 6px 0 0; /* Reduced from 8px */
            margin-left: -15px; /* Reduced from -20px */
            margin-right: -15px; /* Reduced from -20px */
            padding-left: 15px; /* Reduced from 20px */
            padding-right: 15px; /* Reduced from 20px */
            position: relative;
        }
        
        .school-logo {
            width: 60px; /* Reduced from 80px */
            height: 60px; /* Reduced from 80px */
            border: 2px solid #3498db; /* Reduced from 3px */
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 8px; /* Reduced from 12px */
            background: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* Reduced from 0 4px 8px */
            overflow: hidden;
        }
        
        .school-header h3 {
            color: #2c3e50;
            font-weight: 700;
            margin: 8px 0 3px 0; /* Reduced from 10px 0 5px 0 */
            text-shadow: 1px 1px 1px rgba(0,0,0,0.1); /* Reduced from 2px */
            font-size: 20px; /* Reduced from 24px */
        }
        
        .school-header h4 {
            color: #e74c3c;
            font-weight: 600;
            margin: 10px 0 0 0; /* Reduced from 15px */
            text-decoration: underline;
            text-underline-offset: 5px; /* Reduced from 8px */
            font-size: 16px; /* Reduced from 18px */
        }
        
        .student-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px; /* Reduced from 15px */
            margin-bottom: 15px; /* Reduced from 20px */
            background: #f8f9fa;
            padding: 12px; /* Reduced from 15px */
            border-radius: 6px; /* Reduced from 8px */
            border: 1px solid #e9ecef;
        }
        
        .info-row {
            display: flex;
            margin-bottom: 5px; /* Reduced from 8px */
            align-items: center;
        }
        
        .info-label {
            font-weight: 600;
            min-width: 100px; /* Reduced from 120px */
            color: #2c3e50;
            font-size: 12px; /* Reduced from 14px */
        }
        
        .info-value {
            border-bottom: 1px dotted #3498db; /* Reduced from 2px */
            flex: 1;
            padding-left: 8px; /* Reduced from 10px */
            font-weight: 500;
            color: #34495e;
            font-size: 12px; /* Reduced from 14px */
        }
        
        .marks-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0; /* Reduced from 20px */
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05); /* Reduced from 0 2px 10px */
            border-radius: 6px; /* Reduced from 8px */
            overflow: hidden;
            font-size: 11px; /* Reduced from default */
        }
        
        .marks-table th,
        .marks-table td {
            border: 1px solid #dee2e6;
            padding: 6px; /* Reduced from 8px */
            text-align: center;
            font-size: 11px; /* Reduced from 14px */
        }
        
        .marks-table th {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px; /* Reduced from 0.5px */
        }
        
        .marks-table tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .marks-table tbody tr:hover {
            background-color: #e3f2fd;
            transition: background-color 0.2s; /* Reduced from 0.3s */
        }
        
        .result-summary {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px; /* Reduced from 25px */
            margin-top: 15px; /* Reduced from 20px */
            padding-top: 15px; /* Reduced from 20px */
            border-top: 1px dashed #3498db; /* Reduced from 2px */
            background: #f8f9fa;
            padding: 12px; /* Reduced from 15px */
            border-radius: 6px; /* Reduced from 8px */
        }
        
        .signature-section {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px; /* Reduced from 25px */
            margin-top: 20px; /* Reduced from 30px */
            text-align: center;
        }
        
        .signature-box {
            border-top: 1px solid #3498db; /* Reduced from 2px */
            padding-top: 8px; /* Reduced from 10px */
            margin-top: 20px; /* Reduced from 30px */
            font-weight: 600;
            color: #2c3e50;
            font-size: 12px; /* Reduced from 14px */
        }
        
        .grade-scale {
            font-size: 9px; /* Reduced from 12px */
            margin-top: 20px; /* Reduced from 25px */
            padding: 10px; /* Reduced from 15px */
            background: #e3f2fd;
            border-radius: 6px; /* Reduced from 8px */
            border-left: 2px solid #3498db; /* Reduced from 4px */
        }
        
        .grade-scale strong {
            color: #2c3e50;
        }
        
        .student-list-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0; /* Reduced from 20px */
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05); /* Reduced from 0 2px 10px */
            border-radius: 6px; /* Reduced from 8px */
            overflow: hidden;
            font-size: 12px; /* Reduced from default */
        }
        
        .student-list-table th,
        .student-list-table td {
            border: 1px solid #dee2e6;
            padding: 8px; /* Reduced from 12px */
            text-align: center;
        }
        
        .student-list-table th {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            font-weight: 600;
        }
        
        .student-list-table tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .student-list-table tbody tr:hover {
            background-color: #e3f2fd;
            cursor: pointer;
            transition: background-color 0.2s; /* Reduced from 0.3s */
        }
        
        @media print {
            .no-print { display: none !important; }
            .container-fluid { max-width: 100% !important; }
            body { 
                font-size: 10px; /* Reduced for print */
                font-family: 'Hind Siliguri', sans-serif;
            }
            .marksheet { 
                page-break-inside: avoid; 
                box-shadow: none;
                border: 2px solid #000 !important;
                padding: 10px;
                background: white;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .marksheet::before {
                opacity: 0.03; /* Reduced from 0.05 */
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .school-header {
                border-bottom: 2px solid #000 !important;
                background: white;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .school-logo {
                border: 1px solid #000; /* Reduced from 2px */
                box-shadow: none;
                width: 50px; /* Reduced for print */
                height: 50px; /* Reduced for print */
                display: block !important;
            }
            
            .school-logo img {
                max-height: 50px !important;
                width: auto !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .marks-table th {
                background: #f8f9fa;
                color: #000;
            }
            
            /* Ensure borders appear in print */
            .marks-table,
            .marks-table th,
            .marks-table td,
            .student-info,
            .result-summary,
            .signature-section {
                border: 1px solid #000 !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .marks-table th {
                background: #e9ecef !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .student-info,
            .result-summary {
                background: #f8f9fa !important;
                border: 1px solid #e9ecef !important;
                border-radius: 6px !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .signature-section {
                display: grid;
                grid-template-columns: 1fr 1fr 1fr;
                gap: 15px;
                margin-top: 20px;
                text-align: center;
            }
            
            .signature-box {
                border-top: 1px solid #3498db !important;
                padding-top: 8px;
                margin-top: 20px;
                font-weight: 600;
                color: #2c3e50;
                font-size: 12px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            /* Header styles */
            .school-header h3 {
                color: #2c3e50 !important;
                font-weight: 700;
                margin: 8px 0 3px 0;
                text-shadow: 1px 1px 1px rgba(0,0,0,0.1);
                font-size: 20px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .school-header h4 {
                color: #e74c3c !important;
                font-weight: 600;
                margin: 10px 0 0 0;
                text-decoration: underline;
                text-underline-offset: 5px;
                font-size: 16px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            /* Hide all watermark images when printing */
            .marksheet img[alt=''] {
                display: none !important;
            }
            /* Student photo styles */
            .student-photo {
                display: block;
            }
            
            .student-photo-print {
                max-width: 100px;
                max-height: 120px;
                border: 2px solid #3498db;
                border-radius: 5px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            
            /* Student photo print styles */
            .student-photo {
                display: block !important;
            }
            
            .student-photo-print {
                max-width: 80px !important;
                max-height: 100px !important;
                border: 1px solid #000 !important;
                border-radius: 3px !important;
                box-shadow: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <?php if ($student_id && $session && $exam_type): ?>
        <div class="text-center mb-3 no-print">
            <button onclick="window.print()" class="btn btn-success"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
            <a href="bulk_print_marksheets.php?class_id=<?php echo urlencode($class_id); ?>&session=<?php echo urlencode($session); ?>&exam_type=<?php echo urlencode($exam_type); ?>&branch_id=<?php echo $branch_id; ?>&group_name=<?php echo urlencode($group_name); ?>" class="btn btn-info" target="_blank"><i class="fas fa-print"></i> সকল মার্কশীট প্রিন্ট করুন</a>
            <a href="all_subjects_marksheet.php" class="btn btn-primary"><i class="fas fa-search"></i> নতুন অনুসন্ধান</a>
            <a href="../index.php" class="btn btn-secondary"><i class="fas fa-home"></i> হোম</a>
        </div>
        
        <div class="marksheet">
            <div class="school-header">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <!-- School Logo - Left -->
                    <div class="school-logo">
                        <?php if ($logo_image): ?>
                            <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" style="max-height: <?php echo $logo_size; ?>px; width: auto;">
                        <?php else: ?>
                            <i class="fas fa-graduation-cap"></i>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Institution Name and Address - Center -->
                    <div style="text-align: center; flex-grow: 1; padding: 0 20px;">
                        <h3 style="font-size: 24px; margin: 0 0 5px 0;"><?php echo htmlspecialchars($site_name); ?></h3>
                        <p style="color: #7f8c8d; margin: 0 0 5px 0; font-size: 14px;"><?php echo htmlspecialchars($site_address); ?></p>
                        <h4 style="font-size: 18px; margin: 0;">একাডেমিক মার্কশীট</h4>
                    </div>
                    
                    <!-- Student Photo - Right -->
                    <div style="text-align: right;" class="student-photo">
                        <?php if (!empty($student['photo']) && file_exists(__DIR__ . '/' . $student['photo'])): ?>
                            <img src="<?php echo htmlspecialchars($student['photo']); ?>" alt="Student Photo" class="student-photo-print" style="max-width: 100px; max-height: 120px; border: 2px solid #3498db; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                        <?php else: ?>
                            <div style="width: 100px; height: 120px; border: 2px dashed #3498db; border-radius: 5px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa;">
                                <i class="fas fa-user" style="font-size: 36px; color: #3498db;"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Watermark Logos -->
            <?php if ($logo_image): ?>
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(45deg); opacity: 0.05; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 3); ?>px; height: <?php echo ($logo_size * 3); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; top: 20%; left: 20%; transform: rotate(30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; top: 20%; right: 20%; transform: rotate(-30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; bottom: 20%; left: 20%; transform: rotate(-30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; bottom: 20%; right: 20%; transform: rotate(30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
            <?php endif; ?>
            
            <div class="student-info">
                <div>
                    <div class="info-row">
                        <div class="info-label">শিক্ষার্থী আইডি</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['student_id']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পিতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['father_name'] ?? ''); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">মাতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['mother_name'] ?? ''); ?></div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">রোল নম্বর</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['roll_number']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শ্রেণী</div>
                        <div class="info-value"><?php
                            $class_text = $student['class_name'] . ' ' . $student['section'];
                            if (!empty($student['branch_id'])) {
                                $br_name = '';
                                foreach ($branches as $b) {
                                    if ($b['id'] == $student['branch_id']) { $br_name = $b['branch_name']; break; }
                                }
                                if ($br_name) $class_text .= ' (' . $br_name . ')';
                            }
                            echo htmlspecialchars($class_text);
                        ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">সেশন</div>
                        <div class="info-value"><?php echo htmlspecialchars($session); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পরীক্ষার ধরন</div>
                        <div class="info-value"><?php echo htmlspecialchars(ucfirst($exam_type)); ?></div>
                    </div>
                    <?php if (!empty($student['branch_id'])): ?>
                    <div class="info-row">
                        <div class="info-label">শাখা</div>
                        <div class="info-value"><?php 
                            $br_name = '';
                            foreach ($branches as $b) {
                                if ($b['id'] == $student['branch_id']) { $br_name = $b['branch_name']; break; }
                            }
                            echo htmlspecialchars($br_name);
                        ?></div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <table class="marks-table">
                <thead>
                    <tr>
                        <th rowspan="2">বিষয়</th>
                        <th colspan="5">প্রাপ্ত নম্বর</th>
                        <th rowspan="2">প্রাপ্ত<br>নম্বর</th>
                        <th rowspan="2">অতিরিক্ত<br>পয়েন্ট</th>
                        <th rowspan="2">পাস<br>নম্বর</th>
                        <th rowspan="2">গ্রেড</th>
                        <th rowspan="2">জিপি</th>
                    </tr>
                    <tr>
                        <th>সৃজনশীল</th>
                        <th>বহুনির্বাচনি</th>
                        <th>ব্যবহারিক</th>
                        <th>অ্যাসাইনমেন্ট</th>
                        <th>শ্রেণিতে<br>সর্বোচ্চ</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($results as $result): ?>
                    <tr <?php echo isset($result['is_fourth_subject']) && $result['is_fourth_subject'] ? 'style="background-color: #fff3cd;"' : ''; ?>>
                        <td style="text-align: left; padding-left: 15px; font-weight: 500;">
                            <?php echo htmlspecialchars($result['subject_name']); ?>
                            <?php if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']): ?>
                                <span style="color: #856404; font-weight: bold;"> (চতুর্থ বিষয়)</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php 
                            // For combined subjects, show individual CQ marks and average without fractions
                            if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && isset($result['cq_marks_array'])) {
                                // Show individual marks
                                $individual_marks = [];
                                foreach ($result['cq_marks_array'] as $mark) {
                                    $individual_marks[] = floor($mark);
                                }
                                // Calculate average and remove fractional part
                                $avg_cq = array_sum($result['cq_marks_array']) / count($result['cq_marks_array']);
                                echo implode(', ', $individual_marks) . ' (গড়: ' . floor($avg_cq) . ')';
                            } else {
                                echo htmlspecialchars(floor($result['cq_marks']) ?: '-');
                            }
                            ?>
                        </td>
                        <td>
                            <?php 
                            // For combined subjects, show individual MCQ marks and average without fractions
                            if (($result['subject_name'] == 'বাংলা(একত্রে)' || $result['subject_name'] == 'ইংরেজি(একত্রে)') && isset($result['mcq_marks_array'])) {
                                // Show individual marks
                                $individual_marks = [];
                                foreach ($result['mcq_marks_array'] as $mark) {
                                    $individual_marks[] = floor($mark);
                                }
                                // Calculate average and remove fractional part
                                $avg_mcq = array_sum($result['mcq_marks_array']) / count($result['mcq_marks_array']);
                                echo implode(', ', $individual_marks) . ' (গড়: ' . floor($avg_mcq) . ')';
                            } else {
                                echo htmlspecialchars(floor($result['mcq_marks']) ?: '-');
                            }
                            ?>
                        </td>
                        <td><?php echo htmlspecialchars($result['practical_marks'] ?: '-'); ?></td>
                        <td><?php echo htmlspecialchars($result['assignment_marks'] ?: '-'); ?></td>
                        <td><?php echo ($result['class_max_marks'] !== null && $result['class_max_marks'] >= 0) ? htmlspecialchars(sprintf('%.0f', $result['class_max_marks'])) : '-'; ?></td>
                        <td style="font-weight: 600;"><?php echo htmlspecialchars(floor($result['marks_obtained'])); ?></td>
                        <td style="text-align: center; font-weight: 600;">
                            <?php 
                            if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                                if ($result['grade_point'] > 2.00) {
                                    echo number_format($result['grade_point'] - 2.00, 2);
                                } else {
                                    echo '0.00';
                                }
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                        <td><?php echo htmlspecialchars($result['pass_marks']); ?></td>
                        <td style="font-weight: 700; 
                            <?php 
                            switch ($result['grade']) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo htmlspecialchars($result['grade']); ?>
                        </td>
                        <td><?php echo number_format($result['grade_point'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <!-- GPA Summary Row -->
                    <tr style="background-color: #e3f2fd; font-weight: bold;">
                        <td colspan="10" style="text-align: right; padding-right: 15px;">জিপিএ (Grade Point Average):</td>
                        <td><?php echo number_format($final_gpa ?? $gpa, 2); ?></td>
                    </tr>
                </tbody>
            </table>
            
            <div class="result-summary">
                <div>
                    <div class="info-row">
                        <div class="info-label">মোট নম্বর</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo $total_obtained; ?>/<?php echo $total_marks; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শতাংশ</div>
                        <div class="info-value" style="font-weight: 700; color: #3498db;"><?php echo $percentage; ?>%</div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">গ্রেড</div>
                        <div class="info-value" style="font-weight: 700; font-size: 18px; 
                            <?php 
                            // Calculate grade based on GPA instead of percentage
                            $gpa_based_grade = calculateGradeFromGPA($gpa);
                            switch ($gpa_based_grade) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo $gpa_based_grade; ?>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">জিপিএ</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo number_format($gpa, 2); ?></div>
                    </div>
                    <?php if ($merit_position): ?>
                    <div class="info-row">
                        <div class="info-label">মেরিট পজিশন</div>
                        <div class="info-value" style="font-weight: 700; 
                            <?php 
                            if ($merit_position == 1) {
                                echo 'color: #f1c40f; font-size: 20px;';
                            } elseif ($merit_position <= 3) {
                                echo 'color: #9b59b6; font-size: 18px;';
                            } else {
                                echo 'color: #3498db;';
                            }
                            ?>">
                            <?php echo $merit_position; ?>
                            <?php if ($merit_position == 1): ?>
                                <i class="fas fa-trophy" style="color: #f1c40f;"></i>
                            <?php elseif ($merit_position == 2): ?>
                                <i class="fas fa-medal" style="color: #aaa;"></i>
                            <?php elseif ($merit_position == 3): ?>
                                <i class="fas fa-medal" style="color: #cd7f32;"></i>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="signature-section">
                <div>
                    <div class="signature-box" style="font-weight: 600; color: #2c3e50;">শিক্ষার্থীর স্বাক্ষর</div>
                </div>
                <div>
                    <div class="signature-box" style="font-weight: 600; color: #2c3e50;">শিক্ষকের স্বাক্ষর</div>
                </div>
                <div>
                    <div class="signature-box" style="font-weight: 600; color: #2c3e50;">অধ্যাপকের স্বাক্ষর</div>
                </div>
            </div>
        </div>
        <?php elseif ($show_student_list): ?>
        <!-- Student List View -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4 class="card-title mb-0">শিক্ষার্থী নির্বাচন করুন</h4>
                <div>
                    <a href="bulk_print_marksheets.php?class_id=<?php echo urlencode($class_id); ?>&session=<?php echo urlencode($session); ?>&exam_type=<?php echo urlencode($exam_type); ?>&branch_id=<?php echo $branch_id; ?>&group_name=<?php echo urlencode($group_name); ?>" class="btn btn-info btn-sm me-2" target="_blank">
                        <i class="fas fa-print"></i> সকল মার্কশীট প্রিন্ট করুন
                    </a>
                    <a href="all_subjects_marksheet.php" class="btn btn-secondary btn-sm me-2">
                        <i class="fas fa-arrow-left"></i> পিছনে
                    </a>
                    <a href="../index.php" class="btn btn-secondary btn-sm">
                        <i class="fas fa-home"></i> হোম
                    </a>
                </div>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-3">
                        <h5>শ্রেণী: 
                            <?php 
                            $selected_class = array_filter($classes, function($c) use ($class_id) { return $c['id'] == $class_id; });
                            echo !empty($selected_class) ? htmlspecialchars(reset($selected_class)['name'] . ' ' . reset($selected_class)['section']) : '';
                            ?>
                        </h5>
                    </div>
                    <div class="col-md-3">
                        <h5>সেশন: <?php echo htmlspecialchars($session); ?></h5>
                    </div>
                    <div class="col-md-3">
                        <h5>পরীক্ষা: <?php echo htmlspecialchars(ucfirst($exam_type)); ?></h5>
                    </div>
                    <div class="col-md-3">
                        <h5>শাখা: <?php 
                            if ($branch_id > 0) {
                                $selected_branch = array_filter($branches, function($b) use ($branch_id) { return $b['id'] == $branch_id; });
                                echo !empty($selected_branch) ? htmlspecialchars(reset($selected_branch)['branch_name']) : '-';
                            } else {
                                echo 'সব';
                            }
                        ?> | গ্রুপ: <?php echo $group_name ? htmlspecialchars($group_name) : 'সব'; ?></h5>
                    </div>
                </div>
                
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" id="student-search" class="form-control" placeholder="শিক্ষার্থী খুঁজুন (নাম, রোল, আইডি)" value="<?php echo htmlspecialchars($student_search); ?>">
                            <button class="btn btn-outline-secondary" type="button" id="search-btn">
                                <i class="fas fa-search"></i> খুঁজুন
                            </button>
                        </div>
                    </div>
                    <?php if (!empty($students_in_class)): ?>
                    <div class="col-md-6 text-end">
                        <button class="btn btn-success" id="bulk-print-btn">
                            <i class="fas fa-print"></i> সবগুলো প্রিন্ট করুন
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="table-responsive" id="student-table-container">
                    <?php if (empty($students_in_class)): ?>
                        <div class="alert alert-info text-center">
                            <i class="fas fa-info-circle"></i> কোন তথ্য পাওয়া যায়নি
                        </div>
                    <?php else: ?>
                        <table class="student-list-table">
                            <thead>
                                <tr>
                                    <th>রোল</th>
                                    <th>শিক্ষার্থী আইডি</th>
                                    <th>নাম</th>
                                    <th>শাখা</th>
                                    <th>গ্রুপ</th>
                                    <th>কার্যক্রম</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($students_in_class as $student_item): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($student_item['roll_number']); ?></td>
                                    <td><?php echo htmlspecialchars($student_item['student_id']); ?></td>
                                    <td><?php echo htmlspecialchars($student_item['first_name'] . ' ' . $student_item['last_name']); ?></td>
                                    <td><?php 
                                        if (!empty($student_item['branch_id'])) {
                                            $br_name = '';
                                            foreach ($branches as $b) {
                                                if ($b['id'] == $student_item['branch_id']) { $br_name = $b['branch_name']; break; }
                                            }
                                            echo htmlspecialchars($br_name);
                                        } else { echo '-'; }
                                    ?></td>
                                    <td><?php echo htmlspecialchars($student_item['group_name'] ?? '-'); ?></td>
                                    <td>
                                        <a href="?student_id=<?php echo $student_item['id']; ?>&class_id=<?php echo urlencode($class_id); ?>&session=<?php echo urlencode($session); ?>&exam_type=<?php echo urlencode($exam_type); ?>&branch_id=<?php echo $branch_id; ?>&group_name=<?php echo urlencode($group_name); ?>" class="btn btn-primary btn-sm">
                                            <i class="fas fa-eye"></i> ফলাফল দেখুন
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <script>
            // Handle search button click
            document.getElementById('search-btn').addEventListener('click', function() {
                performSearch();
            });
            
            // Handle Enter key in search box
            document.getElementById('student-search').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    performSearch();
                }
            });
            
            // Make search dynamic with AJAX
            let searchTimeout;
            document.getElementById('student-search').addEventListener('input', function() {
                const searchTerm = this.value;
                // Clear previous timeout
                clearTimeout(searchTimeout);
                
                // Set new timeout
                searchTimeout = setTimeout(function() {
                    if (searchTerm.length >= 2 || searchTerm.length === 0) {
                        performSearch();
                    }
                }, 300); // 300ms delay
            });
            
            function performSearch() {
                const searchTerm = document.getElementById('student-search').value;
                const classId = '<?php echo $class_id; ?>';
                const session = '<?php echo $session; ?>';
                const examType = '<?php echo $exam_type; ?>';
                const branchId = '<?php echo $branch_id; ?>';
                const groupName = '<?php echo addslashes($group_name); ?>';
                
                // Show loading indicator
                const container = document.getElementById('student-table-container');
                container.innerHTML = '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">লোড হচ্ছে...</span></div></div>';
                
                // Add CSS for spinner if not already present
                if (!document.getElementById('spinner-styles')) {
                    const style = document.createElement('style');
                    style.id = 'spinner-styles';
                    style.innerHTML = `
                        .spinner-border {
                            display: inline-block;
                            width: 2rem;
                            height: 2rem;
                            vertical-align: -0.125em;
                            border: 0.25em solid currentColor;
                            border-right-color: transparent;
                            border-radius: 50%;
                            animation: spinner-border 0.75s linear infinite;
                        }
                        @keyframes spinner-border {
                            to {
                                transform: rotate(360deg);
                            }
                        }
                        .text-primary {
                            color: #0d6efd;
                        }
                        .visually-hidden {
                            position: absolute;
                            width: 1px;
                            height: 1px;
                            padding: 0;
                            margin: -1px;
                            overflow: hidden;
                            clip: rect(0, 0, 0, 0);
                            white-space: nowrap;
                            border: 0;
                        }
                    `;
                    document.head.appendChild(style);
                }
                
                // For dynamic search, we'll use AJAX to update the table without page reload
                fetch(`marksheet_search.php?class_id=${classId}&session=${session}&exam_type=${examType}&student_search=${encodeURIComponent(searchTerm)}&branch_id=${branchId}&group_name=${encodeURIComponent(groupName)}`)
                    .then(response => response.text())
                    .then(data => {
                        container.innerHTML = data;
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        container.innerHTML = '<div class="alert alert-danger text-center">ত্রুটি দেখা দিয়েছে, অনুগ্রহ করে আবার চেষ্টা করুন</div>';
                    });
            }
            
            function selectStudent(studentId) {
                const session = '<?php echo $session; ?>';
                const examType = '<?php echo $exam_type; ?>';
                const branchId = '<?php echo $branch_id; ?>';
                const groupName = '<?php echo addslashes($group_name); ?>';
                window.location.href = `?student_id=${studentId}&session=${session}&exam_type=${examType}&branch_id=${branchId}&group_name=${encodeURIComponent(groupName)}`;
            }
        </script>
        <?php else: ?>
        <!-- Initial Search Form -->
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">সকল বিষয়ের মার্কশীট অনুসন্ধান করুন</h4>
            </div>
            <div class="card-body">
                <form method="GET" action="" class="row g-3">
                    <div class="col-md-2">
                        <label for="class_id" class="form-label">শ্রেণী</label>
                        <select id="class_id" name="class_id" class="form-select" required>
                            <option value="">শ্রেণী নির্বাচন</option>
                            <?php foreach ($classes as $class_item): ?>
                                <option value="<?php echo htmlspecialchars($class_item['id']); ?>">
                                    <?php echo htmlspecialchars($class_item['name'] . ' ' . $class_item['section']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="branch_id" class="form-label">শাখা</label>
                        <select id="branch_id" name="branch_id" class="form-select">
                            <option value="0">সব শাখা</option>
                            <?php foreach ($branches as $br): ?>
                                <option value="<?php echo $br['id']; ?>" <?php echo $branch_id == $br['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($br['branch_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="group_name" class="form-label">গ্রুপ</label>
                        <select id="group_name" name="group_name" class="form-select">
                            <option value="">সব গ্রুপ</option>
                            <?php foreach ($groups as $grp): ?>
                                <option value="<?php echo htmlspecialchars($grp['group_name']); ?>" <?php echo $group_name === $grp['group_name'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($grp['group_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="session" class="form-label">সেশন</label>
                        <select id="session" name="session" class="form-select" required>
                            <option value="">সেশন নির্বাচন</option>
                            <?php foreach ($sessions as $session_item): ?>
                                <option value="<?php echo htmlspecialchars($session_item['session']); ?>" <?php echo $session === $session_item['session'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($session_item['session']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="exam_type" class="form-label">পরীক্ষার ধরন</label>
                        <select id="exam_type" name="exam_type" class="form-select" required>
                            <option value="">পরীক্ষা নির্বাচন</option>
                            <?php foreach ($exam_types as $exam_type_item): ?>
                                <option value="<?php echo htmlspecialchars($exam_type_item['exam_type']); ?>">
                                    <?php echo htmlspecialchars($exam_type_item['exam_type']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i> খুঁজুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Add bulk print functionality
    document.addEventListener('DOMContentLoaded', function() {
        const bulkPrintBtn = document.getElementById('bulk-print-btn');
        if (bulkPrintBtn) {
            bulkPrintBtn.addEventListener('click', function() {
                // Get current search parameters
                const urlParams = new URLSearchParams(window.location.search);
                const classId = urlParams.get('class_id');
                const session = urlParams.get('session');
                const examType = urlParams.get('exam_type');
                const studentSearch = urlParams.get('student_search') || '';
                
                // Redirect to bulk print page with same parameters
                const bulkPrintUrl = `bulk_print_marksheets.php?class_id=${encodeURIComponent(classId)}&session=${encodeURIComponent(session)}&exam_type=${encodeURIComponent(examType)}&student_search=${encodeURIComponent(studentSearch)}`;
                window.open(bulkPrintUrl, '_blank');
            });
        }
    });
    </script>
</body>
</html>
