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

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

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

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

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

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

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

// Check if we're showing student list (after first search)
$show_student_list = false;
if ($class_id && $session && $exam_type) {
    $show_student_list = true;
    
    // Get students based on class, session, and exam type
    $stmt = $pdo->prepare("
        SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number
        FROM students s 
        WHERE s.class_id = ? AND s.status = 'active'
        AND EXISTS (
            SELECT 1 FROM results r 
            WHERE r.student_id = s.id 
            AND r.session = ? 
            AND r.exam_type = ?
        )
        ORDER BY s.roll_number, s.first_name, s.last_name
    ");
    $stmt->execute([$class_id, $session, $exam_type]);
    $all_students_in_class = $stmt->fetchAll();
    
    // Filter students based on search term
    if (!empty($student_search)) {
        $students_in_class = array_filter($all_students_in_class, function($student) use ($student_search) {
            $search_term = strtolower($student_search);
            return strpos(strtolower($student['first_name']), $search_term) !== false ||
                   strpos(strtolower($student['last_name']), $search_term) !== false ||
                   strpos($student['roll_number'], $search_term) !== false ||
                   strpos($student['student_id'], $search_term) !== false;
        });
    } else {
        $students_in_class = $all_students_in_class;
    }
}

if ($student_id && $session && $exam_type) {
    // Get student details
    $stmt = $pdo->prepare("
        SELECT s.*, c.name as class_name, c.section 
        FROM students s 
        JOIN classes c ON s.class_id = c.id 
        WHERE s.id = ?
    ");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    if ($student) {
        // Get all subjects selected by the student from student_subjects table
        $stmt = $pdo->prepare("
            SELECT ss.subject_id, s.name as subject_name, s.code as subject_code
            FROM student_subjects ss
            JOIN subjects s ON ss.subject_id = s.id
            WHERE ss.student_id = ? AND s.status = 'active'
            ORDER BY s.name
        ");
        $stmt->execute([$student_id]);
        $all_student_subjects = $stmt->fetchAll();
        
        // Get results for the student - FIXED to avoid duplicates
        $stmt = $pdo->prepare("
            SELECT r.*, 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])) {
                $results[] = $results_map[$subject_id];
            } else {
                // If student doesn't have marks, create a placeholder result with 'F' grade
                $placeholder_result = [
                    'subject_id' => $subject_id,
                    'subject_name' => $subject['subject_name'],
                    'subject_code' => $subject['subject_code'],
                    'cq_marks' => 0,
                    'cq_marks_array' => [],
                    'mcq_marks' => 0,
                    'mcq_marks_array' => [],
                    'practical_marks' => 0,
                    'assignment_marks' => 0,
                    'attendance_marks' => 0,
                    'marks_obtained' => 0,
                    'full_marks' => 100,
                    'pass_marks' => 33,
                    'grade' => 'F', // Mark as failed if no marks
                    'grade_point' => 0.00,
                    'class_max_marks' => 0,
                    'is_fourth_subject' => false
                ];
                
                // Try to get subject-specific mark distribution
                $stmt = $pdo->prepare("
                    SELECT total_marks, overall_pass_marks 
                    FROM subject_mark_distribution 
                    WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                    LIMIT 1
                ");
                $stmt->execute([
                    $subject_id, 
                    $student['class_id'], 
                    $session, 
                    $exam_type
                ]);
                $smd = $stmt->fetch();
                
                if ($smd) {
                    $placeholder_result['full_marks'] = $smd['total_marks'];
                    $placeholder_result['pass_marks'] = $smd['overall_pass_marks'];
                } else {
                    // Fallback to mark_distributions
                    $stmt = $pdo->prepare("
                        SELECT total_marks, pass_marks as overall_pass_marks 
                        FROM mark_distributions 
                        WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                        LIMIT 1
                    ");
                    $stmt->execute([
                        $subject_id, 
                        $student['class_id'], 
                        $session, 
                        $exam_type
                    ]);
                    $md = $stmt->fetch();
                    
                    if ($md) {
                        $placeholder_result['full_marks'] = $md['total_marks'];
                        $placeholder_result['pass_marks'] = $md['overall_pass_marks'];
                    }
                }
                
                $results[] = $placeholder_result;
                $has_missing_marks = true; // Mark that we have missing marks
            }
        }
        
        // Group subjects according to specific ordering requirements
        $bangla_results = [];
        $english_results = [];
        $science_math_subjects = []; // Science and Math (go at the top)
        $middle_subjects = [];       // Other subjects except special cases
        $ict_economics_subjects = []; // ICT and Economics (go at the bottom)
        $career_edu = null;          // Career Education
        $agri_edu = null;            // Agricultural Education (goes at the very end)
        $fourth_subject = null;      // 4th subject (to be placed at the end)
        
        foreach ($results as $result) {
            $subject_name = strtolower($result['subject_name']);
            
            // Check if this is a 4th subject
            if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                $fourth_subject = $result;
                continue; // Skip adding to other groups
            }
            
            // 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;
            }
            // Check for Science and Math subjects (go at the top)
            else if (strpos($subject_name, 'science') !== false || strpos($subject_name, 'বিজ্ঞান') !== false ||
                     strpos($subject_name, 'math') !== false || strpos($subject_name, 'গণিত') !== false) {
                $science_math_subjects[] = $result;
            }
            // Check for ICT and Economics subjects (go at the bottom)
            else if (strpos($subject_name, 'ict') !== false || 
                     strpos($subject_name, 'economics') !== false || strpos($subject_name, 'অর্থনীতি') !== false) {
                $ict_economics_subjects[] = $result;
            }
            // Check for Career Education
            else if (strpos($subject_name, 'career') !== false || strpos($subject_name, 'ক্যারিয়ার') !== false) {
                $career_edu = $result;
            }
            // Check for Agricultural Education
            else if (strpos($subject_name, 'agricultural') !== false || strpos($subject_name, 'কৃষি') !== false) {
                $agri_edu = $result;
            }
            // All other subjects
            else {
                $middle_subjects[] = $result;
            }
        }
        
        // Apply custom layout only to middle subjects (excluding Science/Math and ICT/Economics)
        $ordered_middle_subjects = applyCustomLayout($middle_subjects, $layout);
        
        // Combine all subjects in the required order
        // Order: Bangla subjects -> English subjects -> Science/Math -> Other subjects (with custom layout) -> ICT/Economics -> Career Edu -> Agricultural Edu
        $combined_middle = array_merge($science_math_subjects, $ordered_middle_subjects, $ict_economics_subjects);
        
        // Add Career Education if it exists
        if ($career_edu !== null) {
            $combined_middle[] = $career_edu;
        }
        
        // Combine all subjects in the required order
        $results = array_merge($bangla_results, $english_results, $combined_middle);
        
        // Add Agricultural Education at the very end if it exists
        if ($agri_edu !== null) {
            $results[] = $agri_edu;
        }
        
        // Re-index the results array
        $results = array_values($results);
        
        // No special handling needed for combined subjects since we're keeping them separate
        
        // Enhance results with subject-specific marks distribution and GP
        foreach ($results as &$result) {
            // Try to get subject-specific mark distribution
            $stmt = $pdo->prepare("
                SELECT total_marks, overall_pass_marks 
                FROM subject_mark_distribution 
                WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                LIMIT 1
            ");
            $stmt->execute([
                $result['subject_id'], 
                $student['class_id'], 
                $session, 
                $exam_type
            ]);
            $smd = $stmt->fetch();
            
            if ($smd) {
                $result['full_marks'] = $smd['total_marks'];
                $result['pass_marks'] = $smd['overall_pass_marks'];
            } else {
                // Fallback to mark_distributions
                $stmt = $pdo->prepare("
                    SELECT total_marks, pass_marks as overall_pass_marks 
                    FROM mark_distributions 
                    WHERE subject_id = ? AND class_id = ? AND session = ? AND exam_type = ?
                    LIMIT 1
                ");
                $stmt->execute([
                    $result['subject_id'], 
                    $student['class_id'], 
                    $session, 
                    $exam_type
                ]);
                $md = $stmt->fetch();
                
                if ($md) {
                    $result['full_marks'] = $md['total_marks'];
                    $result['pass_marks'] = $md['overall_pass_marks'];
                } else {
                    // Default values
                    $result['full_marks'] = 100;
                    $result['pass_marks'] = 33; // Use 40 as default passing marks as requested
                }
            }
            
            // Add subject-based GP (Grade Point)
            $result['grade_point'] = getGradePoint($result['grade']);
            
            // For all subjects (including Bangla, Bangla Grammar, English, English Grammar)
            $stmt = $pdo->prepare("SELECT MAX(marks_obtained) as max_marks FROM results WHERE subject_id = ? AND session = ? AND exam_type = ? AND student_id IN (SELECT id FROM students WHERE class_id = ? AND status = 'active')");
            $stmt->execute([$result['subject_id'], $session, $exam_type, $student['class_id']]);
            $max_result = $stmt->fetch();
            $result['class_max_marks'] = $max_result['max_marks'] ?? 0;
            
            // Check if this subject is a fourth subject
            $stmt = $pdo->prepare("
                SELECT is_fourth_subject 
                FROM student_subjects 
                WHERE student_id = ? AND subject_id = ?
                LIMIT 1
            ");
            $stmt->execute([$student_id, $result['subject_id']]);
            $subject_info = $stmt->fetch();
            
            $result['is_fourth_subject'] = $subject_info && $subject_info['is_fourth_subject'] ? true : false;
            
            // No custom grading needed as we're keeping subjects separate
        }
        unset($result); // Break the reference with the last element
        
        // Calculate totals and GPA with Jessore Board 4th subject rules
        $total_marks = 0;
        $total_obtained = 0;
        $total_subjects = count($results);
        $passed_subjects = 0;
        $total_grade_points = 0;
        $gpa_subjects = 0; // Subjects used for GPA calculation (excluding failed subjects)
        $has_failed_in_non_fourth_subject = false; // Track if student failed in any non-fourth subject
        $fourth_subject_grade_point = 0; // Track 4th subject grade point for adjustment
        $fourth_subject_found = false; // Track if 4th subject exists
        
        foreach ($results as $result) {
            $total_marks += $result['full_marks'];
            $total_obtained += $result['marks_obtained'];
            
            // Check if student failed in this subject and it's not a fourth subject
            if ($result['grade'] == 'F' && !(isset($result['is_fourth_subject']) && $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 (isset($result['is_fourth_subject']) && $result['is_fourth_subject']) {
                    $fourth_subject_found = true;
                    $fourth_subject_grade_point = $result['grade_point'];
                    // For 4th subject: if GPA > 2.00, subtract 2.00, otherwise subtract 0
                    // Modified to match the requirement: if 4th subject marks > 2, subtract 2, otherwise subtract 0
                    $adjusted_grade_point = ($result['grade_point'] > 2.00) ? ($result['grade_point'] - 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;
        
        // If student failed in any non-fourth subject OR has missing marks, overall grade is F and GPA is 0
        if ($has_failed_in_non_fourth_subject || $has_missing_marks) {
            $overall_grade = 'F';
            $gpa = 0.00;
        } else {
            $overall_grade = calculateOverallGrade($percentage, $passed_subjects, $total_subjects);
            
            // Calculate GPA (Grade Point Average) with Jessore Board rules
            if ($gpa_subjects > 0) {
                // 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
                    $gpa = round($total_grade_points / ($gpa_subjects - 1), 2);
                } else {
                    // Normal calculation
                    $gpa = round($total_grade_points / $gpa_subjects, 2);
                }
            } else {
                $gpa = 0.00; // GPA is 0.00 if all subjects are failed
            }
        }
        
        // Calculate merit position based on GPA
        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 all subjects selected by the student from student_subjects table
                $stmt = $pdo->prepare("SELECT ss.subject_id FROM student_subjects ss WHERE ss.student_id = ?");
                $stmt->execute([$sid]);
                $all_student_subjects = $stmt->fetchAll();
                
                // Get student results with subject names
                $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)");
                $stmt->execute([$sid, $session, $exam_type, $sid, $session, $exam_type]);
                $student_results = $stmt->fetchAll();
                
                // Create a map of results by subject_id for easy lookup
                $results_map = [];
                foreach ($student_results as $result) {
                    $results_map[$result['subject_id']] = $result;
                }
                
                // Create combined results array with all subjects
                $processed_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])) {
                        $processed_results[] = $results_map[$subject_id];
                    } else {
                        // If student doesn't have marks, create a placeholder result with 'F' grade
                        $processed_results[] = [
                            'subject_id' => $subject_id,
                            'grade' => 'F',
                            'grade_point' => 0.00,
                            'is_fourth_subject' => false
                        ];
                        $has_missing_marks = true; // Mark that we have missing marks
                    }
                }
                
                if (empty($processed_results)) {
                    $student_gpas[$sid] = 0.00;
                    continue;
                }
                
                // Calculate GPA using the same logic as for the current student
                $total_grade_points = 0;
                $gpa_subjects = 0;
                $has_failed_in_non_fourth_subject = false;
                $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) {
                        $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) {
                            $fourth_subject_found = true;
                            // For 4th subject: if GPA > 2.00, subtract 2.00, otherwise subtract 0
                            $adjusted_grade_point = ($grade_point > 2.00) ? ($grade_point - 2.00) : $grade_point;
                            $total_grade_points += $adjusted_grade_point;
                        } else {
                            // Regular subject - add full grade point
                            $total_grade_points += $grade_point;
                        }
                        $gpa_subjects++;
                    }
                }
                
                // Calculate final GPA for this student using the same logic as for current student
                if ($has_failed_in_non_fourth_subject || $has_missing_marks) {
                    $student_gpas[$sid] = 0.00;
                } else {
                    if ($gpa_subjects > 0) {
                        // For Jessore Board: when 4th subject exists, divide by (number of subjects - 1)
                        if ($fourth_subject_found) {
                            $student_gpa = round($total_grade_points / ($gpa_subjects - 1), 2);
                        } else {
                            $student_gpa = round($total_grade_points / $gpa_subjects, 2);
                        }
                        $student_gpas[$sid] = $student_gpa;
                    } 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;
        }
    }
}

