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

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

// Get search parameters
$class_id = $_GET['class_id'] ?? '';
$session = $_GET['session'] ?? date('Y');
$exam_type = $_GET['exam_type'] ?? '';
$group_name = $_GET['group_name'] ?? '';
$selected_subjects = $_GET['subjects'] ?? [];
$pass_fail_filter = $_GET['pass_fail_filter'] ?? 'all'; // all, pass, fail
$failed_count_filter = $_GET['failed_count_filter'] ?? 'all'; // all, 0, 1, 2, etc.
$view_mode = $_GET['view_mode'] ?? 'summary'; // summary, detailed

$subjects_data = [];
$show_results = false;
$all_subjects = [];

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

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

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

// Get available groups
$stmt = $pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name");
$groups = $stmt->fetchAll();

if ($class_id && $session && $exam_type) {
    $show_results = true;
    
    // Get all subjects for this class
    $stmt = $pdo->prepare(
        "SELECT DISTINCT s.id, s.name, s.code
        FROM subjects s
        JOIN results r ON s.id = r.subject_id
        JOIN students st ON r.student_id = st.id
        WHERE st.class_id = ? AND r.session = ? AND r.exam_type = ?" . ($group_name !== '' ? " AND st.group_name = ?" : "") . "
        ORDER BY s.name"
    );
    $stmt->execute($group_name !== '' ? [$class_id, $session, $exam_type, $group_name] : [$class_id, $session, $exam_type]);
    $all_subjects = $stmt->fetchAll();
    
    // Filter subjects based on selection
    if (!empty($selected_subjects) && is_array($selected_subjects)) {
        $subjects = array_filter($all_subjects, function($subject) use ($selected_subjects) {
            return in_array($subject['id'], $selected_subjects);
        });
        // Re-index array
        $subjects = array_values($subjects);
    } else {
        $subjects = $all_subjects;
    }
    
    // Get all students in this class
    $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'" . ($group_name !== '' ? " AND s.group_name = ?" : "") . "
        ORDER BY s.roll_number, s.first_name, s.last_name"
    );
    $stmt->execute($group_name !== '' ? [$class_id, $group_name] : [$class_id]);
    $students = $stmt->fetchAll();
    
    // For each student, get their results
    $students_data = [];
    foreach ($students as $student) {
        $student_id = $student['id'];
        
        // Initialize student data
        $students_data[$student_id] = [
            'id' => $student['id'],
            'student_id' => $student['student_id'],
            'first_name' => $student['first_name'],
            'last_name' => $student['last_name'],
            'roll_number' => $student['roll_number'],
            'results' => []
        ];
        
        // Get results for this student
        $stmt = $pdo->prepare(
            "SELECT r.subject_id, r.grade
            FROM results r
            JOIN students s ON r.student_id = s.id
            WHERE r.student_id = ? AND r.session = ? AND r.exam_type = ?" . ($group_name !== '' ? " AND s.group_name = ?" : "") . ""
        );
        $stmt->execute($group_name !== '' ? [$student_id, $session, $exam_type, $group_name] : [$student_id, $session, $exam_type]);
        $results = $stmt->fetchAll();
        
        // Store results by subject_id
        foreach ($results as $result) {
            $students_data[$student_id]['results'][$result['subject_id']] = $result['grade'];
        }
    }
    
    // Filter students based on pass/fail filter
    if ($pass_fail_filter !== 'all') {
        $filtered_students_data = [];
        foreach ($students_data as $student_id => $student) {
            // Count failed subjects for this student
            $failed_count = 0;
            foreach ($subjects as $subject) {
                $grade = isset($student['results'][$subject['id']]) ? $student['results'][$subject['id']] : 'F';
                if ($grade == 'F') $failed_count++;
            }
            
            // Add student to filtered list based on filter
            if (($pass_fail_filter === 'pass' && $failed_count === 0) || 
                ($pass_fail_filter === 'fail' && $failed_count > 0)) {
                $filtered_students_data[$student_id] = $student;
            }
        }
        $students_data = $filtered_students_data;
    }
    
    // For each subject, get pass/fail statistics
    foreach ($subjects as $subject) {
        // Get total students in this class for this exam
        $stmt = $pdo->prepare(
            "SELECT COUNT(DISTINCT r.student_id) as total_students
            FROM results r
            JOIN students s ON r.student_id = s.id
            WHERE r.subject_id = ? AND s.class_id = ? AND r.session = ? AND r.exam_type = ? 
            AND s.status = 'active'" . ($group_name !== '' ? " AND s.group_name = ?" : "") . ""
        );
        $stmt->execute($group_name !== '' ? [$subject['id'], $class_id, $session, $exam_type, $group_name] : [$subject['id'], $class_id, $session, $exam_type]);
        $total_students_result = $stmt->fetch();
        $total_students = $total_students_result['total_students'];
        
        // Get students who failed in this subject
        $stmt = $pdo->prepare(
            "SELECT COUNT(DISTINCT r.student_id) as failed_students
            FROM results r
            JOIN students s ON r.student_id = s.id
            WHERE r.subject_id = ? AND s.class_id = ? AND r.session = ? AND r.exam_type = ? 
            AND r.grade = 'F' AND s.status = 'active'" . ($group_name !== '' ? " AND s.group_name = ?" : "") . ""
        );
        $stmt->execute($group_name !== '' ? [$subject['id'], $class_id, $session, $exam_type, $group_name] : [$subject['id'], $class_id, $session, $exam_type]);
        $failed_students_result = $stmt->fetch();
        $failed_students = $failed_students_result['failed_students'];
        
        // Calculate passed students
        $passed_students = $total_students - $failed_students;
        
        // Add to subjects data
        $subjects_data[] = [
            'id' => $subject['id'],
            'name' => $subject['name'],
            'code' => $subject['code'],
            'total_students' => $total_students,
            'passed_students' => $passed_students,
            'failed_students' => $failed_students,
            'pass_rate' => $total_students > 0 ? round(($passed_students / $total_students) * 100, 2) : 0,
            'fail_rate' => $total_students > 0 ? round(($failed_students / $total_students) * 100, 2) : 0
        ];
    }
    
    // Get class name for display
    $stmt = $pdo->prepare("SELECT name, section FROM classes WHERE id = ?");
    $stmt->execute([$class_id]);
    $class_info = $stmt->fetch();
    $class_name = $class_info ? $class_info['name'] . ' ' . $class_info['section'] : '';
}
?>

