<?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, $student_id) {
    $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'] ?? false)) {
                $fourth_subject_found = true;
                $fourth_subject_grade_point = $grade_point;
                // For 4th subject: add only the bonus points (grade_point - 2.00) if grade_point > 2.00
                // Otherwise, add 0 bonus points
                if ($grade_point > 2.00) {
                    $total_grade_points += ($grade_point - 2.00);
                }
            } else {
                // Regular subject - add full grade point
                $total_grade_points += $grade_point;
            }
            $gpa_subjects++; // Count subjects for GPA calculation
        } else {
            // Student failed in this subject
            if (empty($result['is_fourth_subject']) || !($result['is_fourth_subject'] ?? false)) {
                // Failed in a non-fourth subject
                $has_failed_in_non_fourth_subject = true;
            }
        }
    }
    
    // GPA is 0.00 if student failed in any non-fourth subject
    if ($has_failed_in_non_fourth_subject) {
        return 0.00;
    }
    
    // If no subjects for GPA calculation, return 0.00
    if ($gpa_subjects == 0) {
        return 0.00;
    }
    
    // Calculate GPA (Grade Point Average) with Jessore Board rules
    // For Jessore Board: when 4th subject exists, divide by (number of subjects - 1)
    // because 4th subject's extra points are added but the subject itself is not counted in division
    if ($fourth_subject_found) {
        // When 4th subject exists, divide by (gpa_subjects - 1)
        // because 4th subject is not counted in the division
        // Prevent division by zero when student has only one subject which is a fourth subject
        $divisor = ($gpa_subjects - 1) > 0 ? ($gpa_subjects - 1) : 1;
        $gpa = $total_grade_points / $divisor;
    } else {
        // Normal calculation
        $gpa = $total_grade_points / $gpa_subjects;
    }
    
    // Apply Jessore Board 4th subject rule: If 4th subject exists and GPA > 5.00, cap it at 5.00
    if ($fourth_subject_found && $gpa > 5.00) {
        $gpa = 5.00;
    }
    
    // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
    if ($gpa > 5.00) {
        $gpa = 5.00;
    }
    
    return round($gpa, 2);
}

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

// Function to calculate English grade (custom rules)
function calculateEnglishGrade($cq_marks_array, $full_marks, $pass_marks) {
    // Calculate average of 2 CQ marks
    $cq_average = 0;
    if (count($cq_marks_array) >= 2) {
        $cq_average = ($cq_marks_array[0] + $cq_marks_array[1]) / 2;
    } else if (count($cq_marks_array) == 1) {
        $cq_average = $cq_marks_array[0];
    }
    
    // For English: CQ average > 32 to pass
    if ($cq_average > 32) {
        // Calculate percentage based on total marks
        $percentage = ($cq_average / $full_marks) * 100;
        
        if ($percentage >= 80) return 'A+';
        elseif ($percentage >= 70) return 'A';
        elseif ($percentage >= 60) return 'A-';
        elseif ($percentage >= 50) return 'B';
        elseif ($percentage >= 40) return 'C';
        elseif ($percentage >= 33) return 'D';
        else return 'F';
    } else {
        // If criteria not met, return F
        return 'F';
    }
}

// Function to calculate 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';
        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;
    }
    
    // Calculate obtained marks as sum of averaged CQ and MCQ
    $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
    
    // Average full and pass marks over total Bangla results
    $total_count = count($bangla_results);
    if ($total_count > 0) {
        $combined['full_marks'] = $combined['full_marks'] / $total_count;
        $combined['pass_marks'] = $combined['pass_marks'] / $total_count;
    }
    
    return $combined;
}

// Function to combine English subjects
function combineEnglishSubjects($english_results) {
    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);
    }
    
    // Average the marks for proper grading
    $count = count($english_results);
    if ($count > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $count;
        $combined['mcq_marks'] = $combined['mcq_marks'] / $count;
        // For English: obtained marks = CQ average + MCQ average (as per user requirement)
        $combined['marks_obtained'] = $combined['cq_marks'] + $combined['mcq_marks'];
        $combined['full_marks'] = $combined['full_marks'] / $count;
        $combined['pass_marks'] = $combined['pass_marks'] / $count;
    }
    
    return $combined;
}

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

