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

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

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

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

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

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

    if ($class_id && empty($publication_message)) {
        // Get student details from roll_number, class_id and session
        $stmt = $pdo->prepare("
            SELECT s.*, c.name as class_name, c.section 
            FROM students s 
            JOIN classes c ON s.class_id = c.id 
            WHERE s.roll_number = ? AND s.class_id = ? AND s.session = ?
        ");
        $stmt->execute([$roll, $class_id, $session]);
        $student = $stmt->fetch();
    }
    
    if ($student) {
        $student_id = $student['id'];
        // 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;
        }
        
        // 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();
        
        // 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
            }
        }
        
        // Keep all subjects separate - no grouping or combining
        // Bangla and Bangla Grammar remain separate
        // English and English Grammar remain separate
        // All other subjects remain as they are
        $grouped_results = $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();
            // Class 6, 7, 8: all subjects compulsory — no fourth subject
            $result['is_fourth_subject'] = !in_array((int)$class_id, [6,7,8])
                && $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' && !$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, 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
        if ($student && $session && $exam_type) {
            // Get all students in the same class with their total marks
            $stmt = $pdo->prepare("
                SELECT s.id, s.first_name, s.last_name, s.roll_number,
                       SUM(r.marks_obtained) as total_obtained
                FROM students s
                JOIN results r ON s.id = r.student_id
                WHERE s.class_id = ? AND r.session = ? AND r.exam_type = ?
                GROUP BY s.id, s.first_name, s.last_name, s.roll_number
                ORDER BY total_obtained DESC
            ");
            $stmt->execute([$student['class_id'], $session, $exam_type]);
            $class_results = $stmt->fetchAll();
            
            // Find the position of current student
            $position = 1;
            foreach ($class_results as $class_result) {
                if ($class_result['id'] == $student_id) {
                    $merit_position = $position;
                    break;
                }
                $position++;
            }
        }
    }
}

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

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

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

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

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>সেপারেট বাংলা & ইংরেজি মার্কশীট - <?php echo htmlspecialchars($site_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            font-size: 12px;
            background-color: #f8f9fa;
        }
        
        .search-container {
            max-width: 800px;
            margin: 30px auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            padding: 30px;
        }
        
        .marksheet {
            border: 2px solid #2c3e50;
            padding: 15px;
            margin: 15px auto;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            max-width: 800px;
            position: relative;
            overflow: hidden;
        }
        
        .school-header {
            text-align: center;
            border-bottom: 2px double #3498db;
            padding-bottom: 10px;
            margin-bottom: 15px;
            background: linear-gradient(to right, #ffffff, #e3f2fd, #ffffff);
            border-radius: 6px 6px 0 0;
            margin-left: -15px;
            margin-right: -15px;
            padding-left: 15px;
            padding-right: 15px;
            position: relative;
        }
        
        .school-logo {
            width: 60px;
            height: 60px;
            border: 2px solid #3498db;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 8px;
            background: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .school-header h3 {
            color: #2c3e50;
            font-weight: 700;
            margin: 8px 0 3px 0;
            text-shadow: 1px 1px 1px rgba(0,0,0,0.1);
            font-size: 20px;
        }
        
        .school-header h4 {
            color: #e74c3c;
            font-weight: 600;
            margin: 10px 0 0 0;
            text-decoration: underline;
            text-underline-offset: 5px;
            font-size: 16px;
        }
        
        .student-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 15px;
            background: #f8f9fa;
            padding: 12px;
            border-radius: 6px;
            border: 1px solid #e9ecef;
        }
        
        .info-row {
            display: flex;
            margin-bottom: 5px;
            align-items: center;
        }
        
        .info-label {
            font-weight: 600;
            min-width: 100px;
            color: #2c3e50;
            font-size: 12px;
        }
        
        .info-value {
            border-bottom: 1px dotted #3498db;
            flex: 1;
            padding-left: 8px;
            font-weight: 500;
            color: #34495e;
            font-size: 12px;
        }
        
        .marks-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
            border-radius: 6px;
            overflow: hidden;
            font-size: 11px;
        }
        
        .marks-table th,
        .marks-table td {
            border: 1px solid #dee2e6;
            padding: 6px;
            text-align: center;
            font-size: 11px;
        }
        
        .marks-table th {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }
        
        .marks-table tbody tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .marks-table tbody tr:hover {
            background-color: #e3f2fd;
            transition: background-color 0.2s;
        }
        
        .result-summary {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px dashed #3498db;
            background: #f8f9fa;
            padding: 12px;
            border-radius: 6px;
        }
        
        .signature-section {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;
            margin-top: 20px;
            text-align: center;
        }
        
        .signature-box {
            border-top: 1px solid #3498db;
            padding-top: 8px;
            margin-top: 20px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 12px;
        }
        
        .grade-scale {
            font-size: 9px;
            margin-top: 20px;
            padding: 10px;
            background: #e3f2fd;
            border-radius: 6px;
            border-left: 2px solid #3498db;
        }
        
        .grade-scale strong {
            color: #2c3e50;
        }
        
        @media print {
            .no-print { display: none !important; }
            .container { max-width: 100% !important; }
            body { 
                font-size: 10px;
                font-family: 'Hind Siliguri', sans-serif;
                background-color: white;
            }
            .marksheet { 
                page-break-inside: avoid; 
                box-shadow: none;
                border: 2px solid #000 !important;
                padding: 10px;
                background: white;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .marksheet::before {
                opacity: 0.03;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .school-header {
                border-bottom: 2px solid #000 !important;
                background: white;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .school-logo {
                border: 1px solid #000;
                box-shadow: none;
                width: 50px;
                height: 50px;
                display: block !important;
            }
            
            .school-logo img {
                max-height: 50px !important;
                width: auto !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .marks-table th {
                background: #f8f9fa;
                color: #000;
            }
            
            /* Ensure borders appear in print */
            .marks-table,
            .marks-table th,
            .marks-table td,
            .student-info,
            .result-summary,
            .signature-section {
                border: 1px solid #000 !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .marks-table th {
                background: #e9ecef !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .student-info,
            .result-summary {
                background: #f8f9fa !important;
                border: 1px solid #e9ecef !important;
                border-radius: 6px !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .signature-section {
                display: grid;
                grid-template-columns: 1fr 1fr 1fr;
                gap: 15px;
                margin-top: 20px;
                text-align: center;
            }
            
            .signature-box {
                border-top: 1px solid #3498db !important;
                padding-top: 8px;
                margin-top: 20px;
                font-weight: 600;
                color: #2c3e50;
                font-size: 12px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            /* Header styles */
            .school-header h3 {
                color: #2c3e50 !important;
                font-weight: 700;
                margin: 8px 0 3px 0;
                text-shadow: 1px 1px 1px rgba(0,0,0,0.1);
                font-size: 20px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .school-header h4 {
                color: #e74c3c !important;
                font-weight: 600;
                margin: 10px 0 0 0;
                text-decoration: underline;
                text-underline-offset: 5px;
                font-size: 16px;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            /* Hide all watermark images when printing */
            .marksheet img[alt=''] {
                display: none !important;
            }
            /* Student photo styles */
            .student-photo {
                display: block;
            }
            
            .student-photo-print {
                max-width: 100px;
                max-height: 120px;
                border: 2px solid #3498db;
                border-radius: 5px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            
            /* Student photo 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;
            }
        }
        
        .alert-box {
            max-width: 800px;
            margin: 30px auto;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
        
        .back-button {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <?php if ($student && empty($publication_message)): ?>
        <!-- Marksheet View -->
        <div class="text-center mb-3 no-print">
            <button onclick="history.back()" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> পেছনে</button>
            <button onclick="window.print()" class="btn btn-success"><i class="fas fa-print"></i> প্রিন্ট করুন</button>
            <a href="public_separate_bangla_english_marksheet.php" class="btn btn-primary"><i class="fas fa-search"></i> নতুন অনুসন্ধান</a>
            <a href="public_home.php" class="btn btn-info"><i class="fas fa-home"></i> হোম</a>
        </div>
        
        <div class="marksheet">
            <div class="school-header">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <!-- School Logo - Left -->
                    <div class="school-logo">
                        <?php if ($logo_image): ?>
                            <img src="<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" style="max-height: <?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($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 foreach ($results as $result): ?>
                    <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 endforeach; ?>
                    <!-- GPA Summary Row -->
                    <tr style="background-color: #e3f2fd; font-weight: bold;">
                        <td colspan="9" style="text-align: right; padding-right: 15px;">জিপিএ (Grade Point Average):</td>
                        <td><?php echo number_format($gpa, 2); ?></td>
                    </tr>
                </tbody>
            </table>
            
            <div class="result-summary">
                <div>
                    <div class="info-row">
                        <div class="info-label">মোট নম্বর</div>
                        <div class="info-value" style="font-weight: 700; color: #2c3e50;"><?php echo $total_obtained; ?>/<?php echo $total_marks; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">শতাংশ</div>
                        <div class="info-value" style="font-weight: 700; color: #3498db;"><?php echo $percentage; ?>%</div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">গ্রেড</div>
                        <div class="info-value" style="font-weight: 700; font-size: 18px; 
                            <?php 
                            // Calculate grade based on 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 (!empty($publication_message)): ?>
        <!-- Publication Message -->
        <div class="alert alert-warning alert-box">
            <h4><i class="fas fa-exclamation-triangle"></i> নোটিশ</h4>
            <p><?php echo htmlspecialchars($publication_message); ?></p>
            <a href="public_separate_bangla_english_marksheet.php" class="btn btn-primary"><i class="fas fa-search"></i> আবার চেষ্টা করুন</a>
            <a href="public_home.php" class="btn btn-info"><i class="fas fa-home"></i> হোম</a>
        </div>
        
        <?php else: ?>
        <!-- Search Form -->
        <div class="search-container">
            <h2 class="text-center mb-4">সেপারেট বাংলা & ইংরেজি মার্কশীট অনুসন্ধান</h2>
            
            <form method="GET" action="" class="row g-3">
                <div class="col-md-6">
                    <label for="class" class="form-label">শ্রেণী</label>
                    <select id="class" name="class" class="form-select" required>
                        <option value="">শ্রেণী নির্বাচন করুন</option>
                        <?php foreach ($all_classes as $class_item): ?>
                            <option value="<?php echo htmlspecialchars($class_item); ?>" <?php echo ($class_name == $class_item) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($class_item); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-6">
                    <label for="session" class="form-label">সেশন</label>
                    <select id="session" name="session" class="form-select" required>
                        <option value="">সেশন নির্বাচন করুন</option>
                        <?php foreach ($all_sessions as $session_item): ?>
                            <option value="<?php echo htmlspecialchars($session_item); ?>" <?php echo ($session == $session_item) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($session_item); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-6">
                    <label for="exam" class="form-label">পরীক্ষার ধরন</label>
                    <select id="exam" name="exam" class="form-select" required>
                        <option value="">পরীক্ষা নির্বাচন করুন</option>
                        <?php foreach ($all_exam_types as $exam_type_item): ?>
                            <option value="<?php echo htmlspecialchars($exam_type_item); ?>" <?php echo ($exam_type == $exam_type_item) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($exam_type_item); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-6">
                    <label for="roll" class="form-label">রোল নম্বর</label>
                    <input type="text" id="roll" name="roll" class="form-control" value="<?php echo htmlspecialchars($roll); ?>" placeholder="রোল নম্বর লিখুন" required>
                </div>
                
                <div class="col-12 text-center">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas fa-search"></i> মার্কশীট দেখুন
                    </button>
                    <a href="public_home.php" class="btn btn-secondary btn-lg">
                        <i class="fas fa-home"></i> হোম
                    </a>
                </div>
            </form>
        </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>