<!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;
            background-color: #f8f9fa;
        }
        
        .report-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            margin-bottom: 25px;
            overflow: hidden;
        }
        
        .report-header {
            background: linear-gradient(135deg, #0d6efd 0%, #0b5ed7 100%);
            color: white;
            padding: 25px;
            text-align: center;
        }
        
        .search-panel {
            background: #e9ecef;
            padding: 25px;
            border-radius: 8px;
            margin-bottom: 25px;
        }
        
        .subject-card {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .subject-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .pass-stat {
            background: linear-gradient(135deg, #198754 0%, #157347 100%);
            color: white;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        
        .fail-stat {
            background: linear-gradient(135deg, #dc3545 0%, #bb2d3b 100%);
            color: white;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        
        .rate-display {
            font-size: 1.5rem;
            font-weight: 700;
        }
        
        .subject-name {
            font-weight: 600;
            font-size: 1.2rem;
            color: #2c3e50;
        }
        
        .progress {
            height: 10px;
            border-radius: 5px;
            margin-top: 10px;
        }

        .print-header {
            display: none;
        }

        .selected-subjects-header {
            margin-top: 20px;
        }

        .selected-subjects-header .alert {
            border-radius: 10px;
            border: none;
            background: linear-gradient(135deg, #cce5ff 0%, #99d6ff 100%);
        }

        .selected-subjects-header .alert-heading {
            color: #0d6efd;
            font-weight: 600;
        }

        .failed-subjects-list {
            max-height: 100px;
            overflow-y: auto;
        }

        .result-status {
            font-weight: 600;
            font-size: 1.1rem;
        }

        .pass-status {
            color: #198754;
        }

        .fail-status {
            color: #dc3545;
        }

        .summary-stat-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            border: 1px solid #dee2e6;
            transition: transform 0.2s;
        }

        .summary-stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
        }

        .stat-icon {
            font-size: 2rem;
            margin-right: 15px;
            color: #6c757d;
        }

        .stat-content {
            flex: 1;
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            line-height: 1;
            margin-bottom: 5px;
            color: #2c3e50;
        }

        .stat-label {
            font-size: 0.9rem;
            font-weight: 600;
            color: #6c757d;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .student-card {
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 25px;
            background: white;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .student-header {
            border-bottom: 3px solid #0d6efd;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }

        .student-info {
            color: #0d6efd;
            font-size: 1.3rem;
            margin: 0;
        }

        .student-info i {
            margin-right: 8px;
        }

        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 25px;
        }

        .summary-card {
            border-radius: 10px;
            padding: 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: transform 0.2s;
        }

        .summary-card:hover {
            transform: translateY(-2px);
        }

        .pass-card {
            background: linear-gradient(135deg, #d4edda 0%, #28a745 100%);
            color: white;
        }

        .fail-card {
            background: linear-gradient(135deg, #f8d7da 0%, #dc3545 100%);
            color: white;
        }

        .status-card {
            background: linear-gradient(135deg, #fff3cd 0%, #ffc107 100%);
            color: #212529;
        }

        .pass-status {
            background: linear-gradient(135deg, #d4edda 0%, #28a745 100%) !important;
            color: white;
        }

        .fail-status {
            background: linear-gradient(135deg, #f8d7da 0%, #dc3545 100%) !important;
            color: white;
        }

        .card-icon {
            font-size: 2rem;
            margin-right: 15px;
            opacity: 0.9;
        }

        .card-content {
            flex: 1;
        }

        .card-number {
            font-size: 2.5rem;
            font-weight: 700;
            line-height: 1;
            margin-bottom: 5px;
        }

        .card-label {
            font-size: 1rem;
            font-weight: 600;
            opacity: 0.9;
        }

        .card-status {
            font-size: 1.2rem;
            font-weight: 700;
            margin-top: 5px;
        }

        .subject-table {
            margin-bottom: 0;
        }

        .subject-table th {
            font-weight: 600;
            font-size: 1rem;
        }

        .subject-table td {
            vertical-align: middle;
        }

        .grade-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 700;
            font-size: 1.1rem;
            min-width: 50px;
            text-align: center;
        }

        .grade-pass {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .grade-fail {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .result-badge {
            display: inline-flex;
            align-items: center;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9rem;
        }

        .result-badge i {
            margin-right: 5px;
        }

        .result-pass {
            background-color: #d4edda;
            color: #155724;
        }

        .result-fail {
            background-color: #f8d7da;
            color: #721c24;
        }

        .failed-subjects-alert {
            margin-top: 20px;
        }

        .failed-subjects-alert .alert {
            border-radius: 8px;
            border: none;
        }

        .failed-subjects-alert .alert-heading {
            margin-bottom: 10px;
            font-weight: 600;
        }

        .subjects-list {
            max-height: 100px;
            overflow-y: auto;
        }
        
        .passed-subjects-list {
            max-height: 100px;
            overflow-y: auto;
        }
        
        .failed-subjects-list {
            max-height: 100px;
            overflow-y: auto;
        }

        /* Mobile Responsive */
        @media (max-width: 768px) {
            .student-card {
                padding: 15px;
                margin-bottom: 20px;
            }

            .student-info {
                font-size: 1.1rem;
            }

            .summary-cards {
                grid-template-columns: 1fr;
                gap: 10px;
            }

            .summary-card {
                padding: 15px;
            }

            .card-number {
                font-size: 2rem;
            }

            .card-icon {
                font-size: 1.5rem;
                margin-right: 10px;
            }

            .grade-badge {
                padding: 4px 8px;
                font-size: 1rem;
            }
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            
            .print-header {
                display: block;
                text-align: center;
                margin-bottom: 20px;
            }
            
            .report-card {
                box-shadow: none;
                border: 1px solid #000;
            }
            
            .report-header {
                background: white !important;
                color: black !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .pass-stat, .fail-stat {
                background: white !important;
                color: black !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
                border: 1px solid #000 !important;
            }

            .student-card {
                break-inside: avoid;
                page-break-inside: avoid;
                border: 1px solid #000 !important;
                background: white !important;
                color: black !important;
                box-shadow: none !important;
                margin-bottom: 20px !important;
            }

            .summary-cards {
                display: flex !important;
                flex-wrap: wrap;
                gap: 10px;
            }

            .summary-card {
                flex: 1;
                min-width: 150px;
                background: white !important;
                color: black !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }

            .subject-table {
                font-size: 12px;
            }

            .selected-subjects-header .alert {
                background: white !important;
                color: black !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
                border: 1px solid #000 !important;
            }

            .summary-stat-card {
                border: 1px solid #000 !important;
                background: white !important;
                color: black !important;
                box-shadow: none !important;
                break-inside: avoid;
            }

            .failed-subjects-list {
                max-height: none !important;
                overflow: visible !important;
            }
            
            
            /* Enhanced print styling for beautiful output */
            body {
                font-family: 'Hind Siliguri', Arial, sans-serif;
                font-size: 12px;
                line-height: 1.4;
            }
            
            /* Force all colors to black and white for printing */
            * {
                -webkit-print-color-adjust: exact !important;
                color-adjust: exact !important;
                background: white !important;
                color: black !important;
                font-size: 12px !important;
            }
            
            .table-primary,
            .table-success,
            .table-danger,
            .table-info,
            .table-warning,
            .table-light,
            .table-dark,
            .bg-primary,
            .bg-success,
            .bg-danger,
            .bg-info,
            .bg-warning,
            .bg-light,
            .bg-dark,
            .btn-primary,
            .btn-success,
            .btn-danger,
            .btn-info,
            .btn-warning,
            .btn-light,
            .btn-dark {
                background: white !important;
                color: black !important;
                border: 1px solid black !important;
            }
            
            .badge {
                background: white !important;
                color: black !important;
                border: 1px solid black !important;
                padding: 2px 6px !important;
                font-size: 10px !important;
                margin: 1px !important;
            }
            
            /* Table styling for print */
            table {
                font-size: 11px !important;
                border-collapse: collapse;
            }
            
            th, td {
                padding: 6px !important;
                border: 1px solid black !important;
                text-align: left;
                vertical-align: top;
                page-break-inside: avoid;
            }
            
            th {
                font-weight: bold;
                background: white !important;
                color: black !important;
            }
            
            tr {
                page-break-inside: avoid;
            }
            
            /* Subject lists styling for print */
            .subjects-list,
            .passed-subjects-list,
            .failed-subjects-list {
                max-height: none !important;
                min-height: 20px;
                padding: 4px !important;
                border: 1px solid black !important;
                border-radius: 3px !important;
                background: white !important;
                color: black !important;
            }
            
            /* Header styling for print */
            h1, h2, h3, h4, h5, h6 {
                page-break-after: avoid;
                color: black !important;
                margin: 10px 0 !important;
            }
            
            /* Text alignment for print */
            .text-center {
                text-align: center !important;
            }
            
            .text-start, .text-left {
                text-align: left !important;
            }
            
            .text-end, .text-right {
                text-align: right !important;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <!-- Print Header -->
        <div class="print-header">
            <h2>পাশ/ফেল তালিকা</h2>
            <p><?php echo $show_results ? htmlspecialchars($class_name) . " - " . htmlspecialchars($session) . " (" . htmlspecialchars(ucfirst($exam_type)) . ")" : ""; ?></p>
        </div>
        
        <div class="report-card">
            <div class="report-header">
                <h1><i class="fas fa-chart-bar"></i> পাশ/ফেল তালিকা</h1>
                <p class="mb-0">বিষয়ভিত্তিক পাশ ও ফেল ছাত্র-ছাত্রীর পরিসংখ্যান</p>
            </div>
            
            <div class="container">
                <div class="text-center mb-4 no-print">
                    <?php if ($view_mode === 'detailed'): ?>
                    <button onclick="printDetailedTable()" class="btn btn-success btn-lg me-2">
                        <i class="fas fa-print"></i> শুধু তালিকা প্রিন্ট করুন
                    </button>
                    <?php endif; ?>
                    <button onclick="window.print()" class="btn btn-outline-success btn-lg me-2">
                        <i class="fas fa-print"></i> সম্পূর্ণ রিপোর্ট প্রিন্ট করুন
                    </button>
                    <a href="index.php" class="btn btn-primary btn-lg">
                        <i class="fas fa-arrow-left"></i> রিপোর্ট ড্যাশবোর্ড
                    </a>
                </div>
                
                <div class="search-panel no-print">
                    <h4 class="mb-4"><i class="fas fa-filter"></i> ফিল্টার করুন</h4>
                    <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): ?>
                                    <option value="<?php echo htmlspecialchars($class['id']); ?>" <?php echo $class_id == $class['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($class['name'] . ' ' . $class['section']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <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 $session == $session_item['session'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($session_item['session']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <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 $exam_type == $exam_type_item['exam_type'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars(ucfirst($exam_type_item['exam_type'])); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <!-- Group selection -->
                        <div class="col-md-3">
                            <label for="group_name" class="form-label">গ্রুপ</label>
                            <select id="group_name" name="group_name" class="form-select">
                                <option value="">সব গ্রুপ</option>
                                <?php foreach ($groups as $group): ?>
                                    <option value="<?php echo htmlspecialchars($group['group_name']); ?>" <?php echo $group_name == $group['group_name'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($group['group_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <!-- Subject selection checkboxes -->
                        <?php if (!empty($all_subjects)): ?>
                        <div class="col-12">
                            <label class="form-label">বিষয় নির্বাচন করুন (যে সব বিষয় নির্বাচন করা হবে সেগুলোর ফলাফল দেখাবে)</label>
                            <div class="row">
                                <?php foreach ($all_subjects as $subject): ?>
                                <div class="col-md-3 col-sm-4 col-6 mb-2">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" 
                                               name="subjects[]" 
                                               value="<?php echo htmlspecialchars($subject['id']); ?>" 
                                               id="subject_<?php echo htmlspecialchars($subject['id']); ?>"
                                               <?php echo (empty($selected_subjects) || in_array($subject['id'], $selected_subjects)) ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="subject_<?php echo htmlspecialchars($subject['id']); ?>">
                                            <?php echo htmlspecialchars($subject['name']); ?>
                                        </label>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Pass/Fail filter -->
                        <div class="col-md-2">
                            <label for="pass_fail_filter" class="form-label">পাশ/ফেল ফিল্টার</label>
                            <select id="pass_fail_filter" name="pass_fail_filter" class="form-select">
                                <option value="all" <?php echo $pass_fail_filter === 'all' ? 'selected' : ''; ?>>সব ছাত্র-ছাত্রী</option>
                                <option value="pass" <?php echo $pass_fail_filter === 'pass' ? 'selected' : ''; ?>>শুধু পাশ</option>
                                <option value="fail" <?php echo $pass_fail_filter === 'fail' ? 'selected' : ''; ?>>শুধু ফেল</option>
                            </select>
                        </div>

                        <!-- Failed Count filter -->
                        <div class="col-md-2">
                            <label for="failed_count_filter" class="form-label">ফেলের সংখ্যা</label>
                            <select id="failed_count_filter" name="failed_count_filter" class="form-select">
                                <option value="all" <?php echo $failed_count_filter === 'all' ? 'selected' : ''; ?>>সব</option>
                                <option value="0" <?php echo $failed_count_filter === '0' ? 'selected' : ''; ?>>০ টি ফেল</option>
                                <option value="1" <?php echo $failed_count_filter === '1' ? 'selected' : ''; ?>>১ টি ফেল</option>
                                <option value="2" <?php echo $failed_count_filter === '2' ? 'selected' : ''; ?>>২ টি ফেল</option>
                                <option value="3" <?php echo $failed_count_filter === '3' ? 'selected' : ''; ?>>৩ টি ফেল</option>
                                <option value="4" <?php echo $failed_count_filter === '4' ? 'selected' : ''; ?>>৪ টি ফেল</option>
                                <option value="5" <?php echo $failed_count_filter === '5' ? 'selected' : ''; ?>>৫ টি ফেল</option>
                                <option value="6" <?php echo $failed_count_filter === '6' ? 'selected' : ''; ?>>৬ টি ফেল</option>
                                <option value="7" <?php echo $failed_count_filter === '7' ? 'selected' : ''; ?>>৭ টি ফেল</option>
                                <option value="8" <?php echo $failed_count_filter === '8' ? 'selected' : ''; ?>>৮ টি ফেল</option>
                            </select>
                        </div>
                        
                        <!-- View mode toggle -->
                        <div class="col-md-3">
                            <label for="view_mode" class="form-label">দেখার ধরন</label>
                            <select id="view_mode" name="view_mode" class="form-select">
                                <option value="summary" <?php echo $view_mode === 'summary' ? 'selected' : ''; ?>>সারাংশ তালিকা</option>
                                <option value="detailed" <?php echo $view_mode === 'detailed' ? 'selected' : ''; ?>>বিস্তারিত তালিকা</option>
                            </select>
                        </div>
                        
                        <!-- Search input for detailed view -->
                        <?php if ($view_mode === 'detailed'): ?>
                        <div class="col-md-3">
                            <label for="tableSearch" class="form-label">খুঁজুন</label>
                            <input type="text" id="tableSearch" class="form-control" placeholder="রোল, আইডি, নাম খুঁজুন...">
                        </div>
                        <?php endif; ?>
                        
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-search"></i> দেখুন
                            </button>
                        </div>
                    </form>
                </div>
                
                <?php if ($show_results): ?>
                    <div class="mb-4">
                        <h3 class="text-center mb-4">
                            <?php echo htmlspecialchars($class_name); ?> - <?php echo htmlspecialchars($session); ?> (<?php echo htmlspecialchars(ucfirst($exam_type)); ?>)
                        </h3>
                        
                        <?php if (!empty($students_data)): ?>
                            <?php
                            // Collect data for summary table
                            $student_summary = [];
                            $detailed_student_data = [];
                            foreach ($students_data as $student) {
                                // Get only subjects this student has results for from selected subjects
                                $student_subjects = [];
                                foreach ($subjects as $subject) {
                                    if (isset($student['results'][$subject['id']]) && !empty($student['results'][$subject['id']])) {
                                        $student_subjects[] = $subject;
                                    }
                                }

                                // Skip student if they have no results in selected subjects
                                if (empty($student_subjects)) {
                                    continue;
                                }

                                // Calculate fail statistics for this student
                                $failed_count = 0;
                                $failed_subjects = [];
                                $passed_subjects = [];
                                foreach ($student_subjects as $subject) {
                                    $grade = $student['results'][$subject['id']];
                                    if ($grade == 'F') {
                                        $failed_count++;
                                        $failed_subjects[] = $subject['name'];
                                    } else {
                                        $passed_subjects[] = $subject['name'];
                                    }
                                }

                                // Create summary data for summary view
                                $student_summary[] = [
                                    'id' => $student['id'],
                                    'student_id' => $student['student_id'],
                                    'first_name' => $student['first_name'],
                                    'last_name' => $student['last_name'],
                                    'roll_number' => $student['roll_number'],
                                    'failed_count' => $failed_count,
                                    'failed_subjects' => $failed_subjects,
                                    'passed_subjects' => $passed_subjects,
                                    'total_subjects' => count($student_subjects),
                                    'all_subjects' => array_column($student_subjects, 'name')
                                ];

                                // Create detailed data for detailed view
                                $detailed_student_data[] = [
                                    'id' => $student['id'],
                                    'student_id' => $student['student_id'],
                                    'first_name' => $student['first_name'],
                                    'last_name' => $student['last_name'],
                                    'roll_number' => $student['roll_number'],
                                    'failed_count' => $failed_count,
                                    'failed_subjects' => $failed_subjects,
                                    'passed_subjects' => $passed_subjects,
                                    'total_subjects' => count($student_subjects),
                                    'all_subjects' => array_column($student_subjects, 'name')
                                ];
                            }

                            // Apply failed count filter
                            if ($failed_count_filter !== 'all') {
                                $student_summary = array_filter($student_summary, function($student) use ($failed_count_filter) {
                                    return $student['failed_count'] == (int)$failed_count_filter;
                                });
                                $student_summary = array_values($student_summary); // Re-index array
                                
                                $detailed_student_data = array_filter($detailed_student_data, function($student) use ($failed_count_filter) {
                                    return $student['failed_count'] == (int)$failed_count_filter;
                                });
                                $detailed_student_data = array_values($detailed_student_data); // Re-index array
                            }
                            ?>

                            <?php if (!empty($student_summary)): ?>
                                <!-- Selected Subjects Header -->
                                <div class="selected-subjects-header mb-4">
                                    <div class="alert alert-primary">
                                        <h5 class="alert-heading mb-2">
                                            <i class="fas fa-book"></i>
                                            নির্বাচিত বিষয়সমূহ (<?php echo count($subjects); ?>)
                                        </h5>
                                        <p class="mb-0">
                                            <strong><?php echo htmlspecialchars(implode(', ', array_column($subjects, 'name'))); ?></strong>
                                        </p>
                                    </div>
                                </div>

                                <?php if ($view_mode === 'summary'): ?>
                                <!-- Summary Table -->
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped table-hover">
                                        <thead class="table-primary">
                                            <tr>
                                                <th class="text-center">#</th>
                                                <th>রোল নম্বর</th>
                                                <th>শিক্ষার্থী আইডি</th>
                                                <th>নাম</th>
                                                <th class="text-center">মোট বিষয়</th>
                                                <th class="text-center">ফেলের সংখ্যা</th>
                                                <th>ফেলের বিষয়সমূহ</th>
                                                <th class="text-center">ফলাফল</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $serial = 1; ?>
                                            <?php foreach ($student_summary as $student): ?>
                                                <tr class="<?php echo $student['failed_count'] > 0 ? 'table-danger' : 'table-success'; ?>">
                                                    <td class="text-center"><?php echo $serial++; ?></td>
                                                    <td class="text-center fw-bold"><?php echo htmlspecialchars($student['roll_number']); ?></td>
                                                    <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                                                    <td><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                                    <td class="text-center"><?php echo $student['total_subjects']; ?></td>
                                                    <td class="text-center">
                                                        <span class="badge <?php echo $student['failed_count'] > 0 ? 'bg-danger' : 'bg-success'; ?> fs-6">
                                                            <?php echo $student['failed_count']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php if (!empty($student['failed_subjects'])): ?>
                                                            <div class="failed-subjects-list">
                                                                <?php foreach ($student['failed_subjects'] as $subject): ?>
                                                                    <span class="badge bg-danger me-1 mb-1"><?php echo htmlspecialchars($subject); ?></span>
                                                                <?php endforeach; ?>
                                                            </div>
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td class="text-center">
                                                        <span class="result-status <?php echo $student['failed_count'] > 0 ? 'fail-status' : 'pass-status'; ?>">
                                                            <i class="fas <?php echo $student['failed_count'] > 0 ? 'fa-times-circle' : 'fa-check-circle'; ?>"></i>
                                                            <?php echo $student['failed_count'] > 0 ? 'ফেল' : 'পাশ'; ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php elseif ($view_mode === 'detailed'): ?>
                                <!-- Search input for detailed view table -->
                                <div class="mb-3">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <label for="tableSearch" class="form-label">খুঁজুন</label>
                                            <input type="text" id="tableSearch" class="form-control" placeholder="রোল, আইডি, নাম খুঁজুন...">
                                        </div>
                                    </div>
                                </div>
                                <!-- Detailed Student List -->
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped table-hover" id="detailedTable">
                                        <thead class="table-primary">
                                            <tr>
                                                <th class="text-center">#</th>
                                                <th>রোল নম্বর</th>
                                                <th>শিক্ষার্থী আইডি</th>
                                                <th>নাম</th>
                                                <th>বিষয়সমূহ</th>
                                                <th>পাশ করা বিষয়</th>
                                                <th>ফেল করা বিষয়</th>
                                                <th class="text-center">ফেল করা বিষয় সংখ্যা</th>
                                                <th class="text-center">ফলাফল</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $serial = 1; ?>
                                            <?php foreach ($detailed_student_data as $student): ?>
                                                <tr class="<?php echo $student['failed_count'] > 0 ? 'table-danger' : 'table-success'; ?>">
                                                    <td class="text-center"><?php echo $serial++; ?></td>
                                                    <td class="text-center fw-bold roll-number"><?php echo htmlspecialchars($student['roll_number']); ?></td>
                                                    <td class="student-id"><?php echo htmlspecialchars($student['student_id']); ?></td>
                                                    <td class="student-name"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                                    <td class="subjects-list">
                                                        <div class="subjects-list-inner">
                                                            <?php foreach ($student['all_subjects'] as $subject): ?>
                                                                <span class="badge bg-secondary me-1 mb-1 subject-name"><?php echo htmlspecialchars($subject); ?></span>
                                                            <?php endforeach; ?>
                                                        </div>
                                                    </td>
                                                    <td class="passed-subjects">
                                                        <div class="passed-subjects-inner">
                                                            <?php if (!empty($student['passed_subjects'])): ?>
                                                                <?php foreach ($student['passed_subjects'] as $subject): ?>
                                                                    <span class="badge bg-success me-1 mb-1 subject-name"><?php echo htmlspecialchars($subject); ?></span>
                                                                <?php endforeach; ?>
                                                            <?php else: ?>
                                                                <span class="text-muted">-</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td class="failed-subjects">
                                                        <div class="failed-subjects-inner">
                                                            <?php if (!empty($student['failed_subjects'])): ?>
                                                                <?php foreach ($student['failed_subjects'] as $subject): ?>
                                                                    <span class="badge bg-danger me-1 mb-1 subject-name"><?php echo htmlspecialchars($subject); ?></span>
                                                                <?php endforeach; ?>
                                                            <?php else: ?>
                                                                <span class="text-muted">-</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td class="text-center failed-count"><?php echo $student['failed_count']; ?></td>
                                                    <td class="text-center result-status"><?php echo $student['failed_count'] > 0 ? 'ফেল' : 'পাশ'; ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php endif; ?>

                                <!-- Summary Statistics -->
                                <div class="row mt-4">
                                    <div class="col-md-3">
                                        <div class="summary-stat-card">
                                            <div class="stat-icon">
                                                <i class="fas fa-users"></i>
                                            </div>
                                            <div class="stat-content">
                                                <div class="stat-number"><?php echo count($student_summary); ?></div>
                                                <div class="stat-label">মোট শিক্ষার্থী</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="summary-stat-card">
                                            <div class="stat-icon text-success">
                                                <i class="fas fa-check-circle"></i>
                                            </div>
                                            <div class="stat-content">
                                                <div class="stat-number text-success">
                                                    <?php echo count(array_filter($student_summary, function($s) { return $s['failed_count'] == 0; })); ?>
                                                </div>
                                                <div class="stat-label">পাশ</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="summary-stat-card">
                                            <div class="stat-icon text-danger">
                                                <i class="fas fa-times-circle"></i>
                                            </div>
                                            <div class="stat-content">
                                                <div class="stat-number text-danger">
                                                    <?php echo count(array_filter($student_summary, function($s) { return $s['failed_count'] > 0; })); ?>
                                                </div>
                                                <div class="stat-label">ফেল</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="summary-stat-card">
                                            <div class="stat-icon text-warning">
                                                <i class="fas fa-percentage"></i>
                                            </div>
                                            <div class="stat-content">
                                                <div class="stat-number text-warning">
                                                    <?php
                                                    $pass_count = count(array_filter($student_summary, function($s) { return $s['failed_count'] == 0; }));
                                                    echo count($student_summary) > 0 ? round(($pass_count / count($student_summary)) * 100, 1) : 0;
                                                    ?>%
                                                </div>
                                                <div class="stat-label">পাশের হার</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-info text-center">
                                    <i class="fas fa-info-circle"></i> নির্বাচিত ফিল্টার অনুসারে কোন শিক্ষার্থীর ফলাফল পাওয়া যায়নি।
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="alert alert-info text-center">
                                <i class="fas fa-info-circle"></i> এই শ্রেণী, সেশন এবং পরীক্ষার জন্য কোন ডেটা পাওয়া যায়নি।
                            </div>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="alert alert-info text-center">
                        <i class="fas fa-info-circle"></i> ফিল্টার নির্বাচন করে রিপোর্ট দেখুন
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Add Select All/Deselect All functionality for subject checkboxes
        document.addEventListener('DOMContentLoaded', function() {
            // Add Select All/Deselect All buttons if there are subject checkboxes
            const subjectCheckboxes = document.querySelectorAll('input[name="subjects[]"]');
            if (subjectCheckboxes.length > 0) {
                // Create container for select/deselect buttons
                const buttonContainer = document.createElement('div');
                buttonContainer.className = 'col-12 mb-3';
                buttonContainer.innerHTML = `
                    <button type="button" class="btn btn-sm btn-outline-primary me-2" id="select-all-subjects">
                        <i class="fas fa-check-square"></i> সবগুলো নির্বাচন করুন
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="deselect-all-subjects">
                        <i class="fas fa-square"></i> সবগুলো নির্বাচন মুক্ত করুন
                    </button>
                `;
                
                // Insert buttons before the first checkbox container
                const firstCheckboxContainer = document.querySelector('.col-12 .row');
                if (firstCheckboxContainer) {
                    firstCheckboxContainer.parentNode.insertBefore(buttonContainer, firstCheckboxContainer);
                }
                
                // Add event listeners for select/deselect buttons
                document.getElementById('select-all-subjects').addEventListener('click', function() {
                    subjectCheckboxes.forEach(checkbox => {
                        checkbox.checked = true;
                    });
                });
                
                document.getElementById('deselect-all-subjects').addEventListener('click', function() {
                    subjectCheckboxes.forEach(checkbox => {
                        checkbox.checked = false;
                    });
                });
            }
        });
    
    // Function to print only the detailed table
    function printDetailedTable() {
        // Create a new window for printing
        const printWindow = window.open('', '_blank');
        
        // Get the table HTML
        const tableHTML = document.querySelector('.table-responsive table').outerHTML;
        
        // Get the report title
        const reportTitle = document.querySelector('.report-header h3');
        const titleText = reportTitle ? reportTitle.textContent : 'পাশ/ফেল তালিকা';
        
        // Build the HTML content
        let htmlContent = '<!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">' +
                '<style>' +
                    'body { font-family: \'Hind Siliguri\', sans-serif; padding: 20px; }' +
                    '.print-table { width: 100%; border-collapse: collapse; margin: 20px 0; }' +
                    '.print-table th, .print-table td { border: 1px solid #000; padding: 8px; text-align: left; vertical-align: top; }' +
                    '.print-table th { background-color: #0d6efd; color: white; font-weight: bold; }' +
                    '.subjects-list, .passed-subjects-list, .failed-subjects-list { max-height: 80px; overflow-y: auto; padding: 5px; border: 1px solid #ddd; border-radius: 4px; background-color: #f9f9f9; }' +
                    '.badge { margin: 2px; display: inline-block; padding: 4px 8px; font-size: 0.8rem; }' +
                    '@media print { body { padding: 20px; font-size: 12px; -webkit-print-color-adjust: exact !important; color-adjust: exact !important; } .print-table { font-size: 11px; width: 100% !important; margin: 20px 0 !important; border-collapse: collapse; } .print-table th, .print-table td { padding: 6px !important; border: 1px solid black !important; text-align: left; vertical-align: top; page-break-inside: avoid; } .print-table th { background: white !important; color: black !important; font-weight: bold; padding: 8px !important; } .print-table tbody tr { page-break-inside: avoid; } .subjects-list, .passed-subjects-list, .failed-subjects-list { max-height: none !important; min-height: 20px; padding: 4px !important; border: 1px solid black !important; border-radius: 3px !important; background: white !important; color: black !important; } .badge { margin: 1px !important; display: inline-block !important; padding: 2px 6px !important; font-size: 10px !important; background: white !important; color: black !important; border: 1px solid black !important; border-radius: 3px !important; } /* Force all colors to black and white for printing */ * { -webkit-print-color-adjust: exact !important; color-adjust: exact !important; background: white !important; color: black !important; } .table-primary, .table-success, .table-danger, .table-info, .table-warning, .table-light, .table-dark, .bg-primary, .bg-success, .bg-danger, .bg-info, .bg-warning, .bg-light, .bg-dark, .btn-primary, .btn-success, .btn-danger, .btn-info, .btn-warning, .btn-light, .btn-dark { background: white !important; color: black !important; border: 1px solid black !important; } h1, h2, h3, h4, h5, h6 { page-break-after: avoid; color: black !important; } .text-center { text-align: center !important; } .text-start, .text-left { text-align: left !important; } .text-end, .text-right { text-align: right !important; } }' +
                    '@media (max-width: 768px) { .print-table { font-size: 12px; } .print-table th, .print-table td { padding: 3px; } }' +
                '</style>' +
            '</head>' +
            '<body>' +
                '<div class="text-center mb-4">' +
                    '<h2>পাশ/ফেল তালিকা - বিস্তারিত তালিকা</h2>' +
                    '<p>' + titleText + '</p>' +
                '</div>' +
                '<div class="table-responsive">' +
                    tableHTML +
                '</div>' +
            '</body>' +
            '</html>';
        
        printWindow.document.write(htmlContent);
        printWindow.document.close();
        printWindow.focus();
        
        // Wait for content to load before printing
        printWindow.onload = function() {
            setTimeout(() => {
                printWindow.print();
                printWindow.close();
            }, 1000);
        };
    }
    
    // Add column hiding functionality for responsive design
    document.addEventListener('DOMContentLoaded', function() {
        // Add column toggle buttons for detailed view
        if (document.querySelector('#view_mode') && document.querySelector('#view_mode').value === 'detailed') {
            const tableContainer = document.querySelector('.table-responsive');
            if (tableContainer) {
                const toggleContainer = document.createElement('div');
                toggleContainer.className = 'mb-3';
                toggleContainer.innerHTML = `
                    <div class="row">
                        <div class="col-12">
                            <label class="form-label fw-bold">কলাম দেখান/লুকান:</label>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <div class="form-check">
                                <input class="form-check-input column-toggle" type="checkbox" id="toggleRoll" checked data-column="2">
                                <label class="form-check-label" for="toggleRoll">রোল নম্বর</label>
                            </div>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <div class="form-check">
                                <input class="form-check-input column-toggle" type="checkbox" id="toggleID" checked data-column="3">
                                <label class="form-check-label" for="toggleID">শিক্ষার্থী আইডি</label>
                            </div>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <div class="form-check">
                                <input class="form-check-input column-toggle" type="checkbox" id="toggleName" checked data-column="4">
                                <label class="form-check-label" for="toggleName">নাম</label>
                            </div>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <div class="form-check">
                                <input class="form-check-input column-toggle" type="checkbox" id="toggleSubjects" checked data-column="5">
                                <label class="form-check-label" for="toggleSubjects">বিষয়সমূহ</label>
                            </div>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <div class="form-check">
                                <input class="form-check-input column-toggle" type="checkbox" id="togglePassed" checked data-column="6">
                                <label class="form-check-label" for="togglePassed">পাশ করা বিষয়</label>
                            </div>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <div class="form-check">
                                <input class="form-check-input column-toggle" type="checkbox" id="toggleFailed" checked data-column="7">
                                <label class="form-check-label" for="toggleFailed">ফেল করা বিষয়</label>
                            </div>
                        </div>
                    </div>
                `;
                
                tableContainer.parentNode.insertBefore(toggleContainer, tableContainer);
                
                // Add event listeners for column toggles
                document.querySelectorAll('.column-toggle').forEach(checkbox => {
                    checkbox.addEventListener('change', function() {
                        const columnIndex = this.getAttribute('data-column');
                        const table = document.querySelector('.table-responsive table');
                        if (table) {
                            // Need to account for the serial number column which is the first column
                            const actualColumnIndex = parseInt(columnIndex);
                            const cells = table.querySelectorAll(`td:nth-child(${actualColumnIndex}), th:nth-child(${actualColumnIndex})`);
                            cells.forEach(cell => {
                                if (this.checked) {
                                    cell.style.display = '';
                                } else {
                                    cell.style.display = 'none';
                                }
                            });
                        }
                    });
                });
            }
        }
    });
    
    // Add search functionality for detailed table
    document.addEventListener('DOMContentLoaded', function() {
        const searchInput = document.getElementById('tableSearch');
        if (searchInput) {
            searchInput.addEventListener('keyup', function() {
                const searchTerm = searchInput.value.toLowerCase();
                const table = document.getElementById('detailedTable');
                if (table) {
                    const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
                    
                    for (let i = 0; i < rows.length; i++) {
                        const row = rows[i];
                        const rollNumber = row.querySelector('.roll-number')?.textContent.toLowerCase() || '';
                        const studentId = row.querySelector('.student-id')?.textContent.toLowerCase() || '';
                        const studentName = row.querySelector('.student-name')?.textContent.toLowerCase() || '';
                        const subjectsList = row.querySelector('.subjects-list-inner')?.textContent.toLowerCase() || '';
                        const passedSubjects = row.querySelector('.passed-subjects-inner')?.textContent.toLowerCase() || '';
                        const failedSubjects = row.querySelector('.failed-subjects-inner')?.textContent.toLowerCase() || '';
                        const failedCount = row.querySelector('.failed-count')?.textContent.toLowerCase() || '';
                        const resultStatus = row.querySelector('.result-status')?.textContent.toLowerCase() || '';
                        
                        // Check if search term matches any of the fields
                        const matches = rollNumber.includes(searchTerm) || 
                                    studentId.includes(searchTerm) || 
                                    studentName.includes(searchTerm) || 
                                    subjectsList.includes(searchTerm) || 
                                    passedSubjects.includes(searchTerm) || 
                                    failedSubjects.includes(searchTerm) || 
                                    failedCount.includes(searchTerm) || 
                                    resultStatus.includes(searchTerm);
                        
                        if (matches) {
                            row.style.display = '';
                        } else {
                            row.style.display = 'none';
                        }
                    }
                }
            });
        }
    });
    </script>
</body>
</html>