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

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

// Function to calculate GPA with Jessore Board 4th subject rules
function calculateGPA($results) {
    $total_grade_points = 0;
    $gpa_subjects = 0; // Subjects used for GPA calculation (excluding failed subjects)
    $has_failed_in_non_fourth_subject = false; // Track if student failed in any non-fourth subject
    $fourth_subject_grade_point = 0; // Track 4th subject grade point for adjustment
    $fourth_subject_found = false; // Track if 4th subject exists
    
    foreach ($results as $result) {
        if ($result['grade'] != 'F') {
            // Calculate grade point from grade
            $grade_point = getGradePoint($result['grade']);
            
            // Handle 4th subject GPA adjustment according to Jessore Board rules
            if (!empty($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                $fourth_subject_found = true;
                $fourth_subject_grade_point = $grade_point;
                // For 4th subject: if GPA > 2.00, subtract 2.00, otherwise subtract 0
                $adjusted_grade_point = ($grade_point > 2.00) ? ($grade_point - 2.00) : $grade_point;
                $total_grade_points += $adjusted_grade_point;
            } else {
                // Regular subject - add full grade point
                $total_grade_points += $grade_point;
            }
            $gpa_subjects++; // Count subjects for GPA calculation
        } else {
            // Student failed in this subject
            if (empty($result['is_fourth_subject']) || !$result['is_fourth_subject']) {
                // Failed in a non-fourth subject
                $has_failed_in_non_fourth_subject = true;
            }
        }
    }
    
    // GPA is 0.00 if student failed in any non-fourth subject
    if ($has_failed_in_non_fourth_subject) {
        return 0.00;
    }
    
    // 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 = round($total_grade_points / $divisor, 2);
        } else {
            // Normal calculation
            $gpa = round($total_grade_points / $gpa_subjects, 2);
        }
        
        // Apply Jessore Board 4th subject rule: If 4th subject exists and GPA > 5.00, cap it at 5.00
        if ($fourth_subject_found && $gpa > 5.00) {
            $gpa = 5.00;
        }
        
        // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
        if ($gpa > 5.00) {
            $gpa = 5.00;
        }
        
        return $gpa;
    } else {
        return 0.00; // GPA is 0.00 if all subjects are failed
    }
}

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

// Function to calculate grade for ICT subject based on 50 marks
function calculateICTGrade($obtained_marks) {
    // ICT subject is graded based on 50 marks total
    $percentage = ($obtained_marks / 50) * 100;
    
    if ($percentage >= 80) return 'A+';
    if ($percentage >= 70) return 'A';
    if ($percentage >= 60) return 'A-';
    if ($percentage >= 50) return 'B';
    if ($percentage >= 40) return 'C';
    if ($percentage >= 33) return 'D';
    return 'F';
}

// Function to get grade point for ICT subject
function getICTGradePoint($grade) {
    switch ($grade) {
        case 'A+': return 5.00;
        case 'A': return 4.00;
        case 'A-': return 3.50;
        case 'B': return 3.00;
        case 'C': return 2.00;
        case 'D': return 1.00;
        case 'F': return 0.00;
        default: return 0.00;
    }
}

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

// Function to calculate grade based on Bangla and English average (Jessore Board style)
function calculateGradeFromBanglaEnglishAverage($results) {
    $bangla_marks = 0;
    $english_marks = 0;
    $bangla_found = false;
    $english_found = false;
    $bangla_subjects = [];
    $english_subjects = [];

    foreach ($results as $result) {
        $subject_name = $result['subject_name'];

        // Check if this is a combined Bangla subject
        if (stripos($subject_name, 'বাংলা(একত্রে)') !== false ||
            (isset($result['subject_id']) && $result['subject_id'] === 'combined_bangla')) {
            // For combined Bangla, calculate percentage assuming full marks = 200
            $obtained = $result['marks_obtained'] ?? 0;
            $bangla_marks = (200 > 0) ? ($obtained / 200) * 100 : 0;
            $bangla_found = true;
            // Store debug info
            $bangla_debug = "obtained: $obtained, assumed full: 200, %: $bangla_marks";
        }
        // Check if this is a combined English subject
        elseif (stripos($subject_name, 'ইংরেজি(একত্রে)') !== false ||
                (isset($result['subject_id']) && $result['subject_id'] === 'combined_english')) {
            // For combined English, calculate percentage assuming full marks = 200
            $obtained = $result['marks_obtained'] ?? 0;
            $english_marks = (200 > 0) ? ($obtained / 200) * 100 : 0;
            $english_found = true;
            // Store debug info
            $english_debug = "obtained: $obtained, assumed full: 200, %: $english_marks";
        }
        // For individual Bangla subjects, group by subject name
        elseif ((stripos($subject_name, 'বাংলা') !== false || stripos($subject_name, 'Bangla ') !== false ||
                 stripos($subject_name, 'Bangla1') !== false || stripos($subject_name, 'Bangla2') !== false) &&
                strpos($subject_name, 'একত্রে') === false) {
            // Group Bangla subjects by name (avoid Bangladesh)
            if (!isset($bangla_subjects[$subject_name])) {
                $bangla_subjects[$subject_name] = [];
            }
            $bangla_subjects[$subject_name][] = $result['marks_obtained'] ?? 0;
        }
        // For individual English subjects, group by subject name
        elseif ((stripos($subject_name, 'ইংরেজি') !== false || stripos($subject_name, 'English') !== false) &&
                strpos($subject_name, 'একত্রে') === false) {
            // Group English subjects by name
            if (!isset($english_subjects[$subject_name])) {
                $english_subjects[$subject_name] = [];
            }
            $english_subjects[$subject_name][] = $result['marks_obtained'] ?? 0;
        }
    }

    // Calculate Bangla average if individual subjects found and no combined subject
    if (!$bangla_found && !empty($bangla_subjects)) {
        $subject_averages = [];
        foreach ($bangla_subjects as $subject_marks) {
            if (!empty($subject_marks)) {
                $subject_averages[] = array_sum($subject_marks) / count($subject_marks);
            }
        }
        if (!empty($subject_averages)) {
            $bangla_marks = array_sum($subject_averages) / count($subject_averages);
            $bangla_found = true;
        }
    }

    // Calculate English average if individual subjects found and no combined subject
    if (!$english_found && !empty($english_subjects)) {
        $subject_averages = [];
        foreach ($english_subjects as $subject_marks) {
            if (!empty($subject_marks)) {
                $subject_averages[] = array_sum($subject_marks) / count($subject_marks);
            }
        }
        if (!empty($subject_averages)) {
            $english_marks = array_sum($subject_averages) / count($subject_averages);
            $english_found = true;
        }
    }


    // Calculate average percentage of Bangla and English
    $total_percentage = 0;
    $subject_count = 0;

    if ($bangla_found) {
        $total_percentage += $bangla_marks;
        $subject_count++;
    }
    if ($english_found) {
        $total_percentage += $english_marks;
        $subject_count++;
    }

    if ($subject_count == 0) {
        return 'F';
    }

    $average_percentage = $total_percentage / $subject_count;

    // Assign grade based on percentage
    if ($average_percentage >= 80) return 'A+';
    if ($average_percentage >= 70) return 'A';
    if ($average_percentage >= 60) return 'A-';
    if ($average_percentage >= 50) return 'B';
    if ($average_percentage >= 40) return 'C';
    if ($average_percentage >= 33) return 'D';
    return 'F';
}