// Check if bulk print all flag is set
$bulk_print_all = isset($_GET['bulk_print_all']) && $_GET['bulk_print_all'] == 1;

// Get parameters
$class_id = $_GET['class_id'] ?? '';
$session = $_GET['session'] ?? '';
$exam_type = $_GET['exam_type'] ?? '';
$student_search = $_GET['student_search'] ?? '';
$student_id = $_GET['student_id'] ?? '';
$show_merit_position = isset($_GET['show_merit_position']) ? (bool)$_GET['show_merit_position'] : true; // Default to true

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

// Get classes for dropdown
$stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
$classes = $stmt->fetchAll();

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

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

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

// If parameters are missing, we'll show the search form (don't die with error)

try {
    // Get students in class
    $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.class_id = ? AND s.status = 'active'
        AND EXISTS (
            SELECT 1 FROM results r 
            WHERE r.student_id = s.id 
            AND r.session = ? 
            AND r.exam_type = ?
        )
        ORDER BY s.roll_number ASC
    ");
    $stmt->execute([$class_id, $session, $exam_type]);
    $students = $stmt->fetchAll();
    
    // Filter students if search term is provided
    if ($student_search) {
        $students = array_filter($students, function($student) use ($student_search) {
            return stripos($student['first_name'] . ' ' . $student['last_name'], $student_search) !== false ||
                   stripos($student['student_id'], $student_search) !== false ||
                   stripos($student['roll_number'], $student_search) !== false;
        });
    }
    
    // Process all students when class_id, session, and exam_type are provided
    if ($class_id && $session && $exam_type) {
        $students_to_process = $students;
    } else {
        // Otherwise, process only the first student for testing
        $students_to_process = array_slice($students, 0, 1);
    }
    
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}
?>
<!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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        @import url('https://fonts.maateen.me/kalpurush/font.css');
        @import url('https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap');
        
        /* Student photo styles */
        .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);
        }
        
        /* Print styles */
        @media print {
            .student-photo-print {
                display: block !important;
            }
            
            /* Hide back and print buttons when printing */
            .back-button, .print-button {
                display: none !important;
            }
        }
        
        body {
            font-family: 'Hind Siliguri', 'Kalpurush', Arial, sans-serif;
            background-color: #f8f9fa;
            margin: 0;
            padding: 20px;
        }
        
        * {
            font-family: 'Hind Siliguri', 'Kalpurush', Arial, sans-serif;
        }
        
        .marksheets-container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .marksheet {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            padding: 20px;
            page-break-after: always;
        }
        
        .header {
            text-align: center;
            margin-bottom: 20px;
            border-bottom: 2px solid #333;
            padding-bottom: 15px;
        }
        
        .school-logo {
            max-height: 80px;
            margin-bottom: 10px;
        }
        
        .school-name {
            font-size: 28px;
            font-weight: bold;
            color: #2c3e50;
            margin: 5px 0;
        }
        
        .school-address {
            font-size: 18px;
            color: #7f8c8d;
            margin: 5px 0;
        }
        
        .exam-info {
            background-color: #ecf0f1;
            border-radius: 8px;
            padding: 15px;
            margin: 20px 0;
        }
        
        .student-info {
            display: flex;
            justify-content: space-between;
            margin: 20px 0;
            flex-wrap: wrap;
        }
        
        .info-section {
            flex: 1;
            min-width: 250px;
            margin: 10px;
        }
        
        .info-row {
            display: flex;
            margin-bottom: 8px;
        }
        
        .info-label {
            font-weight: bold;
            width: 120px;
            color: #2c3e50;
        }
        
        .info-value {
            flex: 1;
            color: #34495e;
        }
        
        .marks-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            font-size: 14px;
        }
        
        .marks-table th,
        .marks-table td {
            border: 1px solid #333;
            padding: 8px;
            text-align: center;
        }
        
        .marks-table th {
            background-color: #3498db;
            color: white;
            font-weight: bold;
        }
        

        .marks-table tfoot th {
            background-color: #2c3e50;
            color: white;
        }
        
        .result-summary {
            display: flex;
            justify-content: space-between;
            margin: 30px 0;
            flex-wrap: wrap;
        }
        
        .signature-section {
            display: flex;
            justify-content: space-between;
            margin-top: 50px;
            flex-wrap: wrap;
        }
        
        .signature-box {
            text-align: center;
            flex: 1;
            min-width: 150px;
            margin: 10px;
        }
        
        @media print {
            body {
                padding: 0;
                margin: 0;
            }
            
            .marksheets-container {
                max-width: 100%;
                margin: 0;
            }
            
            .marksheet {
                box-shadow: none;
                margin-bottom: 0;
                border-radius: 0;
                padding: 10px;
            }
            
            /* Hide buttons when printing */
            .back-button, .print-button {
                display: none !important;
            }
            
            @page {
                margin: 0.5cm;
            }
        }
        
        .back-button {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
        }
        
        .print-button {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    
    <div class="back-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); ?>&student_search=<?php echo urlencode($student_search); ?>&show_merit_position=<?php echo $show_merit_position ? '1' : '0'; ?>" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> পিছনে
        </a>
    </div>
    
    <div class="print-button">
        <button class="btn btn-primary" onclick="window.print()">
            <i class="fas fa-print"></i> প্রিন্ট করুন
        </button>
    </div>
    
    <div class="marksheets-container">
        <?php if ($class_id && $session && $exam_type): ?>
    <?php 
    // Process the search and show results
    try {
        // Get students in class
        $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.class_id = ? AND s.status = 'active'
            AND EXISTS (
                SELECT 1 FROM results r 
                WHERE r.student_id = s.id 
                AND r.session = ? 
                AND r.exam_type = ?
            )
            ORDER BY s.roll_number ASC
        ");
        $stmt->execute([$class_id, $session, $exam_type]);
        $students = $stmt->fetchAll();
        
        // Filter students if search term is provided
        if ($student_search) {
            $students = array_filter($students, function($student) use ($student_search) {
                return stripos($student['first_name'] . ' ' . $student['last_name'], $student_search) !== false ||
                       stripos($student['student_id'], $student_search) !== false ||
                       stripos($student['roll_number'], $student_search) !== false;
            });
        }
        
        // Process all students when parameters are provided
        if ($class_id && $session && $exam_type) {
            $students_to_process = $students;
        } else {
            // Otherwise, process only the first student for testing
            $students_to_process = array_slice($students, 0, 1);
        }
        
    } catch (PDOException $e) {
        die("Database error: " . $e->getMessage());
    }
    ?>
    
    <?php foreach ($students_to_process as $student): ?>
        <?php
        // Get student results
        try {
            // 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();
            
            // Debug: Check what subjects this student has
            /*
            echo "<pre>DEBUG: Student ID " . $student['id'] . " - " . $student['first_name'] . " " . $student['last_name'] . "\n";
            foreach ($all_student_subjects as $subj) {
                echo "  Subject: " . $subj['subject_name'] . " (ID: " . $subj['subject_id'] . ") - Fourth: " . ($subj['is_fourth_subject'] ?? 'null') . "\n";
            }
            echo "</pre>";
            */
            
            // Get results for the student - FIXED to avoid duplicates
            $stmt = $pdo->prepare("SELECT r.*, sub.name as subject_name, sub.code as subject_code FROM results r LEFT JOIN subjects sub ON r.subject_id = sub.id WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ? AND r.id IN (SELECT MAX(id) FROM results WHERE student_id = ? AND session = ? AND exam_type = ? GROUP BY subject_id) ORDER BY sub.name");
            $stmt->execute([$student['id'], $session, $exam_type, $student['id'], $session, $exam_type]);
            $results_with_marks = $stmt->fetchAll();
            
            // Create a map of results by subject_id for easy lookup
            $results_map = [];
            foreach ($results_with_marks as $result) {
                $results_map[$result['subject_id']] = $result;
            }
            
            // Create combined results array with all subjects
            $results = [];
            $has_missing_marks = false; // Track if any subject is missing marks
            
            foreach ($all_student_subjects as $subject) {
                $subject_id = $subject['subject_id'];
                
                // If student has marks for this subject, use the result data
                if (isset($results_map[$subject_id])) {
                    // Ensure cq_marks_array and mcq_marks_array are initialized for all subjects
                    $result_data = $results_map[$subject_id];
                    if (!isset($result_data['cq_marks_array'])) {
                        $result_data['cq_marks_array'] = [$result_data['cq_marks']];
                    }
                    if (!isset($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;
                    
                    // Calculate obtained marks (ensure it's a whole number)
                    $obtained_marks = round($result_data['marks_obtained'] ?? 0);
                    $full_marks = $result_data['full_marks'] ?? 100;
                    
                    // Calculate grade and grade_point 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' => [0],
                        'mcq_marks' => 0,
                        'mcq_marks_array' => [0],
                        'practical_marks' => 0,
                        'assignment_marks' => 0,
                        'attendance_marks' => 0,
                        'marks_obtained' => 0,
                        'full_marks' => 100,
                        'pass_marks' => 33,
                        'grade' => 'F', // Mark as failed if no marks
                        'grade_point' => 0.00,
                        'class_max_marks' => 0,
                        'is_fourth_subject' => $subject['is_fourth_subject'] ?? false
                    ];
                    
                    // Try to get subject-specific mark distribution
                    $stmt = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                    $stmt->execute([$subject_id, $student['class_id'], $session, $exam_type]);
                    $smd = $stmt->fetch();
                    
                    if ($smd) {
                        $placeholder_result['full_marks'] = $smd['total_marks'];
                        $placeholder_result['pass_marks'] = $smd['overall_pass_marks'];
                    } else {
                        // Fallback to mark_distributions
                        $stmt = $pdo->prepare("SELECT total_marks, pass_marks as overall_pass_marks FROM mark_distributions WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                        $stmt->execute([$subject_id, $student['class_id'], $session, $exam_type]);
                        $md = $stmt->fetch();
                        
                        if ($md) {
                            $placeholder_result['full_marks'] = $md['total_marks'];
                            $placeholder_result['pass_marks'] = $md['overall_pass_marks'];
                        }
                    }
                    
                    // 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);
                    $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 1st/2nd Paper)
                if (((stripos($result['subject_name'], 'বাংলা') !== false && stripos($result['subject_name'], 'পত্র') !== false) || (stripos($result['subject_name'], 'Bangla') !== false && stripos($result['subject_name'], 'Paper') !== false)) && strpos($result['subject_name'], 'একত্রে') === false) {
                    $original_bangla_results[] = $result;
                }
                // Check if this is an English subject (English 1st/2nd Paper)
                elseif ((stripos($result['subject_name'], 'ইংরেজি') !== false || (stripos($result['subject_name'], 'English') !== false && stripos($result['subject_name'], 'Paper') !== 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) {
                        $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) {
                            $isFourthValue = $subject_info['is_fourth_subject'];
                            if ($isFourthValue === true || $isFourthValue === 1 || $isFourthValue === '1' || $isFourthValue === 'true') {
                                $is_fourth_subject = true;
                                break;
                            }
                        }
                    }
                    $combined_bangla['is_fourth_subject'] = $is_fourth_subject;                    
                    // Apply custom grading for combined Bangla subject
                    $custom_grade = calculateBanglaGrade($combined_bangla['cq_marks_array'], $combined_bangla['mcq_marks'], $combined_bangla['full_marks'], $combined_bangla['pass_marks']);
                    $combined_bangla['grade'] = $custom_grade;
                    $combined_bangla['grade_point'] = getGradePoint($custom_grade);
                    
                    // $processed_results[] = $combined_bangla; // Preventing duplicate - combined subject added to final_results explicitly
                }
            }
            
            // 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) {
                        $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) {
                            $isFourthValue = $subject_info['is_fourth_subject'];
                            if ($isFourthValue === true || $isFourthValue === 1 || $isFourthValue === '1' || $isFourthValue === 'true') {
                                $is_fourth_subject = true;
                                break;
                            }
                        }
                    }
                    $combined_english['is_fourth_subject'] = $is_fourth_subject;
                    
                    // Apply custom grading for combined English subject
                    $custom_grade = calculateEnglishGrade($combined_english['cq_marks_array'], $combined_english['full_marks'], $combined_english['pass_marks']);
                    $combined_english['grade'] = $custom_grade;
                    $combined_english['grade_point'] = getGradePoint($custom_grade);
                    
                   // $processed_results[] = $combined_english; // Preventing duplicate - combined subject added to final_results explicitly
                }
            }
            
            // 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
                $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'];
                    }
                }
                
                // 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([$student['id'], $result['subject_id']]);
                $subject_info = $stmt->fetch();
                
                // Handle different possible values for is_fourth_subject
                if ($subject_info) {
                    $isFourthValue = $subject_info['is_fourth_subject'];
                    $result['is_fourth_subject'] = ($isFourthValue === true || $isFourthValue === 1 || $isFourthValue === '1' || $isFourthValue === 'true');
                } else {
                    $result['is_fourth_subject'] = false;
                }
                
                // Calculate grade and grade_point from marks for regular subjects
                $obtained_marks = round($result['marks_obtained'] ?? 0);
                $full_marks = $result['full_marks'] ?? 100;
                
                // Calculate grade and grade_point from marks
                $grade = calculateGradeFromMarks($obtained_marks, $full_marks);
                $grade_point = getGradePoint($grade);
                
                // Update the result data with calculated values
                $result['marks_obtained'] = $obtained_marks; // Ensure whole number
                $result['grade'] = $grade;
                $result['grade_point'] = $grade_point;
                
                // Ensure cq_marks_array and mcq_marks_array are initialized for all subjects
                if (!isset($result['cq_marks_array'])) {
                    $result['cq_marks_array'] = [$result['cq_marks']];
                }
                if (!isset($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 ($processed_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;
            // Remove duplicate subjects from results array to prevent display duplication
$unique_results = [];
$seen_subject_ids = [];
foreach ($results as $result) {
    if (!in_array($result['subject_id'], $seen_subject_ids)) {
        $unique_results[] = $result;
        $seen_subject_ids[] = $result['subject_id'];
    }
}
$results = $unique_results;
            
            // Separate fourth subjects from regular subjects
            $regular_subjects = array_filter($results, function($result) {
                // Check if is_fourth_subject is set and is true (handle different data types)
                $isFourth = $result['is_fourth_subject'] ?? false;
                // Handle different possible values (1, '1', true, 'true')
                return !($isFourth === true || $isFourth === 1 || $isFourth === '1' || $isFourth === 'true');
            });
            
            $fourth_subjects_only = array_filter($results, function($result) {
                // Check if is_fourth_subject is set and is true (handle different data types)
                $isFourth = $result['is_fourth_subject'] ?? false;
                // Handle different possible values (1, '1', true, 'true')
                return ($isFourth === true || $isFourth === 1 || $isFourth === '1' || $isFourth === 'true');
            });
            
            // Debug: Show which subjects are identified as fourth subjects
            /*
            echo "<pre>DEBUG: Final fourth subjects for student ID " . $student['id'] . ":\n";
            foreach ($fourth_subjects_only as $fs) {
                echo "  Subject: " . $fs['subject_name'] . " - is_fourth_subject: " . ($fs['is_fourth_subject'] ?? 'null') . "\n";
            }
            echo "</pre>";
            */
            
            // Debug: Show what subjects are considered fourth subjects
            /*
            echo "<pre>DEBUG: Fourth subjects for student ID " . $student['id'] . ":\n";
            foreach ($fourth_subjects_only as $fs) {
                echo "Subject: " . $fs['subject_name'] . " (ID: " . $fs['subject_id'] . ") - is_fourth_subject: " . ($fs['is_fourth_subject'] ?? 'undefined') . "\n";
            }
            echo "</pre>";
            */
            
            // Calculate totals for regular subjects
            $total_marks = 0;
            $total_obtained = 0;
            $total_subjects = count($regular_subjects);
            $passed_subjects = 0;
            
            foreach ($regular_subjects as $result) {
                $total_marks += $result['full_marks'] ?? 100;
                $total_obtained += $result['marks_obtained'] ?? 0;
                
                if (($result['grade'] ?? '') != 'F') {
                    $passed_subjects++;
                }
            }
            
            // Calculate GPA with Jessore Board 4th subject rules using all subjects
            $gpa = calculateGPA($results, $student['id']);
            
            // Calculate percentage
            $percentage = $total_marks > 0 ? ($total_obtained / $total_marks) * 100 : 0;
            $percentage = round($percentage, 2);
            
            // Get merit position (only if enabled)
            $merit_position = null;
            // For debugging: uncomment the next line to test if merit position display works
            // $merit_position = 5; // Test value
            if ($show_merit_position) {
                try {
                    // Calculate merit position based on percentage instead of total marks
                    // First, get all students with their percentages
                    $stmt_all = $pdo->prepare("
                        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number,
                               SUM(sr.marks_obtained) as total_obtained, 
                               SUM(COALESCE(smd.total_marks, 100)) as total_marks,
                               (SUM(sr.marks_obtained) * 100.0 / SUM(COALESCE(smd.total_marks, 100))) as percentage
                        FROM students s
                        JOIN results sr ON s.id = sr.student_id
                        LEFT JOIN subject_mark_distribution smd ON sr.subject_id = smd.subject_id AND sr.class_id = smd.class_id AND sr.session = smd.session AND sr.exam_type = smd.exam_type
                        WHERE s.class_id = ? AND sr.exam_type = ? AND sr.session = ?
                        GROUP BY s.id, s.student_id, s.first_name, s.last_name, s.roll_number
                        ORDER BY percentage DESC
                    ");
                    $stmt_all->execute([$class_id, $exam_type, $session]);
                    $all_students = $stmt_all->fetchAll();

// Find the merit position based on percentage
$merit_position = null;
$found_student = false;
$position = 1;
foreach ($all_students as $student_record) {
    if ($student_record['id'] == $student['id']) {
        $merit_position = $position;
        $found_student = true;
        break;
    }
    $position++;
}

// If student not found in the list, explicitly set merit position to null
if (!$found_student) {
    $merit_position = null;
}

// DEBUG: Uncomment the following line to see the final merit position
// echo "Final merit position: " . ($merit_position !== null ? $merit_position : "NULL") . "<br>";
                    
                    // Find the merit position based on percentage
                    $merit_position = 1;
                    foreach ($all_students as $student_record) {
                        if ($student_record['id'] == $student['id']) {
                            break;
                        }
                        $merit_position++;
                    }
                } catch (Exception $e) {
                    // Merit position calculation failed, continue without it
                    // For debugging: uncomment the next line to see the error
                    // echo "Exception: " . $e->getMessage();
                    $merit_position = null; // Explicitly set to null on error
                } catch (PDOException $e) {
                    // Merit position calculation failed due to database error, continue without it
                    // For debugging: uncomment the next line to see the error
                    // echo "PDO Exception: " . $e->getMessage();
                    $merit_position = null; // Explicitly set to null on error
                }
            }
            
        } catch (PDOException $e) {
            die("Database error: " . $e->getMessage());
        }
        ?>
        
        <div class="marksheet">
            <div class="header">
                <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                    <!-- School Logo - Left -->
                    <div style="flex: 1; text-align: left;">
                        <?php if ($logo_image): ?>
                        <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="School Logo" class="school-logo" style="max-height: 80px; width: auto;">
                        <?php endif; ?>
                    </div>
                    
                    <!-- School Information - Center -->
                    <div style="flex: 2; text-align: center;">
                        <div class="school-name"><?php echo htmlspecialchars($site_name); ?></div>
                        <div class="school-address"><?php echo htmlspecialchars($site_address); ?></div>
                        <h3 style="margin-top: 15px; color: #2c3e50;">মার্কশীট</h3>
                    </div>
                    
                    <!-- Student Photo - Right -->
                    <div style="flex: 1; text-align: right;">
                        <?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; margin-left: auto;">
                                <i class="fas fa-user-graduate" style="font-size: 32px; color: #3498db;"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Combined row for student info, exam info, and basic info -->
            <div style="display: flex; justify-content: space-between; margin: 20px 0;">
                <!-- Left side: Student ID, Name, Father's Name, Mother's Name -->
                <div style="flex: 1; padding-right: 10px;">
                    <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>
                
                <!-- Center: Exam Info -->
                <div style="flex: 1; text-align: center; display: flex; flex-direction: column; justify-content: center;">
                    <h4 style="color: #2c3e50; margin: 0;">
                        <?php echo htmlspecialchars(ucfirst($exam_type)); ?> পরীক্ষা
                    </h4>
                    <div style="margin-top: 5px;">
                        <span><?php echo htmlspecialchars($session); ?> সেশন</span>
                    </div>
                </div>
                
                <!-- Right side: Roll Number, Class, Session -->
                <div style="flex: 1; padding-left: 10px;">
                    <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']); ?><?php if (!empty($student['group_name'])): ?> (<?php echo htmlspecialchars($student['group_name']); ?>)<?php endif; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">সেশন</div>
                        <div class="info-value"><?php echo htmlspecialchars($session); ?></div>
                    </div>
                </div>
            </div>
            
            <!-- Main Subjects Table -->
            <h4 class="text-center" style="color: #2c3e50; margin: 20px 0;">প্রধান বিষয়সমূহ</h4>
            <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">গ্রেড</th>
                        <th rowspan="2">জিপি</th>
                    </tr>
                    <tr>
                        <th>সিকিউ</th>
                        <th>এমসিকিউ</th>
                        <th>প্র্যাকটিক্যাল</th>
                        <th>অ্যাসাইনমেন্ট</th>
                        <th>অ্যাটেনডেন্স</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $total_full_marks = 0;
                    $total_obtained_marks = 0;
                    $total_gp = 0;
                    $subject_count = 0;
                    $passed_subjects = 0;
                    
                    foreach ($regular_subjects as $result):
                        $subject_full_marks = $result['full_marks'] ?? 100;
                        $subject_obtained_marks = $result['marks_obtained'] ?? 0;
                        $grade_point = $result['grade_point'] ?? 0.00;
                        
                        // Show all selected subjects, even with 0 full marks
                        // if ($subject_full_marks <= 0) continue;
                        
                        $total_full_marks += $subject_full_marks;
                        $total_obtained_marks += $subject_obtained_marks;
                        $total_gp += $grade_point;
                        $subject_count++;
                        
                        if ($result['grade'] !== 'F') {
                            $passed_subjects++;
                        }
                        
                        // For combined subjects, show appropriate labels
                        $subject_display_name = $result['subject_name'] ?? '';
                        if ($result['subject_id'] == 'combined_bangla') {
                            $subject_display_name = 'বাংলা (১ম ও ২য় পত্র)';
                        } elseif ($result['subject_id'] == 'combined_english') {
                            $subject_display_name = 'ইংরেজি (১ম ও ২য় পত্র)';
                        }
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars($subject_display_name); ?><?php if (!empty($result['subject_code'])): ?> <small>(<?php echo htmlspecialchars($result['subject_code']); ?>)</small><?php endif; ?></td>
                        <td><?php echo (isset($result['cq_marks_array']) && is_array($result['cq_marks_array'])) ? implode(', ', $result['cq_marks_array']) : ($result['cq_marks'] ?? 0); ?></td>
                        <td><?php echo (isset($result['mcq_marks_array']) && is_array($result['mcq_marks_array'])) ? implode(', ', $result['mcq_marks_array']) : ($result['mcq_marks'] ?? 0); ?></td>
                        <td><?php echo $result['practical_marks'] ?? 0; ?></td>
                        <td><?php echo $result['assignment_marks'] ?? 0; ?></td>
                        <td><?php echo $result['attendance_marks'] ?? 0; ?></td>
                        <td><?php echo $subject_obtained_marks; ?></td>
                        <td><?php echo $result['pass_marks'] ?? 33; ?></td>
                        <td><?php echo $result['grade'] ?? 'F'; ?></td>
                        <td><?php echo number_format($grade_point, 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="6">মোট</th>
                        <th><?php echo $total_obtained_marks; ?></th>
                        <th><?php echo $total_full_marks; ?></th>
                        <th colspan="2"></th>
                    </tr>
                    <tr>
                        <th colspan="8">পাস করা বিষয়: <?php echo $passed_subjects; ?>/<?php echo $subject_count; ?> <?php if ($merit_position !== null && $merit_position > 0): ?>(মেরিট: <?php echo $merit_position; ?>)<?php endif; ?></th>
                        <th colspan="2">
                            <?php 
                            // Use the properly calculated GPA that accounts for fourth subject rules
                            echo 'GPA: ' . number_format($gpa, 2);
                            ?>
                        </th>
                    </tr>
                </tfoot>
            </table>
            
            <!-- Fourth Subject Table (if any fourth subjects exist) -->
            <?php if (!empty($fourth_subjects_only)): ?>
            <h4 class="text-center" style="color: #2c3e50; margin: 30px 0;">চতুর্থ বিষয়</h4>
            <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">গ্রেড</th>
                        <th rowspan="2">জিপি</th>
                    </tr>
                    <tr>
                        <th>সিকিউ</th>
                        <th>এমসিকিউ</th>
                        <th>প্র্যাকটিক্যাল</th>
                        <th>অ্যাসাইনমেন্ট</th>
                        <th>অ্যাটেনডেন্স</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $fourth_total_full_marks = 0;
                    $fourth_total_obtained_marks = 0;
                    $fourth_total_gp = 0;
                    $fourth_subject_count = 0;
                    $fourth_passed_subjects = 0;
                    
                    foreach ($fourth_subjects_only as $result):
                        $subject_full_marks = $result['full_marks'] ?? 100;
                        $subject_obtained_marks = $result['marks_obtained'] ?? 0;
                        $grade_point = $result['grade_point'] ?? 0.00;
                        
                        // Show all selected subjects, even with 0 full marks
                        // if ($subject_full_marks <= 0) continue;
                        
                        $fourth_total_full_marks += $subject_full_marks;
                        $fourth_total_obtained_marks += $subject_obtained_marks;
                        $fourth_total_gp += $grade_point;
                        $fourth_subject_count++;
                        
                        // For combined subjects, show appropriate labels
                        $subject_display_name = $result['subject_name'] ?? '';
                        if (($result['subject_id'] ?? '') == 'combined_bangla') {
                            $subject_display_name = 'বাংলা (১ম ও ২য় পত্র)';
                        } elseif (($result['subject_id'] ?? '') == 'combined_english') {
                            $subject_display_name = 'ইংরেজি (১ম ও ২য় পত্র)';
                        }
                        
                        if (($result['grade'] ?? '') !== 'F') {
                            $fourth_passed_subjects++;
                        }
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars($subject_display_name); ?><?php if (!empty($result['subject_code'])): ?> <small>(<?php echo htmlspecialchars($result['subject_code']); ?>)</small><?php endif; ?></td>
                        <td><?php echo (isset($result['cq_marks_array']) && is_array($result['cq_marks_array'])) ? implode(', ', $result['cq_marks_array']) : ($result['cq_marks'] ?? 0); ?></td>
                        <td><?php echo (isset($result['mcq_marks_array']) && is_array($result['mcq_marks_array'])) ? implode(', ', $result['mcq_marks_array']) : ($result['mcq_marks'] ?? 0); ?></td>
                        <td><?php echo $result['practical_marks'] ?? 0; ?></td>
                        <td><?php echo $result['assignment_marks'] ?? 0; ?></td>
                        <td><?php echo $result['attendance_marks'] ?? 0; ?></td>
                        <td><?php echo $subject_obtained_marks; ?></td>
                        <td><?php echo $result['pass_marks'] ?? 33; ?></td>
                        <td><?php echo $result['grade'] ?? 'F'; ?></td>
                        <td><?php echo number_format($grade_point, 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="6">মোট</th>
                        <th><?php echo $fourth_total_obtained_marks; ?></th>
                        <th><?php echo $fourth_total_full_marks; ?></th>
                        <th colspan="2"></th>
                    </tr>
                    <tr>
                        <th colspan="8">পাস করা বিষয়: <?php echo $fourth_passed_subjects; ?>/<?php echo $fourth_subject_count; ?> <?php if ($merit_position !== null && $merit_position > 0): ?>(মেরিট: <?php echo $merit_position; ?>)<?php endif; ?></th>
                        <th colspan="2"></th>
                    </tr>
                </tfoot>
            </table>
            <?php endif; ?>
            
            <!-- Result Summary Section -->
            <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; ?>% <?php if ($show_merit_position && $merit_position !== null && $merit_position > 0): ?>(মেরিট: <?php echo $merit_position; ?>)<?php endif; ?></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>
                    <!-- Merit position now displayed next to percentage -->
                </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 endforeach; ?>
    <?php else: ?>
    <!-- Show search form when parameters are missing -->
    <div class="container mt-4">
        <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-4">
                        <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-4">
                        <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 htmlspecialchars($session_item['session']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <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-4">
                        <label for="show_merit_position" class="form-label">মেরিট পজিশন প্রদর্শন</label>
                        <select id="show_merit_position" name="show_merit_position" class="form-select">
                            <option value="1" selected>হ্যাঁ</option>
                            <option value="0">না</option>
                        </select>
                    </div>
                    <div class="col-md-12 text-center mt-3">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i> শিক্ষার্থী তালিকা দেখুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>