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

// Debug session information
/*
echo "<pre>";
echo "Session ID: " . session_id() . "\n";
echo "Session data: ";
print_r($_SESSION);
echo "</pre>";
*/

// Admin only
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    // Log the attempted access for debugging
    error_log("Bulk remove access denied - User ID: " . ($_SESSION['user_id'] ?? 'NOT SET') . 
              " Role: " . ($_SESSION['user_role'] ?? 'NOT SET') . 
              " Session ID: " . session_id());
    
    // Redirect to login with a message
    $_SESSION['error_message'] = 'আপনার এই পেজটি দেখার অনুমতি নেই। অ্যাডমিন হিসেবে লগইন করুন।';
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';
$fees_to_remove = [];

// Get filter parameters and decode URL-encoded values
$session = $_GET['session'] ?? '';
$class_id = $_GET['class_id'] ?? '';
$fee_type = $_GET['fee_type'] ?? '';

// Decode URL-encoded values after retrieving them
$session = urldecode($session);
$fee_type = urldecode($fee_type);

// Fetch data for dropdowns
// Get sessions from academic_sessions table first, then add any additional ones from fees
$active_sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll(PDO::FETCH_COLUMN);
$fee_sessions = $pdo->query("SELECT DISTINCT academic_year FROM fees WHERE academic_year IS NOT NULL AND academic_year != '' ORDER BY academic_year DESC")->fetchAll(PDO::FETCH_COLUMN);

// Merge sessions, removing duplicates
$sessions = array_unique(array_merge($active_sessions, $fee_sessions));
sort($sessions);
$sessions = array_reverse($sessions);
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll(PDO::FETCH_ASSOC);
$fee_types = $pdo->query("SELECT DISTINCT fee_type FROM fees ORDER BY fee_type")->fetchAll(PDO::FETCH_COLUMN);