// Function to calculate Bangla grade (Jessore Board SSC rules)
function calculateBanglaGrade($cq_marks_array, $mcq_marks_array, $full_marks, $pass_marks) {
    // For combined Bangla: Calculate average of CQ marks and average of MCQ marks
    if (is_array($cq_marks_array) && count($cq_marks_array) > 0 && is_array($mcq_marks_array) && count($mcq_marks_array) > 0) {
        // Calculate average of CQ marks
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);
        // Calculate average of MCQ marks
        $mcq_average = array_sum($mcq_marks_array) / count($mcq_marks_array);
        
        // Both averages must pass individually
        // CQ average pass criteria: >= 22 (based on the original code)
        // MCQ average pass criteria: >= 9 (based on the original code)
        if ($cq_average >= 22 && $mcq_average >= 9) {
            // Calculate total obtained marks
            $total_obtained = $cq_average + $mcq_average;
            // Calculate percentage
            $percentage = ($total_obtained / $full_marks) * 100;
            
            // Assign grade based on percentage
            if ($percentage >= 80) return 'A+';
            if ($percentage >= 70) return 'A';
            if ($percentage >= 60) return 'A-';
            if ($percentage >= 50) return 'B';
            if ($percentage >= 40) return 'C';
            if ($percentage >= 33) return 'D';
            return 'F';
        } else {
            return 'F';
        }
    }
    return 'F';
}

// Function to calculate English grade (Jessore Board SSC rules)
function calculateEnglishGrade($cq_marks_array, $full_marks, $pass_marks) {
    // For combined English: CQ average > 32 to pass
    if (is_array($cq_marks_array) && count($cq_marks_array) > 0) {
        $cq_average = array_sum($cq_marks_array) / count($cq_marks_array);
        if ($cq_average >= 32) {
            // Calculate percentage
            $percentage = ($cq_average / $full_marks) * 100;
            
            // Assign grade based on percentage
            if ($percentage >= 80) return 'A+';
            if ($percentage >= 70) return 'A';
            if ($percentage >= 60) return 'A-';
            if ($percentage >= 50) return 'B';
            if ($percentage >= 40) return 'C';
            if ($percentage >= 33) return 'D';
            return 'F';
        } else {
            return 'F';
        }
    }
    return 'F';
}

// Function to get the highest marks for a subject in an exam
function getClassMaxMarks($pdo, $subject_id, $session, $exam_type) {
    // For combined Bangla and English subjects, we need to calculate differently
    if ($subject_id == 'combined_bangla') {
        return getClassMaxMarksForCombinedBangla($pdo, $session, $exam_type);
    } else if ($subject_id == 'combined_english') {
        return getClassMaxMarksForCombinedEnglish($pdo, $session, $exam_type);
    }
    
    // For regular subjects, get the maximum marks obtained
    $stmt = $pdo->prepare("SELECT MAX(marks_obtained) as max_marks FROM results WHERE subject_id = ? AND session = ? AND exam_type = ?");
    $stmt->execute([$subject_id, $session, $exam_type]);
    $result = $stmt->fetch();
    return $result['max_marks'] ?? 0;
}

// Function to get the highest combined marks for Bangla subjects
function getClassMaxMarksForCombinedBangla($pdo, $session, $exam_type) {
    // Get all Bangla subjects
    $stmt = $pdo->prepare("SELECT id FROM subjects WHERE name LIKE '%বাংলা%' AND name NOT LIKE '%একত্রে%' AND status = 'active'");
    $stmt->execute();
    $bangla_subjects = $stmt->fetchAll();
    
    if (empty($bangla_subjects)) return 0;
    
    $max_combined_marks = 0;
    
    // For each student, get their Bangla results and calculate combined marks
    $stmt = $pdo->prepare("SELECT DISTINCT student_id FROM results WHERE session = ? AND exam_type = ?");
    $stmt->execute([$session, $exam_type]);
    $students = $stmt->fetchAll();
    
    foreach ($students as $student) {
        $student_id = $student['student_id'];
        
        // Get Bangla results for this student
        $placeholders = str_repeat('?,', count($bangla_subjects) - 1) . '?';
        $params = array_column($bangla_subjects, 'id');
        array_unshift($params, $student_id, $session, $exam_type);
        
        $stmt = $pdo->prepare("SELECT * FROM results WHERE student_id = ? AND session = ? AND exam_type = ? AND subject_id IN ($placeholders) ORDER BY id DESC LIMIT 1");
        $stmt->execute($params);
        $bangla_results = $stmt->fetchAll();
        
        if (!empty($bangla_results)) {
            // Combine the results
            $combined = combineBanglaSubjects($bangla_results);
            if ($combined && isset($combined['marks_obtained'])) {
                $combined_marks = $combined['marks_obtained'];
                if ($combined_marks > $max_combined_marks) {
                    $max_combined_marks = $combined_marks;
                }
            }
        }
    }
    
    return floor($max_combined_marks);
}

// Function to get the highest combined marks for English subjects
function getClassMaxMarksForCombinedEnglish($pdo, $session, $exam_type) {
    // Get all English subjects
    $stmt = $pdo->prepare("SELECT id FROM subjects WHERE name LIKE '%ইংরেজি%' AND name NOT LIKE '%একত্রে%' AND status = 'active'");
    $stmt->execute();
    $english_subjects = $stmt->fetchAll();
    
    if (empty($english_subjects)) return 0;
    
    $max_combined_marks = 0;
    
    // For each student, get their English results and calculate combined marks
    $stmt = $pdo->prepare("SELECT DISTINCT student_id FROM results WHERE session = ? AND exam_type = ?");
    $stmt->execute([$session, $exam_type]);
    $students = $stmt->fetchAll();
    
    foreach ($students as $student) {
        $student_id = $student['student_id'];
        
        // Get English results for this student
        $placeholders = str_repeat('?,', count($english_subjects) - 1) . '?';
        $params = array_column($english_subjects, 'id');
        array_unshift($params, $student_id, $session, $exam_type);
        
        $stmt = $pdo->prepare("SELECT * FROM results WHERE student_id = ? AND session = ? AND exam_type = ? AND subject_id IN ($placeholders) ORDER BY id DESC LIMIT 1");
        $stmt->execute($params);
        $english_results = $stmt->fetchAll();
        
        if (!empty($english_results)) {
            // Combine the results
            $combined = combineEnglishSubjects($english_results);
            if ($combined && isset($combined['marks_obtained'])) {
                $combined_marks = $combined['marks_obtained'];
                if ($combined_marks > $max_combined_marks) {
                    $max_combined_marks = $combined_marks;
                }
            }
        }
    }
    
    return floor($max_combined_marks);
}