// Functions removed as we're keeping subjects separate

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

// Custom function to calculate English subject grade based on new criteria
// For English: CQ average > 32 to pass
function calculateEnglishGrade($cq_marks_array, $total_marks, $pass_marks) {
    // Calculate average of 2 CQ marks
    $cq_average = 0;
    if (count($cq_marks_array) >= 2) {
        $cq_average = ($cq_marks_array[0] + $cq_marks_array[1]) / 2;
    } else if (count($cq_marks_array) == 1) {
        $cq_average = $cq_marks_array[0];
    }
    
    // For English: CQ average > 32 to pass
    if ($cq_average > 32) {
        // Calculate 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 apply custom layout to results
function applyCustomLayout($results, $layout_name = null) {
    // If no layout specified, check for default layout
    if ($layout_name === null && isset($_SESSION['default_layout'])) {
        $layout_name = $_SESSION['default_layout'];
    }
    
    // Also check for subject layout from marks setup
    $subject_layout_name = null;
    if (isset($_SESSION['default_subject_layout'])) {
        $subject_layout_name = $_SESSION['default_subject_layout'];
    }
    
    // Determine which layout to use
    $actual_layout_name = null;
    $layout_source = null;
    
    // Priority: explicit layout > custom layout > subject layout
    if ($layout_name !== null && isset($_SESSION['custom_layout_' . $layout_name])) {
        $actual_layout_name = $layout_name;
        $layout_source = 'custom_layout_';
    } else if (isset($_SESSION['default_layout']) && isset($_SESSION['custom_layout_' . $_SESSION['default_layout']])) {
        $actual_layout_name = $_SESSION['default_layout'];
        $layout_source = 'custom_layout_';
    } else if ($subject_layout_name !== null && isset($_SESSION['subject_layout_' . $subject_layout_name])) {
        $actual_layout_name = $subject_layout_name;
        $layout_source = 'subject_layout_';
    } else if (isset($_SESSION['default_subject_layout']) && isset($_SESSION['subject_layout_' . $_SESSION['default_subject_layout']])) {
        $actual_layout_name = $_SESSION['default_subject_layout'];
        $layout_source = 'subject_layout_';
    }
    
    // If we have a layout name, apply it
    if ($actual_layout_name !== null && $layout_source !== null && isset($_SESSION[$layout_source . $actual_layout_name])) {
        $saved_order = explode(',', $_SESSION[$layout_source . $actual_layout_name]);
        $ordered_results = [];
        
        // First add subjects in the saved order
        foreach ($saved_order as $subject_id) {
            // Convert to string for consistent comparison
            $subject_id_str = (string)$subject_id;
            foreach ($results as $result) {
                if (isset($result['subject_id']) && (string)$result['subject_id'] === $subject_id_str) {
                    $ordered_results[] = $result;
                    break;
                }
            }
        }
        
        // Then add any remaining subjects not in the saved order
        foreach ($results as $result) {
            $found = false;
            foreach ($saved_order as $subject_id) {
                // Convert to string for consistent comparison
                $subject_id_str = (string)$subject_id;
                if (isset($result['subject_id']) && (string)$result['subject_id'] === $subject_id_str) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $ordered_results[] = $result;
            }
        }
        
        return $ordered_results;
    }
    
    // Return results sorted by subject name if no layout to apply (matches subject list default ordering)
    usort($results, function($a, $b) {
        return strcmp($a['subject_name'], $b['subject_name']);
    });
    return $results;
}

// 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();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>সেপারেট বাংলা & ইংরেজি মার্কশীট - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            font-size: 12px; /* Reduced from default */
        }
        
        .marksheet {
            border: 2px solid #2c3e50;
            padding: 15px; /* Reduced from 20px */
            margin: 15px auto; /* Reduced from 20px */
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            border-radius: 8px; /* Reduced from 12px */
            max-width: 800px; /* Reduced from 900px */
            position: relative;
            overflow: hidden;
        }
        
        .school-header {
            text-align: center;
            border-bottom: 2px double #3498db;
            padding-bottom: 10px; /* Reduced from 15px */
            margin-bottom: 15px; /* Reduced from 20px */
            background: linear-gradient(to right, #ffffff, #e3f2fd, #ffffff);
            border-radius: 6px 6px 0 0; /* Reduced from 8px */
            margin-left: -15px; /* Reduced from -20px */
            margin-right: -15px; /* Reduced from -20px */
            padding-left: 15px; /* Reduced from 20px */
            padding-right: 15px; /* Reduced from 20px */
            position: relative;
        }
        
        .school-logo {
            width: 60px; /* Reduced from 80px */
            height: 60px; /* Reduced from 80px */
            border: 2px solid #3498db; /* Reduced from 3px */
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 8px; /* Reduced from 12px */
            background: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* Reduced from 0 4px 8px */
            overflow: hidden;
        }
        
        .school-header h3 {
            color: #2c3e50;
            font-weight: 700;
            margin: 8px 0 3px 0; /* Reduced from 10px 0 5px 0 */
            text-shadow: 1px 1px 1px rgba(0,0,0,0.1); /* Reduced from 2px */
            font-size: 20px; /* Reduced from 24px */
        }
        
        .school-header h4 {
            color: #e74c3c;
            font-weight: 600;
            margin: 10px 0 0 0; /* Reduced from 15px */
            text-decoration: underline;
            text-underline-offset: 5px; /* Reduced from 8px */
            font-size: 16px; /* Reduced from 18px */
        }
        
        .student-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px; /* Reduced from 15px */
            margin-bottom: 15px; /* Reduced from 20px */
            background: #f8f9fa;
            padding: 12px; /* Reduced from 15px */
            border-radius: 6px; /* Reduced from 8px */
            border: 1px solid #e9ecef;
        }
        
        .info-row {
            display: flex;
            margin-bottom: 5px; /* Reduced from 8px */
            align-items: center;
        }
        
        .info-label {
            font-weight: 600;
            min-width: 100px; /* Reduced from 120px */
            color: #2c3e50;
            font-size: 12px; /* Reduced from 14px */
        }
        
        .info-value {
            border-bottom: 1px dotted #3498db; /* Reduced from 2px */
            flex: 1;
            padding-left: 8px; /* Reduced from 10px */
            font-weight: 500;
            color: #34495e;
            font-size: 12px; /* Reduced from 14px */
        }
        
        .marks-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0; /* Reduced from 20px */
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05); /* Reduced from 0 2px 10px */
            border-radius: 6px; /* Reduced from 8px */
            overflow: hidden;
            font-size: 11px; /* Reduced from default */
        }
        
        .marks-table th,
        .marks-table td {
            border: 1px solid #dee2e6;
            padding: 6px; /* Reduced from 8px */
            text-align: center;
            font-size: 11px; /* Reduced from 14px */
        }
        
        .marks-table th {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px; /* Reduced from 0.5px */
        }
        
        .marks-table tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .marks-table tbody tr:hover {
            background-color: #e3f2fd;
            transition: background-color 0.2s; /* Reduced from 0.3s */
        }
        
        .result-summary {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px; /* Reduced from 25px */
            margin-top: 15px; /* Reduced from 20px */
            padding-top: 15px; /* Reduced from 20px */
            border-top: 1px dashed #3498db; /* Reduced from 2px */
            background: #f8f9fa;
            padding: 12px; /* Reduced from 15px */
            border-radius: 6px; /* Reduced from 8px */
        }
        
        .signature-section {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px; /* Reduced from 25px */
            margin-top: 20px; /* Reduced from 30px */
            text-align: center;
        }
        
        .signature-box {
            border-top: 1px solid #3498db; /* Reduced from 2px */
            padding-top: 8px; /* Reduced from 10px */
            margin-top: 20px; /* Reduced from 30px */
            font-weight: 600;
            color: #2c3e50;
            font-size: 12px; /* Reduced from 14px */
        }
        
        .grade-scale {
            font-size: 9px; /* Reduced from 12px */
            margin-top: 20px; /* Reduced from 25px */
            padding: 10px; /* Reduced from 15px */
            background: #e3f2fd;
            border-radius: 6px; /* Reduced from 8px */
            border-left: 2px solid #3498db; /* Reduced from 4px */
        }
        
        .grade-scale strong {
            color: #2c3e50;
        }
        
        .student-list-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0; /* Reduced from 20px */
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05); /* Reduced from 0 2px 10px */
            border-radius: 6px; /* Reduced from 8px */
            overflow: hidden;
            font-size: 12px; /* Reduced from default */
        }
        
        .student-list-table th,
        .student-list-table td {
            border: 1px solid #dee2e6;
            padding: 8px; /* Reduced from 12px */
            text-align: center;
        }
        
        .student-list-table th {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            font-weight: 600;
        }
        
        .student-list-table tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .student-list-table tbody tr:hover {
            background-color: #e3f2fd;
            cursor: pointer;
            transition: background-color 0.2s; /* Reduced from 0.3s */
        }
        
        @media print {
            .no-print { display: none !important; }
            .container-fluid { max-width: 100% !important; }
            body { 
                font-size: 10px; /* Reduced for print */
                font-family: 'Hind Siliguri', sans-serif;
            }
            .marksheet { 
                page-break-inside: avoid; 
                box-shadow: none;
                border: 2px solid #000 !important;
                padding: 10px;
                background: white;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .marksheet::before {
                opacity: 0.03; /* Reduced from 0.05 */
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .school-header {
                border-bottom: 2px solid #000 !important;
                background: white;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .school-logo {
                border: 1px solid #000; /* Reduced from 2px */
                box-shadow: none;
                width: 50px; /* Reduced for print */
                height: 50px; /* Reduced for print */
                display: block !important;
            }
            
            .school-logo img {
                max-height: 50px !important;
                width: auto !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .marks-table th {
                background: #f8f9fa;
                color: #000;
            }
            
            /* Ensure borders appear in print */
            .marks-table,
            .marks-table th,
            .marks-table td,
            .student-info,
            .result-summary,
            .signature-section {
                border: 1px solid #000 !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .marks-table th {
                background: #e9ecef !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .student-info,
            .result-summary {
                background: #f8f9fa !important;
                border: 1px solid #e9ecef !important;
                border-radius: 6px !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .signature-section {
                display: grid;
                grid-template-columns: 1fr 1fr 1fr;
                gap: 15px;
                margin-top: 20px;
                text-align: center;
            }
            
            .signature-box {
                border-top: 1px solid #3498db !important;
                padding-top: 8px;
                margin-top: 20px;
                font-weight: 600;
                color: #2c3e50;
                font-size: 12px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            /* Header styles */
            .school-header h3 {
                color: #2c3e50 !important;
                font-weight: 700;
                margin: 8px 0 3px 0;
                text-shadow: 1px 1px 1px rgba(0,0,0,0.1);
                font-size: 20px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .school-header h4 {
                color: #e74c3c !important;
                font-weight: 600;
                margin: 10px 0 0 0;
                text-decoration: underline;
                text-underline-offset: 5px;
                font-size: 16px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            /* Hide all watermark images when printing */
            .marksheet img[alt=''] {
                display: none !important;
            }
            /* Student photo styles */
            .student-photo {
                display: block;
            }
            
            .student-photo-print {
                max-width: 100px;
                max-height: 120px;
                border: 2px solid #3498db;
                border-radius: 5px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            
            /* Student photo print styles */
            .student-photo {
                display: block !important;
            }
            
            .student-photo-print {
                max-width: 80px !important;
                max-height: 100px !important;
                border: 1px solid #000 !important;
                border-radius: 3px !important;
                box-shadow: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <?php if ($student_id && $session && $exam_type): ?>
        <div class="text-center mb-3 no-print">
            <button onclick="window.print()" class="btn btn-success"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
            <a href="combined_bangla_english_marksheet.php" class="btn btn-primary"><i class="fas fa-search"></i> নতুন অনুসন্ধান</a>
            <a href="../index.php" class="btn btn-secondary"><i class="fas fa-home"></i> হোম</a>
        </div>
        
        <div class="marksheet">
            <div class="school-header">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <!-- School Logo - Left -->
                    <div class="school-logo">
                        <?php if ($logo_image): ?>
                            <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" style="max-height: <?php echo $logo_size; ?>px; width: auto;">
                        <?php else: ?>
                            <i class="fas fa-graduation-cap"></i>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Institution Name and Address - Center -->
                    <div style="text-align: center; flex-grow: 1; padding: 0 20px;">
                        <h3 style="font-size: 24px; margin: 0 0 5px 0;"><?php echo htmlspecialchars($site_name); ?></h3>
                        <p style="color: #7f8c8d; margin: 0 0 5px 0; font-size: 14px;"><?php echo htmlspecialchars($site_address); ?></p>
                        <h4 style="font-size: 18px; margin: 0;">Separate Bangla & English Marksheet</h4>
                    </div>
                    
                    <!-- Student Photo - Right -->
                    <div style="text-align: right;" class="student-photo">
                        <?php if (!empty($student['photo']) && file_exists(__DIR__ . '/' . $student['photo'])): ?>
                            <img src="<?php echo htmlspecialchars($student['photo']); ?>" alt="Student Photo" class="student-photo-print" style="max-width: 100px; max-height: 120px; border: 2px solid #3498db; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                        <?php else: ?>
                            <div style="width: 100px; height: 120px; border: 2px dashed #3498db; border-radius: 5px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa;">
                                <i class="fas fa-user" style="font-size: 36px; color: #3498db;"></i>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Watermark Logos -->
            <?php if ($logo_image): ?>
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(45deg); opacity: 0.05; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 3); ?>px; height: <?php echo ($logo_size * 3); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; top: 20%; left: 20%; transform: rotate(30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; top: 20%; right: 20%; transform: rotate(-30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; bottom: 20%; left: 20%; transform: rotate(-30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
                <div style="position: absolute; bottom: 20%; right: 20%; transform: rotate(30deg); opacity: 0.03; z-index: -1; pointer-events: none;">
                    <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="" style="width: <?php echo ($logo_size * 1.5); ?>px; height: <?php echo ($logo_size * 1.5); ?>px; object-fit: contain;">
                </div>
            <?php endif; ?>
            
            <div class="student-info">
                <div>
                    <div class="info-row">
                        <div class="info-label">শিক্ষার্থী আইডি</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['student_id']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পিতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['father_name'] ?? ''); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">মাতার নাম</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['mother_name'] ?? ''); ?></div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">রোল নম্বর</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['roll_number']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শ্রেণী</div>
                        <div class="info-value"><?php echo htmlspecialchars($student['class_name'] . ' ' . $student['section']); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">সেশন</div>
                        <div class="info-value"><?php echo htmlspecialchars($session); ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">পরীক্ষার ধরন</div>
                        <div class="info-value"><?php echo htmlspecialchars(ucfirst($exam_type)); ?></div>
                    </div>
                </div>
            </div>
            
            <table class="marks-table">
                <thead>
                    <tr>
                        <th rowspan="2">বিষয়</th>
                        <th colspan="5">প্রাপ্ত নম্বর</th>
                        <th rowspan="2">প্রাপ্ত<br>নম্বর</th>
                        <th rowspan="2">পাস<br>নম্বর</th>
                        <th rowspan="2">গ্রেড</th>
                        <th rowspan="2">জিপি</th>
                    </tr>
                    <tr>
                        <th>সৃজনশীল</th>
                        <th>বহুনির্বাচনি</th>
                        <th>ব্যবহারিক</th>
                        <th>অ্যাসাইনমেন্ট</th>
                        <th>শ্রেণিতে<br>সর্বোচ্চ</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    // Display regular subjects (excluding 4th subject)
                    foreach ($results as $result): 
                        if (!(isset($result['is_fourth_subject']) && $result['is_fourth_subject'])): ?>
                    <tr>
                        <td style="text-align: left; padding-left: 15px; font-weight: 500;"><?php echo htmlspecialchars($result['subject_name']); ?></td>
                        <td>
                            <?php 
                            echo htmlspecialchars(floor($result['cq_marks']) ?: '-');
                            ?>
                        </td>
                        <td>
                            <?php 
                            echo htmlspecialchars(floor($result['mcq_marks']) ?: '-');
                            ?>
                        </td>
                        <td><?php echo htmlspecialchars($result['practical_marks'] ?: '-'); ?></td>
                        <td><?php echo htmlspecialchars($result['assignment_marks'] ?: '-'); ?></td>
                        <td><?php echo htmlspecialchars($result['class_max_marks'] ?: '-'); ?></td>
                        <td style="font-weight: 600;"><?php echo htmlspecialchars($result['marks_obtained']); ?></td>
                        <td><?php echo htmlspecialchars($result['pass_marks']); ?></td>
                        <td style="font-weight: 700; 
                            <?php 
                            switch ($result['grade']) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo htmlspecialchars($result['grade']); ?>
                        </td>
                        <td><?php echo number_format($result['grade_point'], 2); ?></td>
                    </tr>
                    <?php 
                        endif;
                    endforeach; 
                    
                    // Display 4th subject at the end
                    foreach ($results as $result): 
                        if (isset($result['is_fourth_subject']) && $result['is_fourth_subject']): ?>
                    <tr style="background-color: #e3f2fd; font-weight: bold;">
                        <td style="text-align: left; padding-left: 15px; font-weight: 500;"><?php echo htmlspecialchars($result['subject_name']); ?></td>
                        <td>
                            <?php 
                            echo htmlspecialchars(floor($result['cq_marks']) ?: '-');
                            ?>
                        </td>
                        <td>
                            <?php 
                            echo htmlspecialchars(floor($result['mcq_marks']) ?: '-');
                            ?>
                        </td>
                        <td><?php echo htmlspecialchars($result['practical_marks'] ?: '-'); ?></td>
                        <td><?php echo htmlspecialchars($result['assignment_marks'] ?: '-'); ?></td>
                        <td><?php echo htmlspecialchars($result['class_max_marks'] ?: '-'); ?></td>
                        <td style="font-weight: 600;"><?php echo htmlspecialchars($result['marks_obtained']); ?></td>
                        <td><?php echo htmlspecialchars($result['pass_marks']); ?></td>
                        <td style="font-weight: 700; 
                            <?php 
                            switch ($result['grade']) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo htmlspecialchars($result['grade']); ?>
                        </td>
                        <td><?php echo number_format($result['grade_point'], 2); ?></td>
                    </tr>
                    <?php 
                        break; // Display only the first 4th subject
                        endif;
                    endforeach; 
                    ?>

                </tbody>
            </table>
            
            <div class="result-summary">
                <div>
                    <div class="info-row">
                        <div class="info-label">মোট নম্বর</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo $total_obtained; ?>/<?php echo $total_marks; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শতাংশ</div>
                        <div class="info-value" style="font-weight: 700; color: #3498db;"><?php echo $percentage; ?>%</div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">গ্রেড</div>
                        <div class="info-value" style="font-weight: 700; font-size: 18px; 
                            <?php 
                            // Calculate grade based on GPA instead of percentage
                            $gpa_based_grade = calculateGradeFromGPA($gpa);
                            switch ($gpa_based_grade) {
                                case 'A+': echo 'color: #27ae60;'; break;
                                case 'A': echo 'color: #2ecc71;'; break;
                                case 'A-': echo 'color: #3498db;'; break;
                                case 'B': echo 'color: #9b59b6;'; break;
                                case 'C': echo 'color: #f39c12;'; break;
                                case 'D': echo 'color: #e67e22;'; break;
                                case 'F': echo 'color: #e74c3c;'; break;
                                default: echo 'color: #34495e;';
                            }
                            ?>">
                            <?php echo $gpa_based_grade; ?>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="info-row">
                        <div class="info-label">জিপিএ</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo number_format($gpa, 2); ?></div>
                    </div>
                    <?php if ($merit_position): ?>
                    <div class="info-row">
                        <div class="info-label">মেরিট পজিশন</div>
                        <div class="info-value" style="font-weight: 700; 
                            <?php 
                            if ($merit_position == 1) {
                                echo 'color: #f1c40f; font-size: 20px;';
                            } elseif ($merit_position <= 3) {
                                echo 'color: #9b59b6; font-size: 18px;';
                            } else {
                                echo 'color: #3498db;';
                            }
                            ?>">
                            <?php echo $merit_position; ?>
                            <?php if ($merit_position == 1): ?>
                                <i class="fas fa-trophy" style="color: #f1c40f;"></i>
                            <?php elseif ($merit_position == 2): ?>
                                <i class="fas fa-medal" style="color: #aaa;"></i>
                            <?php elseif ($merit_position == 3): ?>
                                <i class="fas fa-medal" style="color: #cd7f32;"></i>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="signature-section">
                <div>
                    <div class="signature-box" style="font-weight: 600; color: #2c3e50;">শিক্ষার্থীর স্বাক্ষর</div>
                </div>
                <div>
                    <div class="signature-box" style="font-weight: 600; color: #2c3e50;">শিক্ষকের স্বাক্ষর</div>
                </div>
                <div>
                    <div class="signature-box" style="font-weight: 600; color: #2c3e50;">অধ্যাপকের স্বাক্ষর</div>
                </div>
            </div>
        </div>
        <?php elseif ($show_student_list): ?>
        <!-- Student List View -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4 class="card-title mb-0">শিক্ষার্থী নির্বাচন করুন</h4>
                <div>
                    <a href="combined_bangla_english_marksheet.php" class="btn btn-secondary btn-sm me-2">
                        <i class="fas fa-arrow-left"></i> পিছনে
                    </a>
                    <a href="../index.php" class="btn btn-secondary btn-sm">
                        <i class="fas fa-home"></i> হোম
                    </a>
                </div>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <h5>Class: 
                            <?php 
                            $selected_class = array_filter($classes, function($c) use ($class_id) { return $c['id'] == $class_id; });
                            echo !empty($selected_class) ? htmlspecialchars(reset($selected_class)['name'] . ' ' . reset($selected_class)['section']) : '';
                            ?>
                        </h5>
                    </div>
                    <div class="col-md-6">
                        <h5>Session: <?php echo htmlspecialchars($session); ?> | Exam Type: <?php echo htmlspecialchars(ucfirst($exam_type)); ?></h5>
                    </div>
                </div>
                
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" id="student-search" class="form-control" placeholder="শিক্ষার্থী খুঁজুন (নাম, রোল, আইডি)" value="<?php echo htmlspecialchars($student_search); ?>">
                            <button class="btn btn-outline-secondary" type="button" id="search-btn">
                                <i class="fas fa-search"></i> খুঁজুন
                            </button>
                        </div>
                    </div>
                    <?php if (!empty($students_in_class)): ?>
                    <div class="col-md-6 text-end">
                        <button class="btn btn-success" id="bulk-print-btn">
                            <i class="fas fa-print"></i> সবগুলো প্রিন্ট করুন
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="table-responsive" id="student-table-container">
                    <?php if (empty($students_in_class)): ?>
                        <div class="alert alert-info text-center">
                            <i class="fas fa-info-circle"></i> কোন তথ্য পাওয়া যায়নি
                        </div>
                    <?php else: ?>
                        <table class="student-list-table">
                            <thead>
                                <tr>
                                    <th>রোল</th>
                                    <th>শিক্ষার্থী আইডি</th>
                                    <th>নাম</th>
                                    <th>কার্যক্রম</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($students_in_class as $student_item): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($student_item['roll_number']); ?></td>
                                    <td><?php echo htmlspecialchars($student_item['student_id']); ?></td>
                                    <td><?php echo htmlspecialchars($student_item['first_name'] . ' ' . $student_item['last_name']); ?></td>
                                    <td>
                                        <a href="?student_id=<?php echo $student_item['id']; ?>&session=<?php echo urlencode($session); ?>&exam_type=<?php echo urlencode($exam_type); ?>" class="btn btn-primary btn-sm">
                                            <i class="fas fa-eye"></i> ফলাফল দেখুন
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <script>
            // Handle search button click
            document.getElementById('search-btn').addEventListener('click', function() {
                performSearch();
            });
            
            // Handle Enter key in search box
            document.getElementById('student-search').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    performSearch();
                }
            });
            
            // Make search dynamic with AJAX
            let searchTimeout;
            document.getElementById('student-search').addEventListener('input', function() {
                const searchTerm = this.value;
                // Clear previous timeout
                clearTimeout(searchTimeout);
                
                // Set new timeout
                searchTimeout = setTimeout(function() {
                    if (searchTerm.length >= 2 || searchTerm.length === 0) {
                        performSearch();
                    }
                }, 300); // 300ms delay
            });
            
            function performSearch() {
                const searchTerm = document.getElementById('student-search').value;
                const classId = '<?php echo $class_id; ?>';
                const session = '<?php echo $session; ?>';
                const examType = '<?php echo $exam_type; ?>';
                
                // Show loading indicator
                const container = document.getElementById('student-table-container');
                container.innerHTML = '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>';
                
                // Add CSS for spinner if not already present
                if (!document.getElementById('spinner-styles')) {
                    const style = document.createElement('style');
                    style.id = 'spinner-styles';
                    style.innerHTML = `
                        .spinner-border {
                            display: inline-block;
                            width: 2rem;
                            height: 2rem;
                            vertical-align: -0.125em;
                            border: 0.25em solid currentColor;
                            border-right-color: transparent;
                            border-radius: 50%;
                            animation: spinner-border 0.75s linear infinite;
                        }
                        @keyframes spinner-border {
                            to {
                                transform: rotate(360deg);
                            }
                        }
                        .text-primary {
                            color: #0d6efd;
                        }
                        .visually-hidden {
                            position: absolute;
                            width: 1px;
                            height: 1px;
                            padding: 0;
                            margin: -1px;
                            overflow: hidden;
                            clip: rect(0, 0, 0, 0);
                            white-space: nowrap;
                            border: 0;
                        `
                    document.head.appendChild(style)
                }
                
                // For dynamic search, we'll use AJAX to update the table without page reload
                fetch(`marksheet_search.php?class_id=${classId}&session=${session}&exam_type=${examType}&student_search=${encodeURIComponent(searchTerm)}`)
                    .then(response => response.text())
                    .then(data => {
                        container.innerHTML = data;
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        container.innerHTML = '<div class="alert alert-danger text-center">Error occurred, please try again</div>';
                    });
            }
            
            function selectStudent(studentId) {
                const session = '<?php echo $session; ?>';
                const examType = '<?php echo $exam_type; ?>';
                window.location.href = `?student_id=${studentId}&session=${session}&exam_type=${examType}`;
            }
        </script>
        <?php else: ?>
        <!-- Initial Search Form -->
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">সেপারেট বাংলা & ইংরেজি মার্কশীট অনুসন্ধান করুন</h4>
            </div>
            <div class="card-body">
                <form method="GET" action="" class="row g-3">
                    <div class="col-md-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-12 text-center mt-3">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search"></i> শিক্ষার্থী তালিকা দেখুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Add bulk print functionality
    document.addEventListener('DOMContentLoaded', function() {
        const bulkPrintBtn = document.getElementById('bulk-print-btn');
        if (bulkPrintBtn) {
            bulkPrintBtn.addEventListener('click', function() {
                // Get current search parameters
                const urlParams = new URLSearchParams(window.location.search);
                const classId = urlParams.get('class_id');
                const session = urlParams.get('session');
                const examType = urlParams.get('exam_type');
                const studentSearch = urlParams.get('student_search') || '';
                
                // Redirect to bulk print page with same parameters
                const bulkPrintUrl = `bulk_print_marksheets.php?class_id=${encodeURIComponent(classId)}&session=${encodeURIComponent(session)}&exam_type=${encodeURIComponent(examType)}&student_search=${encodeURIComponent(studentSearch)}`;
                window.open(bulkPrintUrl, '_blank');
            });
        }
    });
    </script>
</body>
</html>