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

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

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

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

if (!$class_id || !$session || !$exam_type) {
    die("Class ID, session, and exam type are required parameters.");
}

// Get teacher's assigned classes if user is a teacher
$teacher_id = null;
$assigned_class_ids = [];
if ($_SESSION['user_role'] == 'teacher') {
    // Get teacher ID
    $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch();
    if ($teacher) {
        $teacher_id = $teacher['id'];
        
        // Get assigned class IDs
        $stmt = $pdo->prepare("SELECT DISTINCT c.id FROM classes c WHERE (c.class_teacher_id = ? OR c.id IN (SELECT class_id FROM class_subjects WHERE teacher_id = ?)) AND c.status = 'active'");
        $stmt->execute([$teacher_id, $teacher_id]);
        $assigned_classes = $stmt->fetchAll();
        $assigned_class_ids = array_column($assigned_classes, 'id');
    }
    
    // Check if user has permission to access this class
    if (!empty($assigned_class_ids) && !in_array($class_id, $assigned_class_ids)) {
        die("You don't have permission to access this class.");
    }
}

// Get all students in the class with results
$stmt = $pdo->prepare("
    SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.photo, s.father_name, s.mother_name, 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, s.first_name, s.last_name
");
$stmt->execute([$class_id, $session, $exam_type]);
$students = $stmt->fetchAll();

if (empty($students)) {
    die("No students found with results for this class, session, and exam type.");
}

// 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
    ];
    
    // Sum up the marks from all Bangla subjects
    foreach ($bangla_results as $result) {
        $combined['cq_marks'] += $result['cq_marks'];
        $combined['cq_marks_array'][] = $result['cq_marks']; // Store individual marks
        $combined['mcq_marks'] += $result['mcq_marks'];
        $combined['mcq_marks_array'][] = $result['mcq_marks']; // Store individual MCQ marks
        $combined['practical_marks'] += $result['practical_marks'];
        $combined['assignment_marks'] += $result['assignment_marks'];
        $combined['attendance_marks'] += $result['attendance_marks'];
        $combined['marks_obtained'] += $result['marks_obtained'];
        $combined['full_marks'] += (isset($result['full_marks']) ? $result['full_marks'] : 100);
        $combined['pass_marks'] += (isset($result['pass_marks']) ? $result['pass_marks'] : 33);
    }
    
    // For Jessore Board SSC: Show total sum of marks_obtained from both Bangla subjects
    // CQ and MCQ are averaged for grading criteria, but marks_obtained shows total sum
    $count = count($bangla_results);
    if ($count > 0) {
        $combined['cq_marks'] = $combined['cq_marks'] / $count; // Average for grading
        $combined['mcq_marks'] = $combined['mcq_marks'] / $count; // Average for grading
        // marks_obtained remains as total sum (not averaged)
        $combined['full_marks'] = $combined['full_marks'] / $count;
        $combined['pass_marks'] = $combined['pass_marks'] / $count;
    }
    
    return $combined;
}

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

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

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

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

// Custom function to calculate Bangla subject grade based on subject-wise setup
function calculateBanglaGrade($cq_marks_array, $mcq_marks, $total_marks, $pass_marks, $subject_id, $class_id, $session, $exam_type) {
    // Calculate average of 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];
    }

    // Get subject-specific pass marks from setup
    $cq_pass = 22; // Default fallback
    $mcq_pass = 9;  // Default fallback

    try {
        $pdo = $GLOBALS['pdo']; // Access global PDO
        $stmt = $pdo->prepare("SELECT cq_pass_marks, mcq_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
        $stmt->execute([$subject_id, $class_id, $session, $exam_type]);
        $setup = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($setup && $setup['cq_pass_marks'] !== null) {
            $cq_pass = $setup['cq_pass_marks'];
        }
        if ($setup && $setup['mcq_pass_marks'] !== null) {
            $mcq_pass = $setup['mcq_pass_marks'];
        }
    } catch (Exception $e) {
        // Use defaults if database error
    }

    // Check if averages meet the pass criteria from setup
    if ($cq_average > $cq_pass && $mcq_marks > $mcq_pass) {
        // Calculate overall marks
        $overall_marks = $cq_average + $mcq_marks;
        
        // Calculate percentage based on total marks
        $percentage = ($overall_marks / $total_marks) * 100;
        
        if ($percentage >= 80) return 'A+';
        elseif ($percentage >= 70) return 'A';
        elseif ($percentage >= 60) return 'A-';
        elseif ($percentage >= 50) return 'B';
        elseif ($percentage >= 40) return 'C';
        elseif ($percentage >= 33) return 'D';
        else return 'F';
    } else {
        // If criteria not met, return F
        return 'F';
    }
}