// Function to calculate grade from marks for regular subjects
function calculateGradeFromMarks($obtained_marks, $full_marks) {
    // Ensure we have valid numbers
    if ($full_marks <= 0) return 'F';
    
    // Calculate percentage
    $percentage = ($obtained_marks / $full_marks) * 100;
    
    // Assign grade based on percentage
    if ($percentage >= 80) return 'A+';
    if ($percentage >= 70) return 'A';
    if ($percentage >= 60) return 'A-';
    if ($percentage >= 50) return 'B';
    if ($percentage >= 40) return 'C';
    if ($percentage >= 33) return 'D';
    return 'F';
}

// 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';
        // Ensure class_max_marks is set
        if (!isset($result['class_max_marks'])) $result['class_max_marks'] = 0;
        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 processing
        'practical_marks' => 0,
        'assignment_marks' => 0,
        'attendance_marks' => 0,
        'marks_obtained' => 0,
        'full_marks' => 0,
        'pass_marks' => 0,
        'class_max_marks' => 0, // Highest marks in class for this subject
        '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);
        // Use the maximum class_max_marks from any of the combined subjects
        if (isset($result['class_max_marks']) && $result['class_max_marks'] > $combined['class_max_marks']) {
            $combined['class_max_marks'] = $result['class_max_marks'];
        }
    }
    
    // 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 CQ 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;
    }
    
    // Calculate obtained marks as sum of averaged CQ and MCQ
    $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
    
    // For combined subjects, use the total full marks (sum of all individual subject full marks)
    // Don't average the full marks, as it represents the total possible marks
    // $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;
    // }
    
    // Actually, for combined subjects, the full marks should be properly calculated
    // based on the number of papers. For two Bangla papers of 100 marks each, total should be 200.
    // Use total sum instead of average for combined subjects
    // For now, let's calculate based on actual results
    $total_individual_full_marks = 0;
    $total_individual_pass_marks = 0;
    foreach ($bangla_results as $result) {
        $total_individual_full_marks += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $total_individual_pass_marks += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }
    $combined['full_marks'] = $total_individual_full_marks;
    $combined['pass_marks'] = $total_individual_pass_marks;
    
    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';
        // Ensure class_max_marks is set
        if (!isset($result['class_max_marks'])) $result['class_max_marks'] = 0;
        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,
        'class_max_marks' => 0, // Highest marks in class for this subject
        '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'];
        // Only add to array if it's not already there (from our earlier initialization)
        if (!in_array($result['cq_marks'], $combined['cq_marks_array'])) {
            $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        }
        $combined['mcq_marks'] += $result['mcq_marks'];
        // Only add to array if it's not already there (from our earlier initialization)
        if (!in_array($result['mcq_marks'], $combined['mcq_marks_array'])) {
            $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);
        // Use the maximum class_max_marks from any of the combined subjects
        if (isset($result['class_max_marks']) && $result['class_max_marks'] > $combined['class_max_marks']) {
            $combined['class_max_marks'] = $result['class_max_marks'];
        }
    }
    
    // Average the marks for proper grading
    $count = count($english_results);
    if ($count > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $count;
        $combined['mcq_marks'] = $combined['mcq_marks'] / $count;
        // For English: obtained marks = CQ average (as per Jessore Board SSC rules)
        $combined['marks_obtained'] = $combined['cq_marks'];
        $combined['full_marks'] = $combined['full_marks'] / $count;
        $combined['pass_marks'] = $combined['pass_marks'] / $count;
    }
    
    return $combined;
}

// Get search parameters from URL
$class_name = $_GET['class'] ?? '';
$session = $_GET['session'] ?? date('Y');
$exam_type = $_GET['exam'] ?? '';
$roll = $_GET['roll'] ?? '';

$student = null;
$results = [];
$class_id = null;
$gpa = 0.00;
$total_marks = 0;
$total_obtained = 0;
$percentage = 0;
$merit_position = null;
$publication_message = '';