// Handle form submission for removing fees
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_remove'])) {
    $fee_ids = $_POST['fee_ids'] ?? [];
    if (!empty($fee_ids)) {
        try {
            $pdo->beginTransaction();
            $delete_stmt = $pdo->prepare("DELETE FROM fees WHERE id = ?");
            $deleted_count = 0;
            foreach ($fee_ids as $fee_id) {
                $delete_stmt->execute([$fee_id]);
                $deleted_count++;
            }
            $pdo->commit();
            $success_message = "সফলভাবে $deleted_count টি ফি মুছে ফেলা হয়েছে।";
        } catch (Exception $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error_message = "ফি মুছে ফেলার সময় একটি ত্রুটি হয়েছে: " . $e->getMessage();
        }
    } else {
        $error_message = "কোনো ফি নির্বাচন করা হয়নি।";
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_selected'])) {
    $fee_ids = $_POST['fee_ids'] ?? [];
    if (!empty($fee_ids)) {
        // Fetch the fees to show confirmation
        $placeholders = str_repeat('?,', count($fee_ids) - 1) . '?';
        $stmt = $pdo->prepare("SELECT f.*, s.first_name, s.last_name, s.roll_number 
                              FROM fees f 
                              JOIN students s ON f.student_id = s.id
                              WHERE f.id IN ($placeholders)");
        $stmt->execute($fee_ids);
        $fees_to_remove = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $error_message = "কোনো ফি নির্বাচন করা হয়নি।";
    }
}

// Fetch fees to remove based on filters
if ($session && $class_id) {
    $sql = "SELECT f.*, s.first_name, s.last_name, s.roll_number 
            FROM fees f 
            JOIN students s ON f.student_id = s.id
            WHERE s.class_id = :class_id AND f.academic_year = :session";
    $params = ['class_id' => $class_id, 'session' => $session];
    
    if ($fee_type) {
        $sql .= " AND f.fee_type = :fee_type";
        $params['fee_type'] = $fee_type;
    }
    $sql .= " ORDER BY s.roll_number, f.due_date";
    

    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $fees_to_remove = $stmt->fetchAll(PDO::FETCH_ASSOC);
    

    
    // Show list of all students with fees for this session, class, and fee type
    $student_list_sql = "SELECT s.first_name, s.last_name, s.student_id, s.roll_number, 
                        f.fee_type, f.amount, f.paid_amount, f.due_date, f.academic_year, f.status,
                        (f.amount - COALESCE(f.paid_amount, 0)) as due_amount
                     FROM students s 
                     JOIN fees f ON s.id = f.student_id 
                     WHERE s.class_id = :class_id 
                     AND (:session = '' OR f.academic_year = :session)
                     AND (:fee_type = '' OR f.fee_type = :fee_type)
                     ORDER BY s.roll_number, f.due_date";
    
    $student_params = [
        'class_id' => $class_id,
        'session' => $session,
        'fee_type' => $fee_type
    ];
    
    $student_stmt = $pdo->prepare($student_list_sql);
    $student_stmt->execute($student_params);
    $all_students_with_fees = $student_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<div class='card mt-4'>";
    echo "<div class='card-header'>";
    echo "<h5><i class='fas fa-users'></i> এই সেশন, ক্লাস ও ফি টাইপের জন্য ছাত্র-ছাত্রীদের তালিকা</h5>";
    echo "</div>";
    echo "<div class='card-body'>";
    
    if (empty($all_students_with_fees)) {
        echo "<div class='alert alert-info'>এই সেশন, ক্লাস ও ফি টাইপের জন্য কোনো ছাত্র-ছাত্রী পাওয়া যায়নি।</div>";
    } else {
        echo "<div class='table-responsive'>";
        echo "<table class='table table-striped table-bordered'>";
        echo "<thead class='table-primary'>";
        echo "<tr>";
        echo "<th>রোল নম্বর</th>";
        echo "<th>ছাত্র-ছাত্রী</th>";
        echo "<th>আইডি</th>";
        echo "<th>ফি ধরন</th>";
        echo "<th>মোট পরিমাণ</th>";
        echo "<th>পরিশোধিত</th>";
        echo "<th>বকেয়া</th>";
        echo "<th>শেষ তারিখ</th>";
        echo "<th>অবস্থা</th>";
        echo "</tr>";
        echo "</thead>";
        echo "<tbody>";
        
        foreach ($all_students_with_fees as $student) {
            $status_class = '';
            switch (strtolower($student['status'])) {
                case 'paid': $status_class = 'bg-success'; break;
                case 'partial': $status_class = 'bg-warning text-dark'; break;
                case 'pending': $status_class = 'bg-info'; break;
                case 'overdue': $status_class = 'bg-danger'; break;
                default: $status_class = 'bg-secondary';
            }
            
            echo "<tr>";
            echo "<td>" . htmlspecialchars($student['roll_number']) . "</td>";
            echo "<td>" . htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) . "</td>";
            echo "<td>" . htmlspecialchars($student['student_id']) . "</td>";
            echo "<td>" . htmlspecialchars($student['fee_type']) . "</td>";
            echo "<td>৳" . number_format($student['amount'], 2) . "</td>";
            echo "<td>৳" . number_format($student['paid_amount'], 2) . "</td>";
            echo "<td class='" . ($student['due_amount'] > 0 ? 'text-danger fw-bold' : 'text-success') . "'>৳" . number_format($student['due_amount'], 2) . "</td>";
            echo "<td>" . date('d/m/Y', strtotime($student['due_date'])) . "</td>";
            echo "<td><span class='badge {$status_class}'>" . ucfirst($student['status']) . "</span></td>";
            echo "</tr>";
        }
        
        echo "</tbody>";
        echo "</table>";
        echo "</div>";
        
        // Summary statistics
        $total_students = count($all_students_with_fees);
        $total_amount = array_sum(array_column($all_students_with_fees, 'amount')); 
        $total_paid = array_sum(array_column($all_students_with_fees, 'paid_amount'));
        $total_due = $total_amount - $total_paid;
        
        echo "<div class='row mt-3'>";
        echo "<div class='col-md-3'>";
        echo "<div class='card bg-primary text-white'>";
        echo "<div class='card-body text-center'>";
        echo "<h5>{$total_students}</h5>";
        echo "<p class='mb-0'>মোট ছাত্র-ছাত্রী</p>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
        
        echo "<div class='col-md-3'>";
        echo "<div class='card bg-success text-white'>";
        echo "<div class='card-body text-center'>";
        echo "<h5>৳" . number_format($total_amount, 2) . "</h5>";
        echo "<p class='mb-0'>মোট পরিমাণ</p>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
        
        echo "<div class='col-md-3'>";
        echo "<div class='card bg-info text-white'>";
        echo "<div class='card-body text-center'>";
        echo "<h5>৳" . number_format($total_paid, 2) . "</h5>";
        echo "<p class='mb-0'>পরিশোধিত</p>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
        
        echo "<div class='col-md-3'>";
        echo "<div class='card bg-danger text-white'>";
        echo "<div class='card-body text-center'>";
        echo "<h5>৳" . number_format($total_due, 2) . "</h5>";
        echo "<p class='mb-0'>বকেয়া</p>";
        echo "</div>";
        echo "</div>";
        echo "</div>";
        
        echo "</div>";
    }
    
    echo "</div>";
    echo "</div>";
}

