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

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

$success_message = '';
$error_message = '';
$absence_list = [];
$exam_details = null;
$selected_class = null;
$selected_session = null;
$selected_group = null;

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

// Get distinct sessions from students table
$sessions = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC")->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['generate_list'])) {
    $exam_id = $_POST['exam_id'] ?? '';
    $class_id = $_POST['class_id'] ?? '';
    $session = $_POST['session'] ?? '';
    $group_name = $_POST['group_name'] ?? '';
    
    if (!$exam_id || !$class_id || !$session) {
        $error_message = 'পরীক্ষা, ক্লাস এবং সেশন নির্বাচন করুন';
    } else {
        try {
            // Get exam details
            $stmt = $pdo->prepare("
                SELECT e.*, c.name as class_name, c.section
                FROM exams e
                JOIN classes c ON e.class_id = c.id
                WHERE e.id = ?
            ");
            $stmt->execute([$exam_id]);
            $exam_details = $stmt->fetch();
            
            if (!$exam_details) {
                $error_message = 'পরীক্ষা খুঁজে পাওয়া যায়নি';
            } else {
                // Get all subjects for this exam
                $stmt = $pdo->prepare("
                    SELECT es.*, s.name as subject_name, s.code as subject_code
                    FROM exam_subjects es
                    JOIN subjects s ON es.subject_id = s.id
                    WHERE es.exam_id = ?
                    ORDER BY es.exam_date, es.start_time
                ");
                $stmt->execute([$exam_id]);
                $exam_subjects = $stmt->fetchAll();
                
                if (empty($exam_subjects)) {
                    $error_message = 'এই পরীক্ষার জন্য কোন বিষয় খুঁজে পাওয়া যায়নি';
                } else {
                    // Get students based on class, session, and group
                    $sql = "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.group_name
                            FROM students s
                            WHERE s.class_id = ? AND s.session = ? AND s.status = 'active'";
                    
                    $params = [$class_id, $session];
                    
                    // Add group condition if group is specified
                    if (!empty($group_name)) {
                        $sql .= " AND s.group_name = ?";
                        $params[] = $group_name;
                    }
                    
                    // Add search condition if search term is provided
                    $search_term = $_POST['search_student'] ?? '';
                    if (!empty($search_term)) {
                        $sql .= " AND (s.first_name LIKE ? OR s.last_name LIKE ? OR s.roll_number LIKE ? OR s.student_id LIKE ?)";
                        $search_param = '%' . $search_term . '%';
                        $params[] = $search_param; // first_name
                        $params[] = $search_param; // last_name
                        $params[] = $search_param; // roll_number
                        $params[] = $search_param; // student_id
                    }
                    
                    // Add sorting
                    $sort_by = $_POST['sort_by'] ?? 'roll_asc';
                    switch ($sort_by) {
                        case 'roll_desc':
                            $sql .= " ORDER BY s.roll_number DESC";
                            break;
                        case 'name_asc':
                            $sql .= " ORDER BY s.first_name ASC, s.last_name ASC";
                            break;
                        case 'name_desc':
                            $sql .= " ORDER BY s.first_name DESC, s.last_name DESC";
                            break;
                        case 'absent_first':
                            // We'll sort after fetching data based on attendance status
                            $sql .= " ORDER BY s.roll_number ASC";
                            break;
                        case 'present_first':
                            // We'll sort after fetching data based on attendance status
                            $sql .= " ORDER BY s.roll_number ASC";
                            break;
                        default: // roll_asc
                            $sql .= " ORDER BY s.roll_number ASC";
                            break;
                    }
                    
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                    $students = $stmt->fetchAll();
                    
                    if (empty($students)) {
                        $error_message = 'নির্বাচিত মানদণ্ডের জন্য কোন শিক্ষার্থী খুঁজে পাওয়া যায়নি';
                    } else {
                        // For each student, get their attendance status for each subject
                        foreach ($students as $student) {
                            $student_absences = [
                                'student' => $student,
                                'subjects' => []
                            ];
                            
                            foreach ($exam_subjects as $subject) {
                                // Check if student has attendance record for this subject
                                $stmt = $pdo->prepare("
                                    SELECT attendance_status, remarks
                                    FROM exam_attendance
                                    WHERE exam_id = ? AND subject_id = ? AND student_id = ?
                                ");
                                $stmt->execute([$exam_id, $subject['subject_id'], $student['id']]);
                                $attendance = $stmt->fetch();
                                
                                $student_absences['subjects'][] = [
                                    'subject' => $subject,
                                    'attendance_status' => $attendance['attendance_status'] ?? 'present',
                                    'remarks' => $attendance['remarks'] ?? ''
                                ];
                            }
                            
                            $absence_list[] = $student_absences;
                        }
                        
                        // Apply attendance status filter if specified
                        $attendance_status_filter = $_POST['attendance_status'] ?? '';
                        if (!empty($attendance_status_filter)) {
                            $absence_list = array_filter($absence_list, function($student_data) use ($attendance_status_filter) {
                                $is_absent = false;
                                foreach ($student_data['subjects'] as $subject_data) {
                                    if ($subject_data['attendance_status'] == 'absent') {
                                        $is_absent = true;
                                        break;
                                    }
                                }
                                return ($attendance_status_filter == 'absent') ? $is_absent : !$is_absent;
                            });
                        }
                        
                        // Re-sort if needed for absent_first or present_first
                        if ($sort_by == 'absent_first' || $sort_by == 'present_first') {
                            usort($absence_list, function($a, $b) use ($sort_by) {
                                // Check if student a is absent
                                $a_is_absent = false;
                                foreach ($a['subjects'] as $subject_data) {
                                    if ($subject_data['attendance_status'] == 'absent') {
                                        $a_is_absent = true;
                                        break;
                                    }
                                }
                                
                                // Check if student b is absent
                                $b_is_absent = false;
                                foreach ($b['subjects'] as $subject_data) {
                                    if ($subject_data['attendance_status'] == 'absent') {
                                        $b_is_absent = true;
                                        break;
                                    }
                                }
                                
                                if ($sort_by == 'absent_first') {
                                    // Absent students first
                                    return $b_is_absent - $a_is_absent; // Reverse order for absent first
                                } else {
                                    // Present students first
                                    return $a_is_absent - $b_is_absent; // Normal order for present first
                                }
                            });
                        }
                        
                        $selected_class = $class_id;
                        $selected_session = $session;
                        $selected_group = $group_name;
                    }
                }
            }
        } catch (Exception $e) {
            $error_message = 'ত্রুটি: ' . $e->getMessage();
        }
    }
}

// Handle save absence list
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_absences'])) {
    try {
        $pdo->beginTransaction();
        
        $absence_data = $_POST['absence'] ?? [];
        
        foreach ($absence_data as $student_id => $subjects) {
            foreach ($subjects as $subject_id => $data) {
                $absent_count = (int)($data['absent'] ?? 0);
                $remarks = trim($data['remarks'] ?? '');
                
                // Save to database - for simplicity, we'll just update a note
                // In a real implementation, you might want to store this in a separate table
                // For now, we'll just show a success message
            }
        }
        
        $pdo->commit();
        $success_message = 'অনুপস্থিতির তালিকা সফলভাবে সংরক্ষণ করা হয়েছে!';
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_message = 'ত্রুটি: ' . $e->getMessage();
    }
}

// Get all exams for dropdown
$all_exams = $pdo->query("
    SELECT e.id, e.name, c.name as class_name, c.section, e.session, e.group_name
    FROM exams e
    JOIN classes c ON e.class_id = c.id
    ORDER BY e.created_at DESC
")->fetchAll();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>পরীক্ষার অনুপস্থিতির তালিকা - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .bengali-text {
            font-family: 'Kalpurush', 'SolaimanLipi', 'Nikosh', sans-serif;
        }
        .attendance-table th, .attendance-table td {
            border: 1px solid #dee2e6 !important;
            padding: 8px !important;
            vertical-align: middle;
        }
        .absent-count {
            width: 80px;
        }
        .print-only { display: none; }
        @media print {
            .no-print { display: none !important; }
            .print-only { display: block !important; }
            body { font-size: 12px; }
            .table { font-size: 11px; }
        }
        /* Highlight absent students */
        .absent-student {
            background-color: #f8d7da !important;
            transition: background-color 0.3s ease;
        }
        .present-student {
            background-color: #d4edda !important;
            transition: background-color 0.3s ease;
        }
        .late-student {
            background-color: #fff3cd !important;
            transition: background-color 0.3s ease;
        }
        /* Prevent checkbox blinking */
        .student-checkbox {
            transition: none;
            outline: none;
        }
        .student-checkbox:disabled {
            opacity: 1;
        }
    </style>
</head>
<body class="bengali-text">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="routine.php">
                    <i class="fas fa-calendar"></i> পরীক্ষার রুটিন
                </a>
                <a class="nav-link" href="attendance.php">
                    <i class="fas fa-clipboard-check"></i> হাজিরা পত্র
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-md-12">
                <h2 class="mb-4"><i class="fas fa-user-times"></i> পরীক্ষার অনুপস্থিতির তালিকা</h2>
                
                <!-- Filter Form -->
                <div class="card no-print mb-4">
                    <div class="card-header">
                        <h5><i class="fas fa-filter"></i> ফিল্টার করুন</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="" id="filterForm">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="exam_id" class="form-label">পরীক্ষা নির্বাচন করুন *</label>
                                        <select class="form-select" id="exam_id" name="exam_id" required>
                                            <option value="">পরীক্ষা নির্বাচন করুন</option>
                                            <?php foreach ($all_exams as $exam): ?>
                                                <option value="<?php echo $exam['id']; ?>" 
                                                        <?php echo (isset($_POST['exam_id']) && $_POST['exam_id'] == $exam['id']) ? 'selected' : ''; ?>>
                                                    <?php echo $exam['name'] . ' - ' . $exam['class_name'] . ' (' . $exam['section'] . ')'; ?>
                                                    <?php if ($exam['group_name']): ?>
                                                        - <?php echo $exam['group_name']; ?>
                                                    <?php endif; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="class_id" class="form-label">ক্লাস নির্বাচন করুন *</label>
                                        <select class="form-select" id="class_id" name="class_id" required>
                                            <option value="">ক্লাস নির্বাচন করুন</option>
                                            <?php foreach ($classes as $class): ?>
                                                <option value="<?php echo $class['id']; ?>" 
                                                        <?php echo (isset($_POST['class_id']) && $_POST['class_id'] == $class['id']) ? 'selected' : ''; ?>>
                                                    <?php echo $class['name'] . ' - ' . $class['section']; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="session" class="form-label">সেশন নির্বাচন করুন *</label>
                                        <select class="form-select" id="session" name="session" required>
                                            <option value="">সেশন নির্বাচন করুন</option>
                                            <?php foreach ($sessions as $sess): ?>
                                                <option value="<?php echo $sess['session']; ?>" 
                                                        <?php echo (isset($_POST['session']) && $_POST['session'] == $sess['session']) ? 'selected' : ''; ?>>
                                                    <?php echo $sess['session']; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="group_name" class="form-label">গ্রুপ (ঐচ্ছিক)</label>
                                        <input type="text" class="form-control" id="group_name" name="group_name" 
                                               placeholder="যেমন: সাধারণ, বিজ্ঞান, মানবিক" 
                                               value="<?php echo isset($_POST['group_name']) ? htmlspecialchars($_POST['group_name']) : ''; ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Search and Additional Filters -->
                            <div class="row mt-3">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="search_student" class="form-label">শিক্ষার্থী অনুসন্ধান (নাম, রোল, আইডি)</label>
                                        <input type="text" class="form-control" id="search_student" name="search_student" 
                                               placeholder="শিক্ষার্থীর নাম, রোল নং বা আইডি দিয়ে অনুসন্ধান করুন" 
                                               value="<?php echo isset($_POST['search_student']) ? htmlspecialchars($_POST['search_student']) : ''; ?>">
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="attendance_status" class="form-label">
                                            অনুপস্থিতির অবস্থা <i class="fas fa-caret-down"></i>
                                        </label>
                                        <select class="form-select" id="attendance_status" name="attendance_status">
                                            <option value="">সব অবস্থা</option>
                                            <option value="absent" <?php echo (isset($_POST['attendance_status']) && $_POST['attendance_status'] == 'absent') ? 'selected' : ''; ?>>অনুপস্থিত</option>
                                            <option value="present" <?php echo (isset($_POST['attendance_status']) && $_POST['attendance_status'] == 'present') ? 'selected' : ''; ?>>উপস্থিত</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="sort_by" class="form-label">
                                            সাজানো <i class="fas fa-caret-down"></i>
                                        </label>
                                        <select class="form-select" id="sort_by" name="sort_by">
                                            <option value="roll_asc" <?php echo (!isset($_POST['sort_by']) || $_POST['sort_by'] == 'roll_asc') ? 'selected' : ''; ?>>রোল নং (ছোট থেকে বড়)</option>
                                            <option value="roll_desc" <?php echo (isset($_POST['sort_by']) && $_POST['sort_by'] == 'roll_desc') ? 'selected' : ''; ?>>রোল নং (বড় থেকে ছোট)</option>
                                            <option value="name_asc" <?php echo (isset($_POST['sort_by']) && $_POST['sort_by'] == 'name_asc') ? 'selected' : ''; ?>>নাম (A-Z)</option>
                                            <option value="name_desc" <?php echo (isset($_POST['sort_by']) && $_POST['sort_by'] == 'name_desc') ? 'selected' : ''; ?>>নাম (Z-A)</option>
                                            <option value="absent_first" <?php echo (isset($_POST['sort_by']) && $_POST['sort_by'] == 'absent_first') ? 'selected' : ''; ?>>অনুপস্থিত প্রথমে</option>
                                            <option value="present_first" <?php echo (isset($_POST['sort_by']) && $_POST['sort_by'] == 'present_first') ? 'selected' : ''; ?>>উপস্থিত প্রথমে</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-end">
                                <button type="submit" name="generate_list" class="btn btn-primary">
                                    <i class="fas fa-list"></i> তালিকা তৈরি করুন
                                </button>
                                <button type="button" class="btn btn-secondary ms-2" onclick="clearFilters()">
                                    <i class="fas fa-times"></i> ফিল্টার মুছুন
                                </button>
                                <?php if (!empty($absence_list)): ?>
                                    <button type="button" class="btn btn-success ms-2" onclick="window.print()">
                                        <i class="fas fa-print"></i> প্রিন্ট করুন
                                    </button>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Messages -->
                <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show no-print" role="alert">
                        <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show no-print" role="alert">
                        <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <!-- Absence List -->
                <?php if (!empty($absence_list) && $exam_details): ?>
                    <div class="card">
                        <div class="card-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5><i class="fas fa-clipboard-list"></i> অনুপস্থিতির তালিকা</h5>
                                <div class="no-print">
                                    <button type="button" class="btn btn-success btn-sm" onclick="window.print()">
                                        <i class="fas fa-print"></i> প্রিন্ট করুন
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <!-- Print Header -->
                            <div class="print-only text-center mb-4">
                                <h3>পরীক্ষার অনুপস্থিতির তালিকা</h3>
                                <h4><?php echo $exam_details['name']; ?></h4>
                                <p>
                                    <strong>ক্লাস:</strong> <?php echo $exam_details['class_name'] . ' - ' . $exam_details['section']; ?> |
                                    <strong>সেশন:</strong> <?php echo $selected_session; ?>
                                    <?php if ($selected_group): ?>
                                        | <strong>গ্রুপ:</strong> <?php echo $selected_group; ?>
                                    <?php endif; ?>
                                </p>
                            </div>
                            
                            <form method="POST" action="" class="no-print">
                                <input type="hidden" name="save_absences" value="1">
                                <input type="hidden" id="exam_id_hidden" value="<?php echo $exam_details['id']; ?>">
                                
                                <div class="table-responsive">
                                    <table class="table table-bordered attendance-table">
                                        <thead class="table-dark">
                                            <tr>
                                                <th style="width: 5%;"><input type="checkbox" id="selectAllCheckbox"> নির্বাচন</th>
                                                <th style="width: 5%;">ক্রমিক</th>
                                                <th style="width: 10%;">রোল নং</th>
                                                <th style="width: 15%;">শিক্ষার্থী আইডি</th>
                                                <th style="width: 25%;">নাম</th>
                                                <th style="width: 15%;">গ্রুপ</th>
                                                <th style="width: 15%;">অনুপস্থিতি</th>
                                                <th style="width: 10%;">মন্তব্য</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $total_absents = 0;
                                            foreach ($absence_list as $index => $student_data): 
                                                // Calculate if student is absent (any subject absent)
                                                $is_absent = false;
                                                foreach ($student_data['subjects'] as $subject_data) {
                                                    if ($subject_data['attendance_status'] == 'absent') {
                                                        $is_absent = true;
                                                        $total_absents++;
                                                        break;
                                                    }
                                                }
                                                $row_class = $is_absent ? 'absent-student' : '';
                                            ?>
                                                <tr class="<?php echo $row_class; ?>" id="student-row-<?php echo $student_data['student']['id']; ?>">
                                                    <td class="text-center">
                                                        <input type="checkbox" class="student-checkbox" 
                                                               data-student-id="<?php echo $student_data['student']['id']; ?>"
                                                               <?php echo $is_absent ? 'checked' : ''; ?>>
                                                    </td>
                                                    <td><?php echo $index + 1; ?></td>
                                                    <td><?php echo $student_data['student']['roll_number']; ?></td>
                                                    <td><?php echo $student_data['student']['student_id']; ?></td>
                                                    <td><?php echo $student_data['student']['first_name'] . ' ' . $student_data['student']['last_name']; ?></td>
                                                    <td><?php echo $student_data['student']['group_name'] ?? '-'; ?></td>
                                                    <td class="text-center">
                                                        <?php if ($is_absent): ?>
                                                            <span class="badge bg-danger">অনুপস্থিত</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-success">উপস্থিত</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        // Find remarks for this student
                                                        $remarks = '';
                                                        foreach ($student_data['subjects'] as $subject_data) {
                                                            if (!empty($subject_data['remarks'])) {
                                                                $remarks .= $subject_data['subject']['subject_name'] . ': ' . $subject_data['remarks'] . '; ';
                                                            }
                                                        }
                                                        echo htmlspecialchars($remarks);
                                                        ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot class="table-secondary">
                                            <tr>
                                                <th colspan="6">মোট</th>
                                                <th class="text-center" id="total-absents-footer"><?php echo $total_absents; ?></th>
                                                <th></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                                
                                <div class="d-flex justify-content-between align-items-center mt-3">
                                    <div>
                                        <small class="text-muted">
                                            মোট শিক্ষার্থী: <?php echo count($absence_list); ?> জন | 
                                            মোট অনুপস্থিতি: <span id="total-absents-display"><?php echo $total_absents; ?></span> টি
                                        </small>
                                    </div>
                                    <div>
                                        <button type="submit" class="btn btn-success">
                                            <i class="fas fa-save"></i> তালিকা সংরক্ষণ করুন
                                        </button>
                                    </div>
                                </div>
                            </form>
                            
                            <!-- Print Version -->
                            <div class="print-only mt-4">
                                <div class="table-responsive">
                                    <table class="table table-bordered attendance-table">
                                        <thead>
                                            <tr>
                                                <th style="width: 5%;">ক্রমিক</th>
                                                <th style="width: 10%;">রোল নং</th>
                                                <th style="width: 15%;">শিক্ষার্থী আইডি</th>
                                                <th style="width: 25%;">নাম</th>
                                                <th style="width: 15%;">গ্রুপ</th>
                                                <th style="width: 15%;">অনুপস্থিতি</th>
                                                <th style="width: 15%;">মন্তব্য</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $print_total_absents = 0;
                                            foreach ($absence_list as $index => $student_data): 
                                                // Calculate if student is absent (any subject absent)
                                                $is_absent = false;
                                                foreach ($student_data['subjects'] as $subject_data) {
                                                    if ($subject_data['attendance_status'] == 'absent') {
                                                        $is_absent = true;
                                                        $print_total_absents++;
                                                        break;
                                                    }
                                                }
                                                $row_class = $is_absent ? 'absent-student' : '';
                                            ?>
                                                <tr class="<?php echo $row_class; ?>">
                                                    <td><?php echo $index + 1; ?></td>
                                                    <td><?php echo $student_data['student']['roll_number']; ?></td>
                                                    <td><?php echo $student_data['student']['student_id']; ?></td>
                                                    <td><?php echo $student_data['student']['first_name'] . ' ' . $student_data['student']['last_name']; ?></td>
                                                    <td><?php echo $student_data['student']['group_name'] ?? '-'; ?></td>
                                                    <td class="text-center">
                                                        <?php if ($is_absent): ?>
                                                            অনুপস্থিত
                                                        <?php else: ?>
                                                            উপস্থিত
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        // Find remarks for this student
                                                        $remarks = '';
                                                        foreach ($student_data['subjects'] as $subject_data) {
                                                            if (!empty($subject_data['remarks'])) {
                                                                $remarks .= $subject_data['subject']['subject_name'] . ': ' . $subject_data['remarks'] . '; ';
                                                            }
                                                        }
                                                        echo htmlspecialchars($remarks);
                                                        ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <th colspan="5">মোট</th>
                                                <th class="text-center"><?php echo $print_total_absents; ?></th>
                                                <th></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                                
                                <div class="mt-4">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>তৈরি করেছেন:</strong> _____________________</p>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>পরীক্ষকের স্বাক্ষর:</strong> _____________________</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php elseif (isset($_POST['generate_list']) && empty($absence_list)): ?>
                    <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>
        // Select all checkboxes functionality
        document.getElementById('selectAllCheckbox').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
                // Trigger change event to update attendance status
                checkbox.dispatchEvent(new Event('change'));
            });
        });
        
        // Add event listeners to student checkboxes
        document.addEventListener('DOMContentLoaded', function() {
            const checkboxes = document.querySelectorAll('.student-checkbox');
            checkboxes.forEach(checkbox => {
                // Add a small delay to prevent rapid firing
                let timeoutId = null;
                
                checkbox.addEventListener('change', function() {
                    // Clear any existing timeout
                    if (timeoutId) {
                        clearTimeout(timeoutId);
                    }
                    
                    const studentId = this.getAttribute('data-student-id');
                    const isChecked = this.checked;
                    const examId = document.getElementById('exam_id_hidden').value;
                    
                    // Update UI immediately for better responsiveness
                    updateStudentRow(studentId, isChecked);
                    
                    // Debounce the database update to prevent rapid requests
                    timeoutId = setTimeout(() => {
                        updateAttendanceStatus(examId, studentId, isChecked);
                    }, 300); // 300ms delay
                });
            });
        });
        
        // Function to update student row UI
        function updateStudentRow(studentId, isAbsent) {
            const row = document.getElementById('student-row-' + studentId);
            const statusCell = row.querySelector('td:nth-child(7)'); // Status column (7th column)
            
            if (isAbsent) {
                row.classList.add('absent-student');
                // Update status badge
                if (statusCell) {
                    statusCell.innerHTML = '<span class="badge bg-danger">অনুপস্থিত</span>';
                }
                
                // Update total absents in footer
                updateTotalAbsents();
            } else {
                row.classList.remove('absent-student');
                // Update status badge
                if (statusCell) {
                    statusCell.innerHTML = '<span class="badge bg-success">উপস্থিত</span>';
                }
                
                // Update total absents in footer
                updateTotalAbsents();
            }
        }
        
        // Function to update total absents in footer
        function updateTotalAbsents() {
            // Count current absent students by checking checkboxes
            let total = 0;
            const checkboxes = document.querySelectorAll('.student-checkbox:checked');
            total = checkboxes.length;
            
            // Update footer total
            const footerTotal = document.getElementById('total-absents-footer');
            if (footerTotal) {
                footerTotal.textContent = total;
            }
            
            // Update display total
            const displayTotal = document.getElementById('total-absents-display');
            if (displayTotal) {
                displayTotal.textContent = total;
            }
        }
        
        // Function to send AJAX request to update attendance status
        function updateAttendanceStatus(examId, studentId, isAbsent) {
            // Show a temporary loading indicator
            const checkbox = document.querySelector(`.student-checkbox[data-student-id="${studentId}"]`);
            const originalState = checkbox.checked;
            
            // Disable checkbox during request to prevent multiple clicks
            checkbox.disabled = true;
            
            // Send AJAX request to update database
            fetch('update_attendance.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    exam_id: examId,
                    student_id: studentId,
                    is_absent: isAbsent
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('Attendance updated successfully for student ' + studentId);
                } else {
                    console.error('Failed to update attendance:', data.message);
                    // Revert UI changes if update failed
                    revertCheckbox(studentId, !isAbsent);
                }
            })
            .catch(error => {
                console.error('Error updating attendance:', error);
                // Revert UI changes if update failed
                revertCheckbox(studentId, !isAbsent);
            })
            .finally(() => {
                // Re-enable checkbox after request completes
                checkbox.disabled = false;
            });
        }
        
        // Function to revert checkbox state if update fails
        function revertCheckbox(studentId, checkedState) {
            const checkbox = document.querySelector(`.student-checkbox[data-student-id="${studentId}"]`);
            if (checkbox) {
                checkbox.checked = checkedState;
                // Trigger change event to update UI
                checkbox.dispatchEvent(new Event('change'));
            }
        }
        
        // Function to clear all filters
        function clearFilters() {
            document.getElementById('filterForm').reset();
            document.getElementById('filterForm').submit();
        }
    </script>
</body>
</html>