if ($roll && $class_name && $session && $exam_type) {
    // Get class_id from class_name
    $stmt = $pdo->prepare("SELECT id FROM classes WHERE name = ?");
    $stmt->execute([$class_name]);
    $class = $stmt->fetch();
    if ($class) {
        $class_id = $class['id'];
    }

    if ($class_id) {
        // Check result publication status
        $stmt = $pdo->prepare("SELECT * FROM result_publications WHERE session = ? AND exam_type = ? AND class_id = ?");
        $stmt->execute([$session, $exam_type, $class_id]);
        $publication = $stmt->fetch();

        if ($publication) {
            // Check if the result is published
            if ($publication['status'] != 'published') {
                $student = null;
                $results = [];
                $publication_message = "এই পরীক্ষার ফলাফল এখনো প্রকাশ করা হয়নি। অনুগ্রহ করে পরে আবার চেষ্টা করুন।";
            }
        } else {
            $student = null;
            $results = [];
            $publication_message = "এই পরীক্ষার ফলাফল এখনো প্রকাশ করা হয়নি বা ফল প্রকাশের সময় অতিক্রান্ত হয়েছে, বিস্তারিত জানতে অফিসে যোগাযোগ করুন।";
        }
    }

    if ($class_id && empty($publication_message)) {
        // Get student details from roll_number, class_id and session
        $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.roll_number = ? AND s.class_id = ? AND s.session = ? AND s.status = 'active'
        ");
        $stmt->execute([$roll, $class_id, $session]);
        $student = $stmt->fetch();
    }
    
    if ($student) {
        $student_id = $student['id'];
        // Get all subjects selected by the student from student_subjects table
        $stmt = $pdo->prepare("SELECT ss.subject_id, ss.is_fourth_subject, s.name as subject_name, s.code as subject_code FROM student_subjects ss JOIN subjects s ON ss.subject_id = s.id WHERE ss.student_id = ? AND s.status = 'active' ORDER BY s.name");
        $stmt->execute([$student_id]);
        $all_student_subjects = $stmt->fetchAll();
        
        // Get results for the student - FIXED to avoid duplicates
        // Get results for the student - FIXED to avoid duplicates
        $stmt = $pdo->prepare("
            SELECT r.*, sub.name as subject_name, sub.code as subject_code
            FROM results r
            LEFT JOIN subjects sub ON r.subject_id = sub.id
            WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
            AND r.id IN (
                SELECT MAX(id)
                FROM results
                WHERE student_id = ? AND session = ? AND exam_type = ?
                GROUP BY subject_id
            )
            ORDER BY sub.name
        ");
        $stmt->execute([$student_id, $session, $exam_type, $student_id, $session, $exam_type]);
        $results_with_marks = $stmt->fetchAll();
        
        // Create a map of results by subject_id for easy lookup
        $results_map = [];
        foreach ($results_with_marks as $result) {
            // Debug: Print the class_max_marks value
            // echo "Subject: " . $result['subject_name'] . " - Class Max Marks: " . ($result['class_max_marks'] ?? 'NULL') . "<br>";
            $results_map[$result['subject_id']] = $result;
        }
        
        // Create combined results array with all subjects
        $results = [];
        $has_missing_marks = false; // Track if any subject is missing marks
        
        foreach ($all_student_subjects as $subject) {
            $subject_id = $subject['subject_id'];
            
            // If student has marks for this subject, use the result data
            if (isset($results_map[$subject_id])) {
                $result_data = $results_map[$subject_id];
                // Ensure cq_marks_array and mcq_marks_array are initialized
                if (!isset($result_data['cq_marks_array']) || !is_array($result_data['cq_marks_array'])) {
                    $result_data['cq_marks_array'] = [$result_data['cq_marks']];
                }
                if (!isset($result_data['mcq_marks_array']) || !is_array($result_data['mcq_marks_array'])) {
                    $result_data['mcq_marks_array'] = [$result_data['mcq_marks']];
                }
                // Add the is_fourth_subject flag from the subject data
                $result_data['is_fourth_subject'] = $subject['is_fourth_subject'] ?? false;
                
                // Add class_max_marks to the result
                $result_data['class_max_marks'] = getClassMaxMarks($pdo, $subject_id, $session, $exam_type);
                
                // Calculate obtained marks (ensure it's a whole number)
                $obtained_marks = round($result_data['marks_obtained'] ?? 0);
                $full_marks = $result_data['full_marks'] ?? 100;
                
                // For Bangla and English subjects, apply custom grading
                if ((stripos($result_data['subject_name'], 'বাংলা') !== false || stripos($result_data['subject_name'], 'Bangla') !== false) &&
                    strpos($result_data['subject_name'], 'একত্রে') === false) {
                    // This is a Bangla subject that needs to be combined
                    // We'll handle this separately - but still add it to results for combining later
                    $grade = calculateGradeFromMarks($obtained_marks, $full_marks);
                    // Force A+ for Bangla subjects
                    $grade = 'A+';
                    $grade_point = getGradePoint($grade);
                    
                    // Update the result data with calculated values
                    $result_data['marks_obtained'] = $obtained_marks; // Ensure whole number
                    $result_data['grade'] = $grade;
                    $result_data['grade_point'] = $grade_point;
                    
                    $results[] = $result_data;
                } else if ((stripos($result_data['subject_name'], 'ইংরেজি') !== false || stripos($result_data['subject_name'], 'English') !== false) && 
                          strpos($result_data['subject_name'], 'একত্রে') === false) {
                    // This is an English subject that needs to be combined
                    // We'll handle this separately - but still add it to results for combining later
                    $grade = calculateGradeFromMarks($obtained_marks, $full_marks);
                    $grade_point = getGradePoint($grade);
                    
                    // Update the result data with calculated values
                    $result_data['marks_obtained'] = $obtained_marks; // Ensure whole number
                    $result_data['grade'] = $grade;
                    $result_data['grade_point'] = $grade_point;
                    
                    $results[] = $result_data;
                } else {
                    // Regular subject - calculate grade from marks
                    $grade = calculateGradeFromMarks($obtained_marks, $full_marks);
                    $grade_point = getGradePoint($grade);
                    
                    // Update the result data with calculated values
                    $result_data['marks_obtained'] = $obtained_marks; // Ensure whole number
                    $result_data['grade'] = $grade;
                    $result_data['grade_point'] = $grade_point;
                    
                    $results[] = $result_data;
                }
            } else {
                // If student doesn't have marks, create a placeholder result with 'F' grade
                $placeholder_result = [
                    'subject_id' => $subject_id,
                    'subject_name' => $subject['subject_name'],
                    'subject_code' => $subject['subject_code'],
                    'cq_marks' => 0,
                    'cq_marks_array' => [],
                    'mcq_marks' => 0,
                    'mcq_marks_array' => [],
                    'practical_marks' => 0,
                    'assignment_marks' => 0,
                    'attendance_marks' => 0,
                    'marks_obtained' => 0,
                    'full_marks' => 100,
                    'pass_marks' => 33,
                    'grade' => 'F', // Mark as failed if no marks
                    'grade_point' => 0.00,
                    'class_max_marks' => getClassMaxMarks($pdo, $subject_id, $session, $exam_type),
                    'is_fourth_subject' => $subject['is_fourth_subject'] ?? false
                ];
                
                // Try to get subject-specific mark distribution
                $stmt = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                $stmt->execute([$subject_id, $student['class_id'], $session, $exam_type]);
                $smd = $stmt->fetch();
                
                if ($smd) {
                    $placeholder_result['full_marks'] = $smd['total_marks'];
                    $placeholder_result['pass_marks'] = $smd['overall_pass_marks'];
                } else {
                    // Fallback to mark_distributions
                    $stmt = $pdo->prepare("SELECT total_marks, pass_marks as overall_pass_marks FROM mark_distributions WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                    $stmt->execute([$subject_id, $student['class_id'], $session, $exam_type]);
                    $md = $stmt->fetch();
                    
                    if ($md) {
                        $placeholder_result['full_marks'] = $md['total_marks'];
                        $placeholder_result['pass_marks'] = $md['overall_pass_marks'];
                    }
                }
                
                // Recalculate grade and grade_point for placeholder result
                $obtained_marks = round($placeholder_result['marks_obtained'] ?? 0);
                $full_marks = $placeholder_result['full_marks'] ?? 100;
                $grade = calculateGradeFromMarks($obtained_marks, $full_marks);
                // Force A+ for Bangla subjects
                if (stripos($placeholder_result['subject_name'], 'বাংলা') !== false ||
                    stripos($placeholder_result['subject_name'], 'Bangla') !== false) {
                    $grade = 'A+';
                }
                $grade_point = getGradePoint($grade);
                
                $placeholder_result['marks_obtained'] = $obtained_marks;
                $placeholder_result['grade'] = $grade;
                $placeholder_result['grade_point'] = $grade_point;
                
                $results[] = $placeholder_result;
                $has_missing_marks = true; // Mark that we have missing marks
            }
        }
        
        // Process combined subjects
        $processed_results = [];
        $original_bangla_results = [];
        $original_english_results = [];
        $other_results = [];
        $combined_subject_ids = [];
        
        // First, collect original Bangla and English results
        foreach ($results as $result) {
            // Check if this is a Bangla subject (Bangla or Bangla Grammar)
            if ((stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) && strpos($result['subject_name'], 'একত্রে') === false) {
                $original_bangla_results[] = $result;
            }
            // Check if this is an English subject (English or English Grammar)
            elseif ((stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) && strpos($result['subject_name'], 'একত্রে') === false) {
                $original_english_results[] = $result;
            } else {
                $other_results[] = $result;
            }
        }
        
        // Process Bangla subjects as a combined subject
        $combined_bangla = null;
        if (!empty($original_bangla_results)) {
            // Combine Bangla and Bangla Grammar into one subject
            $combined_bangla = combineBanglaSubjects($original_bangla_results);
            if ($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) {
                    if (!empty($bangla_result['is_fourth_subject'])) {
                        $is_fourth_subject = true;
                        break;
                    }
                }
                $combined_bangla['is_fourth_subject'] = $is_fourth_subject;
                
                // Apply custom grading for combined Bangla subject
                // For combined Bangla, calculate based on CQ and MCQ averages
                // Calculate total obtained and use the actual full marks from the combined subject
                $total_obtained = $combined_bangla['cq_marks'] + $combined_bangla['mcq_marks'];
                
                // Use the actual full marks calculated in the combineBanglaSubjects function
                $total_full_marks = $combined_bangla['full_marks'] > 0 ? $combined_bangla['full_marks'] : 200; // Default to 200 if not set
                
                // Calculate percentage based on total obtained vs total possible
                $percentage = ($total_obtained / $total_full_marks) * 100;
                
                // Determine grade based on percentage
                if ($percentage >= 80) $custom_grade = 'A+';
                elseif ($percentage >= 70) $custom_grade = 'A';
                elseif ($percentage >= 60) $custom_grade = 'A-';
                elseif ($percentage >= 50) $custom_grade = 'B';
                elseif ($percentage >= 40) $custom_grade = 'C';
                elseif ($percentage >= 33) $custom_grade = 'D';
                else $custom_grade = 'F';
                
                $combined_bangla['grade'] = $custom_grade;
                $combined_bangla['grade_point'] = getGradePoint($custom_grade);
                // Update marks_obtained to reflect the calculated total for proper display
                $combined_bangla['marks_obtained'] = $total_obtained;
                
                $processed_results[] = $combined_bangla;
            }
        }
        
        // Process English subjects as a combined subject
        $combined_english = null;
        if (!empty($original_english_results)) {
            // Combine English and English Grammar into one subject
            $combined_english = combineEnglishSubjects($original_english_results);
            if ($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) {
                    if (!empty($english_result['is_fourth_subject'])) {
                        $is_fourth_subject = true;
                        break;
                    }
                }
                $combined_english['is_fourth_subject'] = $is_fourth_subject;
                
                // Apply custom grading for combined English subject
                // For combined English, calculate based on CQ average
                // Calculate total obtained for percentage calculation
                $total_obtained = $combined_english['cq_marks']; // For English, typically only CQ is considered
                
                // Use the actual full marks calculated in the combineEnglishSubjects function
                $total_full_marks = $combined_english['full_marks'] > 0 ? $combined_english['full_marks'] : 200; // Default to 200 if not set
                
                // Calculate percentage based on total obtained vs total possible
                $percentage = ($total_obtained / $total_full_marks) * 100;
                
                // Determine grade based on percentage
                if ($percentage >= 80) $custom_grade = 'A+';
                elseif ($percentage >= 70) $custom_grade = 'A';
                elseif ($percentage >= 60) $custom_grade = 'A-';
                elseif ($percentage >= 50) $custom_grade = 'B';
                elseif ($percentage >= 40) $custom_grade = 'C';
                elseif ($percentage >= 33) $custom_grade = 'D';
                else $custom_grade = 'F';
                
                $combined_english['grade'] = $custom_grade;
                $combined_english['grade_point'] = getGradePoint($custom_grade);
                // Update marks_obtained to reflect the calculated total for proper display
                $combined_english['marks_obtained'] = $total_obtained;
                
                $processed_results[] = $combined_english;
            }
        }
        
        // Collect subject IDs that have been combined to avoid duplicates
        foreach ($original_bangla_results as $bangla_result) {
            $combined_subject_ids[] = $bangla_result['subject_id'];
        }
        foreach ($original_english_results as $english_result) {
            $combined_subject_ids[] = $english_result['subject_id'];
        }
        
        // Process other subjects (exclude combined subjects)
        foreach ($other_results as $result) {
            // Skip subjects that have been combined
            if (in_array($result['subject_id'], $combined_subject_ids)) {
                continue;
            }
            
            // Enhance with subject-specific marks distribution if needed
            if (!isset($result['full_marks']) || !isset($result['pass_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'];
                    }
                }
            }
            
            // Ensure cq_marks_array and mcq_marks_array are initialized
            if (!isset($result['cq_marks_array']) || !is_array($result['cq_marks_array'])) {
                $result['cq_marks_array'] = [$result['cq_marks']];
            }
            if (!isset($result['mcq_marks_array']) || !is_array($result['mcq_marks_array'])) {
                $result['mcq_marks_array'] = [$result['mcq_marks']];
            }
            
            $processed_results[] = $result;
        }
        
        // Build final results array ensuring no duplicates
        $final_results = [];
        
        // Add combined Bangla if it exists
        if ($combined_bangla) {
            $final_results[] = $combined_bangla;
        }
        
        // Add combined English if it exists
        if ($combined_english) {
            $final_results[] = $combined_english;
        }
        
        // Add other processed results (excluding combined subjects)
        foreach ($other_results as $result) {
            // Skip if this is one of the subjects that was combined
            if (in_array($result['subject_id'], $combined_subject_ids)) {
                continue;
            }
            $final_results[] = $result;
        }
        
        $results = $final_results;
        
        // Separate fourth subjects from regular subjects
        $regular_subjects = array_filter($results, function($result) {
            return empty($result['is_fourth_subject']);
        });

        $fourth_subjects = array_filter($results, function($result) {
            return !empty($result['is_fourth_subject']);
        });

        // Keep results as regular subjects first, fourth subjects will be displayed separately at bottom
        
        // Apply special handling for ICT subjects
        foreach ($results as &$result) {
            // Check if this is an ICT subject (contains 'ICT' or 'আইসিটি' in the name)
            if ((stripos($result['subject_name'], 'ICT') !== false || stripos($result['subject_name'], 'আইসিটি') !== false)) {
                // For ICT subjects, calculate grade based on 50 marks
                $ict_obtained = $result['marks_obtained'] ?? 0;
                $ict_grade = calculateICTGrade($ict_obtained);
                $ict_grade_point = getICTGradePoint($ict_grade);
                
                // Update the result with ICT-specific grade and grade point
                $result['grade'] = $ict_grade;
                $result['grade_point'] = $ict_grade_point;
            }
        }
        unset($result); // Break the reference with the last element
        
        // Calculate GPA with Jessore Board rules
        $gpa = calculateGPA($results);
        // For compatibility with existing display logic, set base_gpa and fourth_subject_bonus to 0
        $base_gpa = $gpa;
        $fourth_subject_bonus = 0.00;
        
        // Calculate totals including 4th subject additional points
        $total_marks = 0;
        $total_obtained = 0;
        $regular_subject_count = 0;
        $fourth_subject_marks = 0;

        foreach ($results as $result) {
            // Include all subjects in total calculation
            $total_marks += $result['full_marks'] ?? 100;
            $total_obtained += $result['marks_obtained'] ?? 0;

            if (empty($result['is_fourth_subject'])) {
                $regular_subject_count++;
            } else {
                $fourth_subject_marks += $result['marks_obtained'] ?? 0;
            }
        }
        
        $percentage = $total_marks > 0 ? round(($total_obtained / $total_marks) * 100, 2) : 0;
        
        // Get merit position based on GPA first, then total marks for tie-breaking
        if ($student && $session && $exam_type) {
            try {
                // Get all students in the same class with their GPAs and total marks
                $stmt = $pdo->prepare(
                    "SELECT s.id, 
                           s.roll_number,
                           SUM(r.marks_obtained) as total_obtained,
                           COUNT(r.student_id) as subject_count
                    FROM students s
                    JOIN results r ON s.id = r.student_id
                    WHERE s.class_id = ? AND r.exam_type = ? AND r.session = ?
                    GROUP BY s.id, s.roll_number
                    ORDER BY s.roll_number"
                );
                $stmt->execute([$class_id, $exam_type, $session]);
                $all_class_results = $stmt->fetchAll();
                        
                // Calculate GPA for each student to determine merit position
                $student_gpas = [];
                foreach ($all_class_results as $class_result) {
                    // Get all results for this student
                    $result_stmt = $pdo->prepare(
                        "SELECT r.*, sub.name as subject_name, sub.code as subject_code, 
                               ss.is_fourth_subject 
                        FROM results r 
                        LEFT JOIN subjects sub ON r.subject_id = sub.id 
                        LEFT JOIN student_subjects ss ON r.subject_id = ss.subject_id AND r.student_id = ss.student_id 
                        WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ? 
                        ORDER BY sub.name"
                    );
                    $result_stmt->execute([$class_result['id'], $session, $exam_type]);
                    $student_results = $result_stmt->fetchAll();
                            
                    // Process subjects for GPA calculation (similar to main calculation)
                    $processed_results = [];
                    foreach ($student_results as $result) {
                        $result['full_marks'] = $result['full_marks'] ?? 100;
                        $result['pass_marks'] = $result['pass_marks'] ?? 33;
                        $result['grade_point'] = getGradePoint($result['grade']);
                        $processed_results[] = $result;
                    }
                            
                    // Calculate GPA for this student
                    $student_gpa = calculateGPA($processed_results);
                    $student_gpas[$class_result['id']] = [
                        'gpa' => $student_gpa,
                        'total_obtained' => $class_result['total_obtained'],
                        'roll_number' => $class_result['roll_number']
                    ];
                }
                        
                // Sort students by GPA (descending), then by total marks (descending) for tie-breaking
                uasort($student_gpas, function($a, $b) {
                    // First, sort by GPA (descending)
                    if ($a['gpa'] != $b['gpa']) {
                        return $b['gpa'] <=> $a['gpa'];
                    }
                    // If GPAs are equal, sort by total obtained marks (descending)
                    return $b['total_obtained'] <=> $a['total_obtained'];
                });
                        
                // Find the position of current student
                $position = 1;
                $current_student_found = false;
                foreach ($student_gpas as $student_id => $data) {
                    if ($student_id == $student['id']) {
                        $merit_position = $position;
                        $current_student_found = true;
                        break;
                    }
                    $position++;
                }
                        
                // If student wasn't found in results, merit position remains null
                if (!$current_student_found) {
                    $merit_position = null;
                }
            } catch (Exception $e) {
                // Merit position calculation failed, continue without it
                error_log("Merit position calculation failed: " . $e->getMessage());
            }
        }
    }
}