?>

<!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: #f4f7f6;
        }
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid #eee;
            font-weight: 600;
            font-size: 1.2rem;
            padding: 1rem 1.5rem;
            border-radius: 15px 15px 0 0 !important;
        }
        .table-bordered {
            border-radius: 0 0 15px 15px;
            overflow: hidden;
        }
        .table thead th {
            background-color: #e74c3c;
            color: white;
            border-color: #e74c3c;
        }
        .btn-danger {
            background-color: #e74c3c;
            border-color: #e74c3c;
        }
        .btn-danger:hover {
            background-color: #c0392b;
            border-color: #c0392b;
        }
        .btn-primary {
            background-color: #667eea;
            border-color: #667eea;
        }
        .btn-primary:hover {
            background-color: #5a67d8;
            border-color: #5a67d8;
        }
        .pagination .page-item.active .page-link {
            background-color: #e74c3c;
            border-color: #e74c3c;
        }
        .form-control, .form-select {
            border-radius: 8px;
        }
        .form-control:focus, .form-select:focus {
            border-color: #e74c3c;
            box-shadow: 0 0 0 0.25rem rgba(231, 76, 60, 0.25);
        }
        .alert-danger {
            background-color: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }
        .alert-success {
            background-color: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }
    </style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark mb-4">
    <div class="container-fluid">
        <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> ফি ম্যানেজমেন্ট</a>
        <a class="nav-link text-white" href="manage.php"><i class="fas fa-arrow-left"></i> ফি ব্যবস্থাপনায় ফিরে যান</a>
    </div>
</nav>