// Custom function to calculate English subject grade based on subject-wise setup
function calculateEnglishGrade($cq_marks_array, $total_marks, $pass_marks, $subject_id, $class_id, $session, $exam_type) {
    // Calculate average of 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];
    }

    // Get subject-specific pass marks from setup
    $cq_pass = 32; // Default fallback

    try {
        $pdo = $GLOBALS['pdo']; // Access global PDO
        $stmt = $pdo->prepare("SELECT cq_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
        $stmt->execute([$subject_id, $class_id, $session, $exam_type]);
        $setup = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($setup && $setup['cq_pass_marks'] !== null) {
            $cq_pass = $setup['cq_pass_marks'];
        }
    } catch (Exception $e) {
        // Use defaults if database error
    }

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

// Function to calculate GPA with Jessore Board 4th subject rules
function calculateGPA($results) {
    $total_grade_points = 0;
    $gpa_subjects = 0; // Subjects used for GPA calculation (excluding failed subjects and 4th subjects)
    $has_failed_in_non_fourth_subject = false; // Track if student failed in any non-fourth subject
    $fourth_subject_grade_point = 0; // Track 4th subject grade point for adjustment
    $fourth_subject_found = false; // Track if 4th subject exists
    
    foreach ($results as $result) {
        if (($result['grade'] ?? '') != 'F') {
            $grade_point = $result['grade_point'] ?? 0.00;
            
            // Handle 4th subject GPA adjustment according to Jessore Board rules
            if (!empty($result['is_fourth_subject']) && ($result['is_fourth_subject'] ?? false)) {
                $fourth_subject_found = true;
                $fourth_subject_grade_point = $grade_point;
                // For 4th subject: add only the bonus points (grade_point - 2.00) if grade_point > 2.00
                // Otherwise, add 0 bonus points
                if ($grade_point > 2.00) {
                    $total_grade_points += ($grade_point - 2.00);
                }
            } else {
                // Regular subject - add full grade point
                $total_grade_points += $grade_point;
                $gpa_subjects++; // Count only non-fourth subjects for GPA calculation
            }
        } else {
            // Student failed in this subject
            if (empty($result['is_fourth_subject']) || !($result['is_fourth_subject'] ?? false)) {
                // Failed in a non-fourth subject
                $has_failed_in_non_fourth_subject = true;
            }
        }
    }
    
    // GPA is 0.00 if student failed in any non-fourth subject
    if ($has_failed_in_non_fourth_subject) {
        return 0.00;
    }
    
    // If no subjects for GPA calculation, return 0.00
    if ($gpa_subjects == 0) {
        // If there are no regular subjects but there is a 4th subject, GPA is 0.00
        if ($fourth_subject_found) {
            return 0.00;
        } else {
            return 0.00;
        }
    }
    
    // Calculate GPA (Grade Point Average) with Jessore Board rules
    // For Jessore Board: when 4th subject exists, divide total grade points by number of regular subjects
    // The 4th subject contributes bonus points but is not counted in the subject total for division
    if ($fourth_subject_found) {
        // When 4th subject exists, divide by number of regular subjects (gpa_subjects)
        // because 4th subject's bonus points are added but it's not counted in the division
        $gpa = $total_grade_points / $gpa_subjects;
    } else {
        // Normal calculation - divide by total number of subjects
        $gpa = $total_grade_points / $gpa_subjects;
    }
    
    // Ensure total GPA never exceeds 5.00 regardless of whether there is a fourth subject or not
    if ($gpa > 5.00) {
        $gpa = 5.00;
    }
    
    return round($gpa, 2);
}

// Prepare data for all students
$all_students_data = [];

foreach ($students as $student) {
    // 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 = $stmt->fetchAll();
    
    // Group subjects according to Jessore Board SSC ordering requirements
    $combined_subjects = [];
    $bangla_results = [];
    $english_results = [];
    $other_results = [];

    foreach ($results as $result) {
        // Check if this is a Bangla subject (Bangla 1st/2nd Paper or Bangla Grammar, but not History subjects)
        $is_bangla = false;
        if ((stripos($result['subject_name'], 'বাংলা') !== false || stripos($result['subject_name'], 'Bangla') !== false) &&
            stripos($result['subject_name'], 'History') === false &&
            stripos($result['subject_name'], 'Introduction') === false) {
            $is_bangla = true;
        }
        if ($is_bangla) {
            $bangla_results[] = $result;
        }
        // Check if this is an English subject (English 1st/2nd Paper or English Grammar)
        else if ((stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) &&
                 stripos($result['subject_name'], 'Literature') === false) {
            $english_results[] = $result;
        }
        // All other subjects
        else {
            $other_results[] = $result;
        }
    }
    
    // Store the original results for use in maximum marks calculation
    $original_bangla_results = $bangla_results;
    $original_english_results = $english_results;
    
    // Process Bangla subjects as a combined subject
    if (!empty($bangla_results)) {
        // Combine Bangla and Bangla Grammar into one subject
        $combined_bangla = combineBanglaSubjects($bangla_results);
        // Use localized name for combined Bangla
        $combined_bangla['subject_name'] = 'বাংলা(একত্রে)';
        $combined_subjects[] = $combined_bangla;
    }
    
    // Process English subjects as a combined subject
    if (!empty($english_results)) {
        // Combine English and English Grammar into one subject
        $combined_english = combineEnglishSubjects($english_results);
        // Use localized name for combined English
        $combined_english['subject_name'] = 'ইংরেজি(একত্রে)';
        $combined_subjects[] = $combined_english;
    }
    
    // Define Jessore Board SSC subject priority order for other subjects
    $subject_priority = [
        // Core subjects after Bangla/English
        'Math' => 1,
        'Mathematics' => 1,
        'গণিত' => 1,
        'Science' => 2,
        'বিজ্ঞান' => 2,
        'Physics' => 3,
        'পদার্থবিদ্যা' => 3,
        'Chemistry' => 4,
        'রসায়ন' => 4,
        'Biology' => 5,
        'জীববিদ্যা' => 5,
        'Higher Math' => 6,
        'উচ্চতর গণিত' => 6,
        'ICT' => 7,
        'আইসিটি' => 7,
        'Economics' => 8,
        'অর্থনীতি' => 8,
        'Geography' => 9,
        'ভূগোল' => 9,
        'History of Bangladesh' => 10,
        'বাংলাদেশের ইতিহাস' => 10,
        'Bangladesh and World Introduction' => 11,
        'বাংলাদেশ ও বিশ্ব পরিচিতি' => 11,
        'Islam' => 12,
        'ইসলাম' => 12,
        'Physical Edu' => 13,
        'শারীরিক শিক্ষা' => 13,
        'Career Edu' => 14,
        'ক্যারিয়ার শিক্ষা' => 14,
        'Agricultural Edu' => 15,
        'কৃষি শিক্ষা' => 15
    ];

    // Sort other subjects by priority, then by name
    usort($other_results, function($a, $b) use ($subject_priority) {
        $a_priority = $subject_priority[$a['subject_name']] ?? 99;
        $b_priority = $subject_priority[$b['subject_name']] ?? 99;

        if ($a_priority != $b_priority) {
            return $a_priority - $b_priority;
        }

        return strcmp($a['subject_name'], $b['subject_name']);
    });

    // Combine subjects in Jessore Board SSC order: Bangla/English (combined) -> Other subjects
    $results = array_merge($combined_subjects, $other_results);

    // Separate regular subjects and 4th subjects for display
    $regular_subjects = [];
    $fourth_subjects = [];

    foreach ($results as $result) {
        // 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();
        $is_fourth_subject = $subject_info && $subject_info['is_fourth_subject'] ? true : false;
        
        $result['is_fourth_subject'] = $is_fourth_subject;
        
        if ($is_fourth_subject) {
            $fourth_subjects[] = $result;
        } else {
            $regular_subjects[] = $result;
        }
    }

    // Calculate class highest marks for Bangla and English combined subjects
    $class_highest_bangla = 0;
    $class_highest_english = 0;

    // Get all students in the class
    $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
    $stmt->execute([$student['class_id']]);
    $all_students_list = $stmt->fetchAll(PDO::FETCH_COLUMN);

    foreach ($all_students_list as $sid) {
        // Calculate Bangla highest for this student
        if (!empty($original_bangla_results)) {
            $bangla_ids = array_column($original_bangla_results, 'subject_id');
            $placeholders = str_repeat('?,', count($bangla_ids) - 1) . '?';
            $stmt = $pdo->prepare("
                SELECT SUM(marks_obtained) as total_marks
                FROM results r1
                WHERE r1.student_id = ? AND r1.subject_id IN ($placeholders) AND r1.session = ? AND r1.exam_type = ?
                AND r1.id IN (
                    SELECT MAX(r2.id)
                    FROM results r2
                    WHERE r2.student_id = r1.student_id AND r2.subject_id = r1.subject_id AND r2.session = r1.session AND r2.exam_type = r1.exam_type
                )
            ");
            $params = array_merge([$sid], $bangla_ids, [$session, $exam_type]);
            $stmt->execute($params);
            $bangla_result = $stmt->fetch();
            if ($bangla_result && $bangla_result['total_marks'] > $class_highest_bangla) {
                $class_highest_bangla = $bangla_result['total_marks'];
            }
        }

        // Calculate English highest for this student
        if (!empty($original_english_results)) {
            $english_ids = array_column($original_english_results, 'subject_id');
            $placeholders = str_repeat('?,', count($english_ids) - 1) . '?';
            $stmt = $pdo->prepare("
                SELECT SUM(marks_obtained) as total_marks
                FROM results r1
                WHERE r1.student_id = ? AND r1.subject_id IN ($placeholders) AND r1.session = ? AND r1.exam_type = ?
                AND r1.id IN (
                    SELECT MAX(r2.id)
                    FROM results r2
                    WHERE r2.student_id = r1.student_id AND r2.subject_id = r1.subject_id AND r2.session = r1.session AND r2.exam_type = r1.exam_type
                )
            ");
            $params = array_merge([$sid], $english_ids, [$session, $exam_type]);
            $stmt->execute($params);
            $english_result = $stmt->fetch();
            if ($english_result && $english_result['total_marks'] > $class_highest_english) {
                $class_highest_english = $english_result['total_marks'];
            }
        }
    }

    // Update class_max_marks for combined Bangla and English subjects
    foreach ($regular_subjects as &$result) {
        if ($result['subject_name'] == 'বাংলা(একত্রে)') {
            $result['class_max_marks'] = $class_highest_bangla;
        } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
            $result['class_max_marks'] = $class_highest_english;
        }
    }
    unset($result); // Break reference

    // Ensure combined subjects have required fields
    foreach ($regular_subjects as &$result) {
        if ($result['subject_id'] == 'combined_bangla' || $result['subject_id'] == 'combined_english') {
            // For combined subjects, try to get actual marks from subject_mark_distribution
            // Use a generic subject ID to fetch the passing marks (we'll use the first Bangla/English subject ID)
            $combined_subject_id = null;
            if ($result['subject_id'] == 'combined_bangla' && !empty($original_bangla_results)) {
                $combined_subject_id = $original_bangla_results[0]['subject_id'];
            } else if ($result['subject_id'] == 'combined_english' && !empty($original_english_results)) {
                $combined_subject_id = $original_english_results[0]['subject_id'];
            }
            
            if ($combined_subject_id) {
                $stmt = $pdo->prepare("SELECT total_marks, overall_pass_marks FROM subject_mark_distribution WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ? LIMIT 1");
                $stmt->execute([$combined_subject_id, $student['class_id'], $session, $exam_type]);
                $smd = $stmt->fetch();
                
                if ($smd) {
                    $result['full_marks'] = $smd['total_marks'];
                    $result['pass_marks'] = $smd['overall_pass_marks'];
                } else {
                    // Fallback to defaults
                    if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                        $result['full_marks'] = 100;
                    }
                    if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                        $result['pass_marks'] = 40;
                    }
                }
            } else {
                // Fallback to defaults
                if (!isset($result['full_marks']) || $result['full_marks'] == 0) {
                    $result['full_marks'] = 100;
                }
                if (!isset($result['pass_marks']) || $result['pass_marks'] == 0) {
                    $result['pass_marks'] = 40;
                }
            }
        }
    }
    unset($result); // Break reference
    
    // Enhance results with subject-specific marks distribution and GP
    foreach ($regular_subjects as &$result) {
        // Try to get subject-specific mark distribution
        $stmt = $pdo->prepare("
            SELECT total_marks, overall_pass_marks 
            FROM subject_mark_distribution 
            WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
            LIMIT 1
        ");
        $stmt->execute([
            $result['subject_id'], 
            $student['class_id'], 
            $session, 
            $exam_type
        ]);
        $smd = $stmt->fetch();
        
        if ($smd) {
            $result['full_marks'] = $smd['total_marks'];
            $result['pass_marks'] = $smd['overall_pass_marks'];
        } else {
            // Fallback to mark_distributions
            $stmt = $pdo->prepare("
                SELECT total_marks, pass_marks as overall_pass_marks 
                FROM mark_distributions 
                WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                LIMIT 1
            ");
            $stmt->execute([
                $result['subject_id'], 
                $student['class_id'], 
                $session, 
                $exam_type
            ]);
            $md = $stmt->fetch();
            
            if ($md) {
                $result['full_marks'] = $md['total_marks'];
                $result['pass_marks'] = $md['overall_pass_marks'];
            } else {
                // Default values
                $result['full_marks'] = 100;
                $result['pass_marks'] = 33; // Use 40 as default passing marks as requested
            }
        }
        
        // Add subject-based GP (Grade Point)
        $result['grade_point'] = getGradePoint($result['grade']);
        
        // Get maximum obtained marks for this subject in the class
        if ($result['subject_id'] == 'combined_bangla') {
            // For combined Bangla, we need to find the maximum combined marks across all students in the class
            // First, get all Bangla subject IDs
            $bangla_ids = array_column($original_bangla_results, 'subject_id');
            if (!empty($bangla_ids)) {
                // Get all students in the class
                $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                $stmt->execute([$student['class_id']]);
                $students_list = $stmt->fetchAll();
                
                $max_combined_marks = 0;
                foreach ($students_list as $student_row) {
                    $student_id_tmp = $student_row['id'];
                    
                    // Get results for this student in all Bangla subjects (only latest entry per subject)
                    $placeholders = str_repeat('?,', count($bangla_ids) - 1) . '?';
                    $stmt = $pdo->prepare("
                        SELECT SUM(marks_obtained) as total_marks
                        FROM results r1
                        WHERE r1.student_id = ? AND r1.subject_id IN ($placeholders) AND r1.session = ? AND r1.exam_type = ?
                        AND r1.id IN (
                            SELECT MAX(r2.id)
                            FROM results r2
                            WHERE r2.student_id = r1.student_id AND r2.subject_id = r1.subject_id AND r2.session = r1.session AND r2.exam_type = r1.exam_type
                        )
                    ");
                    $params = array_merge([$student_id_tmp], $bangla_ids, [$session, $exam_type]);
                    $stmt->execute($params);
                    $student_result = $stmt->fetch();

                    if ($student_result && $student_result['total_marks'] !== null) {
                        // Show total sum like in combineBanglaSubjects (not average)
                        $combined_marks = $student_result['total_marks'];
                        if ($combined_marks > $max_combined_marks) {
                            $max_combined_marks = $combined_marks;
                        }
                    }
                }
                
                $result['class_max_marks'] = $max_combined_marks;
            } else {
                $result['class_max_marks'] = 0;
            }
        } else if ($result['subject_id'] == 'combined_english') {
            // For combined English, we need to find the maximum combined marks across all students in the class
            // First, get all English subject IDs
            $english_ids = array_column($original_english_results, 'subject_id');
            if (!empty($english_ids)) {
                // Get all students in the class
                $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
                $stmt->execute([$student['class_id']]);
                $students_list = $stmt->fetchAll();
                
                $max_combined_marks = 0;
                foreach ($students_list as $student_row) {
                    $student_id_tmp = $student_row['id'];
                    
                    // Get results for this student in all English subjects (only latest entry per subject)
                    $placeholders = str_repeat('?,', count($english_ids) - 1) . '?';
                    $stmt = $pdo->prepare("
                        SELECT SUM(marks_obtained) as total_marks
                        FROM results r1
                        WHERE r1.student_id = ? AND r1.subject_id IN ($placeholders) AND r1.session = ? AND r1.exam_type = ?
                        AND r1.id IN (
                            SELECT MAX(r2.id)
                            FROM results r2
                            WHERE r2.student_id = r1.student_id AND r2.subject_id = r1.subject_id AND r2.session = r1.session AND r2.exam_type = r1.exam_type
                        )
                    ");
                    $params = array_merge([$student_id_tmp], $english_ids, [$session, $exam_type]);
                    $stmt->execute($params);
                    $student_result = $stmt->fetch();

                    if ($student_result && $student_result['total_marks'] !== null) {
                        // Show total sum like in combineEnglishSubjects (not average)
                        $combined_marks = $student_result['total_marks'];
                        if ($combined_marks > $max_combined_marks) {
                            $max_combined_marks = $combined_marks;
                        }
                    }
                }
                
                $result['class_max_marks'] = $max_combined_marks;
            } else {
                $result['class_max_marks'] = 0;
            }
        } else {
            // For regular subjects
            $stmt = $pdo->prepare("SELECT MAX(marks_obtained) as max_marks FROM results WHERE subject_id = ? AND session = ? AND exam_type = ? AND student_id IN (SELECT id FROM students WHERE class_id = ? AND status = 'active')");
            $stmt->execute([$result['subject_id'], $session, $exam_type, $student['class_id']]);
            $max_result = $stmt->fetch();
            $result['class_max_marks'] = $max_result['max_marks'] ?? 0;
        }
        
        // Apply custom grading for combined Bangla and English subjects
        if ($result['subject_name'] == 'বাংলা(একত্রে)') {
            // For combined Bangla: uses cq_pass_marks and mcq_pass_marks from setup
            // Use the first original Bangla subject ID for lookup
            $bangla_subject_id = !empty($original_bangla_results) ? $original_bangla_results[0]['subject_id'] : $result['subject_id'];
            $custom_grade = calculateBanglaGrade($result['cq_marks_array'], $result['mcq_marks'], $result['full_marks'], $result['pass_marks'], $bangla_subject_id, $student['class_id'], $session, $exam_type);
            $result['grade'] = $custom_grade;
            $result['grade_point'] = getGradePoint($custom_grade);
        } else if ($result['subject_name'] == 'ইংরেজি(একত্রে)') {
            // For combined English: uses cq_pass_marks from setup
            // Use the first original English subject ID for lookup
            $english_subject_id = !empty($original_english_results) ? $original_english_results[0]['subject_id'] : $result['subject_id'];
            $custom_grade = calculateEnglishGrade($result['cq_marks_array'], $result['full_marks'], $result['pass_marks'], $english_subject_id, $student['class_id'], $session, $exam_type);
            $result['grade'] = $custom_grade;
            $result['grade_point'] = getGradePoint($custom_grade);
        }
    }
    unset($result); // Break the reference with the last element
    
    // Calculate totals and GPA with Jessore Board 4th subject rules
    $total_marks = 0;
    $total_obtained = 0;
    $total_subjects = count($regular_subjects) + count($fourth_subjects);
    $passed_subjects = 0;
    $total_grade_points = 0;
    $gpa_subjects = 0; // Subjects used for GPA calculation (excluding failed subjects)
    $has_failed_in_non_fourth_subject = false; // Track if student failed in any non-fourth subject
    $fourth_subject_grade_point = 0; // Track 4th subject grade point for adjustment
    $fourth_subject_found = false; // Track if 4th subject exists
    
    // Combine regular and fourth subjects for GPA calculation
    $all_results = array_merge($regular_subjects, $fourth_subjects);
    
    foreach ($all_results as $result) {
        $total_marks += $result['full_marks'];
        $total_obtained += $result['marks_obtained'];
        
        // Check if student failed in this subject and it's not a fourth subject
        if ($result['grade'] == 'F' && !$result['is_fourth_subject']) {
            $has_failed_in_non_fourth_subject = true;
        }
        
        if ($result['grade'] != 'F') {
            $passed_subjects++;
            
            // Handle 4th subject GPA adjustment according to Jessore Board rules
            if ($result['is_fourth_subject']) {
                $fourth_subject_found = true;
                $fourth_subject_grade_point = $result['grade_point'];
                // For 4th subject: if GPA > 2.00, add only 2.00 points, otherwise add the actual points
                $adjusted_grade_point = ($result['grade_point'] > 2.00) ? 2.00 : $result['grade_point'];
                $total_grade_points += $adjusted_grade_point;
            } else {
                // Regular subject - add full grade point
                $total_grade_points += $result['grade_point'];
                $gpa_subjects++; // Count subjects for GPA calculation
            }
        }
    }
    
    $percentage = $total_marks > 0 ? round(($total_obtained / $total_marks) * 100, 2) : 0;
    
    // Calculate GPA using the function
    $gpa = calculateGPA($all_results);
    
    // Calculate merit position based on GPA
    $merit_position = null;
    if ($student && $session && $exam_type) {
        // Store the current student's GPA before calculating for other students
        $current_student_gpa = $gpa;
        
        // Get all students in the same class with their GPA for merit calculation
        $stmt = $pdo->prepare("SELECT id FROM students WHERE class_id = ? AND status = 'active'");
        $stmt->execute([$student['class_id']]);
        $all_student_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        // Calculate GPA for each student using the same logic as the current student
        $student_gpas = [];
        foreach ($all_student_ids as $sid) {
            // Get student results - FIXED to get only latest result per subject (same as main query)
            $stmt = $pdo->prepare("
                SELECT r.*, sub.name as subject_name
                FROM results r
                LEFT JOIN subjects sub ON r.subject_id = sub.id
                WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?
                AND r.id IN (
                    SELECT MAX(id)
                    FROM results
                    WHERE student_id = ? AND session = ? AND exam_type = ?
                    GROUP BY subject_id
                )
            ");
            $stmt->execute([$sid, $session, $exam_type, $sid, $session, $exam_type]);
            $student_results = $stmt->fetchAll();
            
            if (empty($student_results)) {
                $student_gpas[$sid] = 0.00;
                continue;
            }
            
            // Group Bangla and English subjects together (same logic as for current student)
            $grouped_results = [];
            $combined_subjects = [];
            $bangla_results = [];
            $english_results = [];
            
            foreach ($student_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) {
                    $bangla_results[] = $result;
                }
                // Check if this is an English subject (English or English Grammar)
                else if (stripos($result['subject_name'], 'ইংরেজি') !== false || stripos($result['subject_name'], 'English') !== false) {
                    $english_results[] = $result;
                }
                // For other subjects, add directly
                else {
                    $grouped_results[] = $result;
                }
            }
            
            // Process Bangla subjects as a combined subject
            if (!empty($bangla_results)) {
                // Combine Bangla and Bangla Grammar into one subject
                $combined_bangla = combineBanglaSubjects($bangla_results);
                // Use localized name for combined Bangla
                $combined_bangla['subject_name'] = 'বাংলা(একত্রে)';
                $combined_subjects[] = $combined_bangla;
            }
            
            // Process English subjects as a combined subject
            if (!empty($english_results)) {
                // Combine English and English Grammar into one subject
                $combined_english = combineEnglishSubjects($english_results);
                // Use localized name for combined English
                $combined_english['subject_name'] = 'ইংরেজি(একত্রে)';
                $combined_subjects[] = $combined_english;
            }
            
            // Combine subjects should appear first, then other subjects
            $processed_results = array_merge($combined_subjects, $grouped_results);
            
            // Calculate GPA using the same logic as for the current student
            // Use local variables to avoid overwriting main student variables
            $student_total_grade_points = 0;
            $student_gpa_subjects = 0;
            $student_has_failed_in_non_fourth_subject = false;
            $student_fourth_subject_found = false;
            
            foreach ($processed_results as $result) {
                // Add subject-based GP (Grade Point)
                $grade_point = getGradePoint($result['grade']);
                
                // Check if this subject is a fourth subject
                $stmt = $pdo->prepare("SELECT is_fourth_subject FROM student_subjects WHERE student_id = ? AND subject_id = ? LIMIT 1");
                $stmt->execute([$sid, $result['subject_id']]);
                $subject_info = $stmt->fetch();
                $is_fourth_subject = $subject_info && $subject_info['is_fourth_subject'] ? true : false;
                
                // Check if student failed in this subject and it's not a fourth subject
                if ($result['grade'] == 'F' && !$is_fourth_subject) {
                    $student_has_failed_in_non_fourth_subject = true;
                }

                if ($result['grade'] != 'F') {
                    // Handle 4th subject GPA adjustment according to Jessore Board rules
                    if ($is_fourth_subject) {
                        $student_fourth_subject_found = true;
                        // For 4th subject: add only the bonus points (grade_point - 2.00) if grade_point > 2.00
                        if ($grade_point > 2.00) {
                            $student_total_grade_points += ($grade_point - 2.00);
                        }
                    } else {
                        // Regular subject - add full grade point
                        $student_total_grade_points += $grade_point;
                    }
                    $student_gpa_subjects++; // Count only non-fourth subjects for GPA calculation
                }
            }
            
            // Calculate final GPA for this student using the same logic as for current student
            if ($student_has_failed_in_non_fourth_subject) {
                $student_gpas[$sid] = 0.00;
            } else {
                if ($student_gpa_subjects > 0) {
                    // For Jessore Board: when 4th subject exists, divide by (number of subjects - 1)
                    if ($student_fourth_subject_found) {
                        $student_gpa = $student_total_grade_points / $student_gpa_subjects;
                    } else {
                        $student_gpa = $student_total_grade_points / $student_gpa_subjects;
                    }
                    
                    // Apply Jessore Board 4th subject rule: If 4th subject exists and GPA > 5.00, cap it at 5.00
                    if ($student_fourth_subject_found && $student_gpa > 5.00) {
                        $student_gpa = 5.00;
                    }
                    
                    $student_gpas[$sid] = round($student_gpa, 2);
                } else {
                    $student_gpas[$sid] = 0.00;
                }
            }
        }
        
        // Sort students by GPA in descending order (highest GPA first)
        arsort($student_gpas);
        
        // Create an array of student IDs ordered by merit position
        $merit_order = [];
        $position = 1;
        foreach ($student_gpas as $sid => $student_gpa) {
            $merit_order[$sid] = $position++;
        }
        
        // Get merit position for current student
        $merit_position = isset($merit_order[$student['id']]) ? $merit_order[$student['id']] : null;
        
        // Restore the current student's GPA
        $gpa = $current_student_gpa;
    }
    
    // Add student data to the array
    $all_students_data[] = [
        'student' => $student,
        'regular_subjects' => $regular_subjects,
        'fourth_subjects' => $fourth_subjects,
        'total_marks' => $total_marks,
        'total_obtained' => $total_obtained,
        'percentage' => $percentage,
        'gpa' => $gpa,
        'passed_subjects' => $passed_subjects,
        'total_subjects' => $total_subjects,
        'merit_position' => $merit_position
    ];
}
?>

<!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;
        }
        
        .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;
        }
        
        .page-break {
            page-break-before: always;
        }
        
        @media print {
            .no-print { display: none !important; }
            .container-fluid { max-width: 100% !important; }
            body { 
                font-size: 10px;
                font-family: 'Hind Siliguri', sans-serif;
            }
            .marksheet { 
                page-break-inside: avoid; 
                box-shadow: none;
                border: 2px solid #000 !important;
                padding: 10px;
                background: white;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .marksheet::before {
                opacity: 0.03;
                -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: 100px;
                border: 2px solid #3498db;
                border-radius: 3px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            
            /* Student photo print styles */
            .student-photo {
                display: block !important;
            }
            
            .student-photo-print {
                max-width: 80px !important;
                max-height: 100px !important;
                border: 1px solid #000 !important;
                border-radius: 3px !important;
                box-shadow: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <div class="text-center mb-3 no-print">
            <button onclick="downloadAllPDF()" class="btn btn-success me-2"><i class="fas fa-download"></i> সবগুলো মার্কশিট PDF ডাউনলোড করুন</button>
            <a href="bulk_print_marksheets.php" class="btn btn-primary me-2"><i class="fas fa-search"></i> মার্কশিট প্রিন্ট করুন</a>
            <a href="../index.php" class="btn btn-secondary"><i class="fas fa-home"></i> হোম</a>
        </div>
        
        <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>
        <script>
            function downloadAllPDF() {
                // Show print view first to ensure all elements are properly rendered
                window.print();
                
                // Then generate PDF after a delay to allow print view to render
                setTimeout(function() {
                    const { jsPDF } = window.jspdf;
                    const marksheets = document.querySelectorAll('.marksheet');
                    
                    if (marksheets.length === 0) {
                        alert('কোন মার্কশিট পাওয়া যায়নি!');
                        return;
                    }
                    
                    // Create a new PDF document
                    const pdf = new jsPDF('p', 'mm', 'a4');
                    
                    let pdfHeight = 0;
                    
                    // Process each marksheet element
                    marksheets.forEach((element, index) => {
                        // Convert the marksheet to canvas
                        html2canvas(element, { 
                            scale: 2,
                            useCORS: true,
                            logging: false,
                            onclone: function(clonedDoc) {
                                // Ensure all images are loaded
                                const images = clonedDoc.querySelectorAll('img');
                                images.forEach(img => {
                                    if (img.complete === false) {
                                        img.onload = function() {};
                                        img.onerror = function() {};
                                    }
                                });
                            }
                        }).then(canvas => {
                            const imgData = canvas.toDataURL('image/jpeg', 1.0);
                            
                            // Calculate dimensions to fit in A4
                            const pageWidth = pdf.internal.pageSize.getWidth();
                            const pageHeight = pdf.internal.pageSize.getHeight();
                            const imgProps = pdf.getImageProperties(imgData);
                            const pdfWidth = pageWidth - 20; // 10mm margin on each side
                            const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
                            
                            // Add a new page for each marksheet except the first one
                            if (index > 0) {
                                pdf.addPage();
                            }
                            
                            // Add the marksheet image to the PDF
                            pdf.addImage(imgData, 'JPEG', 10, 10, pdfWidth, Math.min(pdfHeight, pageHeight - 20));
                            
                            // If this is the last marksheet, save the PDF
                            if (index === marksheets.length - 1) {
                                pdf.save('all_marksheets_<?php echo $class_id; ?>_<?php echo $session; ?>_<?php echo $exam_type; ?>.pdf');
                            }
                        }).catch(error => {
                            console.error('Error generating PDF for marksheet ' + (index + 1) + ':', error);
                            alert('PDF তৈরিতে সমস্যা হয়েছে। পুনরায় চেষ্টা করুন।');
                        });
                    });
                }, 1000); // Wait 1 second to ensure print view is rendered
            }
        </script>
        
        <?php foreach ($all_students_data as $index => $student_data): ?>
        <?php if ($index > 0): ?>
        <div class="page-break"></div>
        <?php endif; ?>
        <div class="marksheet">
            <div class="school-header">
                <!-- School Logo - Left -->
                <div class="school-logo" style="float: left; width: 60px; height: 60px; text-align: left; display: block;">
                    <?php if ($logo_image): ?>
                        <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" style="max-height: <?php echo $logo_size; ?>px; width: 100%; height: 100%; border-radius: 50%; object-fit: contain;">
                    <?php else: ?>
                        <i class="fas fa-graduation-cap"></i>
                    <?php endif; ?>
                </div>
                
                <!-- Institution Name and Address - Center -->
                <div style="display: inline-block; width: 70%; text-align: center; vertical-align: top;">
                    <h3 style="font-size: 24px; margin: 0 0 5px 0;"><?php echo htmlspecialchars($site_name); ?></h3>
                    <p style="color: #7f8c8d; margin: 0 0 5px 0; font-size: 14px;"><?php echo htmlspecialchars($site_address); ?></p>
                    <h4 style="font-size: 18px; margin: 0;">একাডেমিক মার্কশীট</h4>
                </div>
                
                <!-- Student Photo - Right -->
                <div style="float: right; width: 15%; text-align: right; display: block;" class="student-photo">
                    <?php if (!empty($student_data['student']['photo']) && file_exists(__DIR__ . '/' . $student_data['student']['photo'])): ?>
                        <img src="<?php echo htmlspecialchars($student_data['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 style="clear: both;"></div>
            </div>
            
            <!-- Watermark Logos -->
            <?php if ($logo_image): ?>
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(45deg); opacity: 0.05; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 3); ?>px; height: <?php echo ($logo_size * 3); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; top: 20%; left: 20%; transform: rotate(30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; top: 20%; right: 20%; transform: rotate(-30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; bottom: 20%; left: 20%; transform: rotate(-30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; bottom: 20%; right: 20%; transform: rotate(30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
            <?php endif; ?>
            
            <div class="student-info">
                <div>
                    <div class="info-row">
                        <div class="info-label">শিক্ষার্থী আইডি</div>
                        <div class="info-value"><?php echo htmlspecialchars($student_data['student']['student_id']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student_data['student']['first_name'] . ' ' . $student_data['student']['last_name']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পিতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student_data['student']['father_name'] ?? ''); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">মাতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student_data['student']['mother_name'] ?? ''); ?></div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">রোল নম্বর</div>
                        <div class="info-value"><?php echo htmlspecialchars($student_data['student']['roll_number']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শ্রেণী</div>
                        <div class="info-value"><?php echo htmlspecialchars($student_data['student']['class_name'] . ' ' . $student_data['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>
            
            <!-- Subject Marks Table -->
            <table class="marks-table">
                <thead>
                    <tr>
                        <th>বিষয়</th>
                        <th>পূর্ণ নম্বর</th>
                        <th>প্রাপ্ত নম্বর</th>
                        <th>গ্রেড</th>
                        <th>সর্বোচ্চ (ক্লাস)</th>
                        <th>বর্ণনা</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($student_data['regular_subjects'] as $subject): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($subject['subject_name']); ?></td>
                        <td><?php echo $subject['full_marks'] ?? 0; ?></td>
                        <td><?php echo $subject['marks_obtained'] ?? 0; ?></td>
                        <td><?php echo $subject['grade'] ?? 'N/A'; ?></td>
                        <td><?php echo $subject['class_max_marks'] ?? 0; ?></td>
                        <td>
                            <?php if ($subject['is_fourth_subject']): ?>
                                <span class="badge bg-info">৪র্থ বিষয়</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    
                    <?php if (!empty($student_data['fourth_subjects'])): ?>
                    <tr>
                        <td colspan="6" style="text-align: center; font-weight: bold; background-color: #e9ecef;">৪র্থ বিষয়</td>
                    </tr>
                    <?php foreach ($student_data['fourth_subjects'] as $subject): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($subject['subject_name']); ?></td>
                        <td><?php echo $subject['full_marks'] ?? 0; ?></td>
                        <td><?php echo $subject['marks_obtained'] ?? 0; ?></td>
                        <td><?php echo $subject['grade'] ?? 'N/A'; ?></td>
                        <td><?php echo $subject['class_max_marks'] ?? 0; ?></td>
                        <td><span class="badge bg-info">৪র্থ বিষয়</span></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            
            <!-- Result Summary -->
            <div class="result-summary">
                <div style="text-align: center;">
                    <h6>ফলাফল</h6>
                    <p><strong>মোট নম্বর:</strong> <?php echo $student_data['total_obtained']; ?>/<?php echo $student_data['total_marks']; ?></p>
                    <p><strong>প্রাপ্ত %:</strong> <?php echo $student_data['percentage']; ?>%</p>
                </div>
                <div style="text-align: center;">
                    <h6>গ্রেড পয়েন্ট</h6>
                    <p><strong>জিপিএ:</strong> <?php echo $student_data['gpa']; ?></p>
                    <p><strong>মেধা ক্রম:</strong> <?php echo $student_data['merit_position'] ? '#' . $student_data['merit_position'] : 'N/A'; ?></p>
                </div>
            </div>
            
            <!-- Grade Scale -->
            <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)
            </div>
            
            <!-- Signature Section -->
            <div class="signature-section">
                <div class="signature-box">
                    শিক্ষার্থীর স্বাক্ষর
                </div>
                <div class="signature-box">
                    অভিভাবকের স্বাক্ষর
                </div>
                <div class="signature-box">
                    প্রধান শিক্ষকের স্বাক্ষর
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</body>
</html>