// Get available classes, sessions and exam types for the search form
$classes_stmt = $pdo->query("SELECT DISTINCT c.name FROM classes c JOIN students s ON c.id = s.class_id ORDER BY c.name");
$all_classes = $classes_stmt->fetchAll(PDO::FETCH_COLUMN);

$sessions_stmt = $pdo->query("SELECT DISTINCT session FROM results ORDER BY session DESC");
$all_sessions = $sessions_stmt->fetchAll(PDO::FETCH_COLUMN);

$exam_types_stmt = $pdo->query("SELECT DISTINCT exam_type FROM results ORDER BY exam_type");
$all_exam_types = $exam_types_stmt->fetchAll(PDO::FETCH_COLUMN);
?>

<!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;
            background-color: #f8f9fa;
        }
        
        .search-container {
            max-width: 800px;
            margin: 30px auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            padding: 30px;
        }
        
        .marksheet {
            border: 2px solid #2c3e50;
            padding: 15px;
            margin: 15px auto;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            max-width: 800px;
            position: relative;
            overflow: hidden;
        }
        
        .school-header {
            text-align: center;
            border-bottom: 2px double #3498db;
            padding-bottom: 10px;
            margin-bottom: 15px;
            background: linear-gradient(to right, #ffffff, #e3f2fd, #ffffff);
            border-radius: 6px 6px 0 0;
            margin-left: -15px;
            margin-right: -15px;
            padding-left: 15px;
            padding-right: 15px;
            position: relative;
        }
        
        .school-logo {
            width: 60px;
            height: 60px;
            border: 2px solid #3498db;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 8px;
            background: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .school-header h3 {
            color: #2c3e50;
            font-weight: 700;
            margin: 8px 0 3px 0;
            text-shadow: 1px 1px 1px rgba(0,0,0,0.1);
            font-size: 20px;
        }
        
        .school-header h4 {
            color: #e74c3c;
            font-weight: 600;
            margin: 10px 0 0 0;
            text-decoration: underline;
            text-underline-offset: 5px;
            font-size: 16px;
        }
        
        .student-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 15px;
            background: #f8f9fa;
            padding: 12px;
            border-radius: 6px;
            border: 1px solid #e9ecef;
        }
        
        .info-row {
            display: flex;
            margin-bottom: 5px;
            align-items: center;
        }
        
        .info-label {
            font-weight: 600;
            min-width: 100px;
            color: #2c3e50;
            font-size: 12px;
        }
        
        .info-value {
            border-bottom: 1px dotted #3498db;
            flex: 1;
            padding-left: 8px;
            font-weight: 500;
            color: #34495e;
            font-size: 12px;
        }
        
        .marks-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
            border-radius: 6px;
            overflow: hidden;
            font-size: 11px;
        }
        
        .marks-table th,
        .marks-table td {
            border: 1px solid #dee2e6;
            padding: 6px;
            text-align: center;
            font-size: 11px;
        }
        
        .marks-table th {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }
        
        .marks-table tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .marks-table tbody tr:hover {
            background-color: #e3f2fd;
            transition: background-color 0.2s;
        }
        
        .result-summary {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px dashed #3498db;
            background: #f8f9fa;
            padding: 12px;
            border-radius: 6px;
        }
        
        .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;
            padding-top: 8px;
            margin-top: 20px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 12px;
        }
        
        .grade-scale {
            font-size: 9px;
            margin-top: 20px;
            padding: 10px;
            background: #e3f2fd;
            border-radius: 6px;
            border-left: 2px solid #3498db;
        }
        
        .grade-scale strong {
            color: #2c3e50;
        }
        
        @media print {
            .no-print { display: none !important; }
            .container { max-width: 100% !important; }
            body { 
                font-size: 10px;
                font-family: 'Hind Siliguri', sans-serif;
                background-color: white;
            }
            .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;
                -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;
                box-shadow: none;
                width: 50px;
                height: 50px;
                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 {
                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;
            }
        }
        
        .alert-box {
            max-width: 800px;
            margin: 30px auto;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
        
        .back-button {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <?php if ($student && empty($publication_message)): ?>
        <!-- Marksheet View -->
        <div class="text-center mb-3 no-print">
            <button onclick="history.back()" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> পেছনে</button>
            <button onclick="window.print()" class="btn btn-success"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
            <a href="jessore_board_ssc_bangla_english_marksheet.php" class="btn btn-primary"><i class="fas fa-search"></i> নতুন অনুসন্ধান</a>
            <a href="index.php" class="btn btn-info"><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: 60px; 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>
                        <p style="margin: 5px 0 0 0; font-size: 14px;">বাংলা ও ইংরেজি বিষয়</p>
                    </div>
                    
                    <!-- Student Photo - Right -->
                    <div style="text-align: right;" class="student-photo">
                        <?php if (!empty($student['photo']) && file_exists($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: 200px; height: 200px; object-fit: contain;">
                </div>
            <?php endif; ?>
            
            <div class="student-info">
                <div>
                    <div class="info-row">
                        <div class="info-label">শিক্ষার্থী আইডি</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['student_id']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পিতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['father_name'] ?? ''); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">মাতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['mother_name'] ?? ''); ?></div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">রোল নম্বর</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['roll_number']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শ্রেণী</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['class_name'] . ' ' . $student['section']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">সেশন</div>
                        <div class="info-value"><?php echo htmlspecialchars($session); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পরীক্ষার ধরন</div>
                        <div class="info-value"><?php echo htmlspecialchars(ucfirst($exam_type)); ?></div>
                    </div>
                </div>
            </div>
            
            <table class="marks-table">
                <thead>
                    <tr>
                        <th rowspan="2">বিষয়</th>
                        <th colspan="5">প্রাপ্ত নম্বর</th>
                        <th rowspan="2">সর্বোচ্চ<br>নম্বর</th>
                        <th rowspan="2">প্রাপ্ত<br>নম্বর</th>
                        <th rowspan="2">পাস<br>নম্বর</th>
                        <th rowspan="2">গ্রেড</th>
                        <th rowspan="2">জিপি</th>
                    </tr>
                    <tr>
                        <th>সৃজনশীল</th>
                        <th>বহুনির্বাচনি</th>
                        <th>ব্যবহারিক</th>
                        <th>অ্যাসাইনমেন্ট</th>
                        <th>উপস্থিতি</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Display regular subjects first
                    foreach ($regular_subjects as $result):
                    ?>
                    <tr>
                        <td style="text-align: left; padding-left: 15px; font-weight: 500;">
                            <?php echo htmlspecialchars($result['subject_name'] ?? 'Unknown Subject'); ?>
                        </td>
                        <td>
                            <?php
                            if (isset($result['cq_marks_array']) && is_array($result['cq_marks_array'])) {
                                // Apply floor to each CQ mark to ensure whole numbers
                                $floored_cq_marks = array_map('floor', $result['cq_marks_array']);
                                echo htmlspecialchars(implode(', ', $floored_cq_marks) ?: '-');
                            } else {
                                echo htmlspecialchars(floor($result['cq_marks']) ?: '-');
                            }
                            ?>
                        </td>
                        <td>
                            <?php
                            if (isset($result['mcq_marks_array']) && is_array($result['mcq_marks_array'])) {
                                // Apply floor to each MCQ mark to ensure whole numbers
                                $floored_mcq_marks = array_map('floor', $result['mcq_marks_array']);
                                echo htmlspecialchars(implode(', ', $floored_mcq_marks) ?: '-');
                            } 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 htmlspecialchars($result['attendance_marks'] ?: '-'); ?></td>
                        <td>
                            <?php
                            // Display the highest marks for the subject
                            // For ICT subjects, show 50 as the full marks
                            if ((stripos($result['subject_name'], 'ICT') !== false || stripos($result['subject_name'], 'আইসিটি') !== false)) {
                                echo '50';
                            } else {
                                echo htmlspecialchars(floor($result['class_max_marks'] ?? 0));
                            }
                            ?>
                        </td>
                        <td style="font-weight: 600;"><?php echo htmlspecialchars(floor($result['marks_obtained'] ?? 0)); ?></td>
                        <td><?php echo htmlspecialchars($result['pass_marks'] ?? '-'); ?></td>
                        <td style="font-weight: 700;
                            <?php
                            switch ($result['grade'] ?? 'F') {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo htmlspecialchars($result['grade'] ?? 'F'); ?>
                        </td>
                        <td><?php echo number_format($result['grade_point'] ?? 0.00, 2); ?></td>
                    </tr>
                    <?php endforeach; ?>

                    <?php if (!empty($fourth_subjects)): ?>
                    <!-- Separator row for fourth subject -->
                    <tr style="background-color: #f8f9fa; border-top: 2px solid #dee2e6;">
                        <td colspan="12" style="text-align: center; font-weight: bold; color: #495057; padding: 8px;">
                            ৪র্থ বিষয় (অতিরিক্ত)
                        </td>
                    </tr>

                    <?php foreach ($fourth_subjects as $result): ?>
                    <tr style="background-color: #fff3cd; border: 2px solid #ffc107;">
                        <td style="text-align: left; padding-left: 15px; font-weight: 500;">
                            <?php echo htmlspecialchars($result['subject_name'] ?? 'Unknown Subject'); ?>
                            <span style="color: #856404; font-weight: bold;">(৪র্থ বিষয়)</span>
                        </td>
                        <td>
                            <?php
                            if (isset($result['cq_marks_array']) && is_array($result['cq_marks_array'])) {
                                // Apply floor to each CQ mark to ensure whole numbers
                                $floored_cq_marks = array_map('floor', $result['cq_marks_array']);
                                echo htmlspecialchars(implode(', ', $floored_cq_marks) ?: '-');
                            } else {
                                echo htmlspecialchars(floor($result['cq_marks']) ?: '-');
                            }
                            ?>
                        </td>
                        <td>
                            <?php
                            if (isset($result['mcq_marks_array']) && is_array($result['mcq_marks_array'])) {
                                // Apply floor to each MCQ mark to ensure whole numbers
                                $floored_mcq_marks = array_map('floor', $result['mcq_marks_array']);
                                echo htmlspecialchars(implode(', ', $floored_mcq_marks) ?: '-');
                            } 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 htmlspecialchars($result['attendance_marks'] ?: '-'); ?></td>
                        <td>
                            <?php
                            // Display the highest marks for the subject
                            // For ICT subjects, show 50 as the full marks
                            if ((stripos($result['subject_name'], 'ICT') !== false || stripos($result['subject_name'], 'আইসিটি') !== false)) {
                                echo '50';
                            } else {
                                echo htmlspecialchars(floor($result['class_max_marks'] ?? 0));
                            }
                            ?>
                        </td>
                        <td style="font-weight: 600;"><?php echo htmlspecialchars(floor($result['marks_obtained'] ?? 0)); ?></td>
                        <td><?php echo htmlspecialchars($result['pass_marks'] ?? '-'); ?></td>
                        <td style="font-weight: 700;
                            <?php
                            switch ($result['grade'] ?? 'F') {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo htmlspecialchars($result['grade'] ?? 'F'); ?>
                        </td>
                        <td><?php echo number_format($result['grade_point'] ?? 0.00, 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                    <!-- GPA Summary Row -->
                    <tr style="background-color: #e3f2fd; font-weight: bold;">
                        <td colspan="9" style="text-align: right; padding-right: 15px;">চূড়ান্ত জিপিএ (Grade Point Average):</td>
                        <td><?php echo number_format($gpa, 2); ?></td>
                    </tr>
                </tbody>
            </table>
            
            <div class="result-summary">
                <div>
                    <div class="info-row">
                        <div class="info-label">মোট নম্বর (সকল বিষয়)</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo $total_obtained; ?>/<?php echo $total_marks; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শতাংশ (সকল বিষয়)</div>
                        <div class="info-value" style="font-weight: 700; color: #3498db;"><?php echo $percentage; ?>%</div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">গ্রেড</div>
                        <div class="info-value" style="font-weight: 700; font-size: 18px;
                            <?php
                            // Calculate grade based on Bangla marks only
                            $bangla_english_grade = calculateGradeFromBanglaEnglishAverage($results);

                            // Debug info - show in grade text
                            global $debug_bangla_info;
                            $debug_text = "";
                            if (isset($debug_bangla_info) && !empty($debug_bangla_info)) {
                                $debug_text = " ($debug_bangla_info)";
                            }

                            switch ($bangla_english_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 $bangla_english_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($base_gpa, 2); ?></div>
                    </div>
                    <?php if ($fourth_subject_bonus > 0): ?>
                    <div class="info-row">
                        <div class="info-label">৪র্থ বিষয় অবদান (+<?php echo number_format($fourth_subject_bonus, 2); ?>)</div>
                        <div class="info-value" style="font-weight: 700; color: #27ae60;">+<?php echo number_format($fourth_subject_bonus, 2); ?></div>
                    </div>
                    <?php endif; ?>
                    <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 
                    // Count regular and 4th subjects
                    $regular_count = 0;
                    $fourth_count = 0;
                    foreach ($results as $result) {
                        if (!empty($result['is_fourth_subject'])) {
                            $fourth_count++;
                        } else {
                            $regular_count++;
                        }
                    }
                    ?>
                    <div class="info-row">
                        <div class="info-label">বিষয়সমূহ</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;">
                            <?php echo $regular_count; ?> টি সাধারণ + <?php echo $fourth_count; ?> টি ৪র্থ বিষয় (সকল বিষয় অন্তর্ভুক্ত)
                        </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 class="grade-scale">
                <strong>গ্রেড স্কেল:</strong> A+ (80%-100%), A (70%-79%), A- (60%-69%), B (50%-59%), C (40%-49%), D (33%-39%), F (0%-32%)
                <br><strong>দ্রষ্টব্য:</strong> আইসিটি বিষয়টি ৫০ নম্বরের ভিত্তিতে গ্রেড করা হয়
            </div>
        </div>
        
        <?php elseif (!empty($publication_message)): ?>
        <!-- Publication Message -->
        <div class="alert alert-warning alert-box">
            <h4><i class="fas fa-exclamation-triangle"></i> নোটিশ</h4>
            <p><?php echo htmlspecialchars($publication_message); ?></p>
            <a href="jessore_board_ssc_bangla_english_marksheet.php" class="btn btn-primary"><i class="fas fa-search"></i> আবার চেষ্টা করুন</a>
            <a href="index.php" class="btn btn-info"><i class="fas fa-home"></i> হোম</a>
        </div>
        
        <?php else: ?>
        <!-- Search Form -->
        <div class="search-container">
            <h2 class="text-center mb-4">যশোর বোর্ড এসএসসি বাংলা & ইংরেজি মার্কশীট</h2>
            
            <form method="GET" action="" class="row g-3">
                <div class="col-md-6">
                    <label for="class" class="form-label">শ্রেণী</label>
                    <select id="class" name="class" class="form-select" required>
                        <option value="">শ্রেণী নির্বাচন করুন</option>
                        <?php foreach ($all_classes as $class_item): ?>
                            <option value="<?php echo htmlspecialchars($class_item); ?>" <?php echo ($class_name == $class_item) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($class_item); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-6">
                    <label for="session" class="form-label">সেশন</label>
                    <select id="session" name="session" class="form-select" required>
                        <option value="">সেশন নির্বাচন করুন</option>
                        <?php foreach ($all_sessions as $session_item): ?>
                            <option value="<?php echo htmlspecialchars($session_item); ?>" <?php echo ($session == $session_item) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($session_item); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-6">
                    <label for="exam" class="form-label">পরীক্ষার ধরন</label>
                    <select id="exam" name="exam" class="form-select" required>
                        <option value="">পরীক্ষা নির্বাচন করুন</option>
                        <?php foreach ($all_exam_types as $exam_type_item): ?>
                            <option value="<?php echo htmlspecialchars($exam_type_item); ?>" <?php echo ($exam_type == $exam_type_item) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($exam_type_item); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-6">
                    <label for="roll" class="form-label">রোল নম্বর</label>
                    <input type="text" id="roll" name="roll" class="form-control" value="<?php echo htmlspecialchars($roll); ?>" placeholder="রোল নম্বর লিখুন" required>
                </div>
                
                <div class="col-12 text-center">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas fa-search"></i> মার্কশীট দেখুন
                    </button>
                    <a href="index.php" class="btn btn-secondary btn-lg">
                        <i class="fas fa-home"></i> হোম
                    </a>
                </div>
            </form>
        </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>