<div class="container-fluid">
    <div class="card filter-card">
        <div class="card-header">
            <h5><i class="fas fa-filter"></i> ফি ফিল্টার করুন</h5>
        </div>
        <div class="card-body">
            <form method="GET" action="">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">সেশন</label>
                        <select name="session" class="form-select" required>
                            <option value="">সেশন নির্বাচন করুন</option>
                            <?php foreach ($sessions as $sess): ?>
                                <option value="<?php echo htmlspecialchars($sess); ?>" <?php echo ($session === $sess) ? 'selected' : ''; ?>><?php echo htmlspecialchars($sess); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">ক্লাস</label>
                        <select name="class_id" class="form-select" required>
                            <option value="">ক্লাস নির্বাচন করুন</option>
                            <?php foreach ($classes as $class): ?>
                                <option value="<?php echo $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-4">
                        <label class="form-label">ফি-এর ধরন (ঐচ্ছিক)</label>
                        <select name="fee_type" class="form-select">
                            <option value="">সকল ধরন</option>
                            <?php foreach ($fee_types as $ft): ?>
                                <option value="<?php echo htmlspecialchars($ft); ?>" <?php echo ($fee_type === $ft) ? 'selected' : ''; ?>><?php echo htmlspecialchars($ft); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12 text-center mt-4">
                        <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-search"></i> ফি খুঁজুন</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <?php if ($success_message): ?><div class="alert alert-success mt-3"><?php echo $success_message; ?></div><?php endif; ?>
    <?php if ($error_message): ?><div class="alert alert-danger mt-3"><?php echo $error_message; ?></div><?php endif; ?>

    <?php if (!empty($fees_to_remove) && !isset($_POST['remove_selected'])): ?>
    <form method="POST" action="">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5><i class="fas fa-trash-alt"></i> ফি রিমুভ করুন</h5>
                <div class="w-50">
                    <input type="text" id="feeSearchInput" class="form-control" placeholder="রোল বা নাম দিয়ে খুঁজুন...">
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered mb-0">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="selectAll"></th>
                                <th>রোল</th>
                                <th>নাম</th>
                                <th>ফি-এর ধরন</th>
                                <th>পরিমাণ</th>
                                <th>শেষ তারিখ</th>
                                <th>স্ট্যাটাস</th>
                                <th>মন্তব্য</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($fees_to_remove as $fee): ?>
                            <tr>
                                <td><input type="checkbox" name="fee_ids[]" value="<?php echo $fee['id']; ?>"></td>
                                <td><?php echo htmlspecialchars($fee['roll_number']); ?></td>
                                <td><?php echo htmlspecialchars($fee['first_name'] . ' ' . $fee['last_name']); ?></td>
                                <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                                <td><?php echo htmlspecialchars($fee['amount']); ?></td>
                                <td><?php echo htmlspecialchars($fee['due_date']); ?></td>
                                <td><?php echo htmlspecialchars($fee['status']); ?></td>
                                <td><?php echo htmlspecialchars($fee['remarks']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer d-flex justify-content-between align-items-center">
                <div id="pagination-summary" class="text-muted"></div>
                <nav id="pagination-nav"></nav>
                <button type="submit" name="remove_selected" class="btn btn-danger"><i class="fas fa-trash-alt"></i> নির্বাচিত ফি রিমুভ করুন</button>
            </div>
        </div>
    </form>
    <?php elseif (isset($_POST['remove_selected']) && !empty($fees_to_remove)): ?>
    <!-- Confirmation page -->
    <form method="POST" action="">
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-exclamation-triangle"></i> কনফার্ম রিমুভ</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-danger">
                    <h5><i class="fas fa-exclamation-circle"></i> সতর্কতা!</h5>
                    <p>আপনি কি নিশ্চিত যে আপনি নিম্নলিখিত <?php echo count($fees_to_remove); ?> টি ফি মুছে ফেলতে চান? এই কাজটি পুনরুদ্ধার করা সম্ভব নয়।</p>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>রোল</th>
                                <th>নাম</th>
                                <th>ফি-এর ধরন</th>
                                <th>পরিমাণ</th>
                                <th>শেষ তারিখ</th>
                                <th>স্ট্যাটাস</th>
                                <th>মন্তব্য</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($fees_to_remove as $fee): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($fee['roll_number']); ?></td>
                                <td><?php echo htmlspecialchars($fee['first_name'] . ' ' . $fee['last_name']); ?></td>
                                <td><?php echo htmlspecialchars($fee['fee_type']); ?></td>
                                <td><?php echo htmlspecialchars($fee['amount']); ?></td>
                                <td><?php echo htmlspecialchars($fee['due_date']); ?></td>
                                <td><?php echo htmlspecialchars($fee['status']); ?></td>
                                <td><?php echo htmlspecialchars($fee['remarks']); ?></td>
                                <input type="hidden" name="fee_ids[]" value="<?php echo $fee['id']; ?>">
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer">
                <button type="submit" name="confirm_remove" class="btn btn-danger"><i class="fas fa-trash-alt"></i> হ্যাঁ, ফি মুছে ফেলুন</button>
                <a href="bulk_remove.php" class="btn btn-secondary"><i class="fas fa-times"></i> বাতিল করুন</a>
            </div>
        </div>
    </form>
    <?php elseif(isset($_GET['session'])): ?>
        <div class="alert alert-info mt-3">আপনার নির্বাচিত ফিল্টারে কোনো ফি পাওয়া যায়নি।</div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Select all checkbox functionality
    const selectAllCheckbox = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('input[name="fee_ids[]"]');
    
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
        });
    }
    
    const searchInput = document.getElementById('feeSearchInput');
    const table = document.querySelector('.table-bordered');
    const tbody = table?.querySelector('tbody');
    const rows = tbody ? Array.from(tbody.querySelectorAll('tr')) : [];
    
    const paginationSummary = document.getElementById('pagination-summary');
    const paginationNav = document.getElementById('pagination-nav');
    const rowsPerPage = 10;
    let currentPage = 1;
    let filteredRows = rows;

    function setupPagination() {
        if (!tbody) return;

        function displayPage(page) {
            currentPage = page;
            rows.forEach(row => row.style.display = 'none');
            
            const startIndex = (page - 1) * rowsPerPage;
            const endIndex = startIndex + rowsPerPage;
            const pageRows = filteredRows.slice(startIndex, endIndex);
            pageRows.forEach(row => row.style.display = '');

            if (paginationSummary) {
                const start = Math.min(startIndex + 1, filteredRows.length);
                const end = Math.min(endIndex, filteredRows.length);
                paginationSummary.textContent = `${filteredRows.length} টির মধ্যে ${start}-${end} টি দেখানো হচ্ছে`;
            }

            renderPaginationLinks();
        }

        function renderPaginationLinks() {
            if (!paginationNav) return;
            paginationNav.innerHTML = '';
            const pageCount = Math.ceil(filteredRows.length / rowsPerPage);

            if (pageCount <= 1) return;

            const ul = document.createElement('ul');
            ul.className = 'pagination pagination-sm mb-0';

            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
            const prevA = document.createElement('a');
            prevA.className = 'page-link';
            prevA.href = '#';
            prevA.innerHTML = '&laquo;';
            prevA.addEventListener('click', (e) => {
                e.preventDefault();
                if (currentPage > 1) displayPage(currentPage - 1);
            });
            prevLi.appendChild(prevA);
            ul.appendChild(prevLi);

            // Page numbers logic
            const maxPagesToShow = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
            let endPage = Math.min(pageCount, startPage + maxPagesToShow - 1);
            if (endPage - startPage + 1 < maxPagesToShow) {
                startPage = Math.max(1, endPage - maxPagesToShow + 1);
            }

            if (startPage > 1) {
                const firstLi = document.createElement('li');
                firstLi.className = 'page-item';
                const firstA = document.createElement('a');
                firstA.className = 'page-link';
                firstA.href = '#';
                firstA.textContent = '1';
                firstA.addEventListener('click', (e) => { e.preventDefault(); displayPage(1); });
                firstLi.appendChild(firstA);
                ul.appendChild(firstLi);
                if (startPage > 2) {
                    const dotsLi = document.createElement('li');
                    dotsLi.className = 'page-item disabled';
                    dotsLi.innerHTML = '<span class="page-link">...</span>';
                    ul.appendChild(dotsLi);
                }
            }

            for (let i = startPage; i <= endPage; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                const a = document.createElement('a');
                a.className = 'page-link';
                a.href = '#';
                a.textContent = i;
                a.addEventListener('click', (e) => {
                    e.preventDefault();
                    displayPage(i);
                });
                li.appendChild(a);
                ul.appendChild(li);
            }

            if (endPage < pageCount) {
                if (endPage < pageCount - 1) {
                    const dotsLi = document.createElement('li');
                    dotsLi.className = 'page-item disabled';
                    dotsLi.innerHTML = '<span class="page-link">...</span>';
                    ul.appendChild(dotsLi);
                }
                const lastLi = document.createElement('li');
                lastLi.className = 'page-item';
                const lastA = document.createElement('a');
                lastA.className = 'page-link';
                lastA.href = '#';
                lastA.textContent = pageCount;
                lastA.addEventListener('click', (e) => { e.preventDefault(); displayPage(pageCount); });
                lastLi.appendChild(lastA);
                ul.appendChild(lastLi);
            }

            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${currentPage === pageCount ? 'disabled' : ''}`;
            const nextA = document.createElement('a');
            nextA.className = 'page-link';
            nextA.href = '#';
            nextA.innerHTML = '&raquo;';
            nextA.addEventListener('click', (e) => {
                e.preventDefault();
                if (currentPage < pageCount) displayPage(currentPage + 1);
            });
            nextLi.appendChild(nextA);
            ul.appendChild(nextLi);

            paginationNav.appendChild(ul);
        }

        displayPage(1);
    }

    function handleSearch() {
        if (!searchInput) return;
        const searchTerm = searchInput.value.toLowerCase().trim();
        
        filteredRows = rows.filter(row => {
            const roll = row.cells[1].textContent.toLowerCase(); // Roll column is index 1 after checkbox
            const name = row.cells[2].textContent.toLowerCase(); // Name column is index 2 after checkbox
            const match = roll.includes(searchTerm) || name.includes(searchTerm);
            return match;
        });
        
        setupPagination();
    }

    if (searchInput) {
        searchInput.addEventListener('keyup', handleSearch);
    }

    setupPagination();
});
</script>
</body>
</html>