<?php 
// Debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../db_connect.php'; 
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

$success_msg = ''; $error_msg = '';

// ---------------------------------------------------------
// 1. DELETE STUDENT LOGIC
// ---------------------------------------------------------
if (isset($_GET['delete_id'])) {
    try {
        // ON DELETE CASCADE in the DB will automatically remove related enrollments
        $del_stmt = $pdo->prepare("DELETE FROM students WHERE id = ?");
        $del_stmt->execute([$_GET['delete_id']]);
        $success_msg = "Student deleted successfully!";
    } catch (PDOException $e) {
        $error_msg = "Error deleting student: " . $e->getMessage();
    }
}

// ---------------------------------------------------------
// 2. ADD NEW STUDENT LOGIC (Updated for Enrollments Table)
// ---------------------------------------------------------
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_student'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $admission_id = trim($_POST['admission_id']);
    $course_id = $_POST['course_id']; // This will now go to enrollments
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    
    try {
        $pdo->beginTransaction();

        // 1. Insert into students table (course_id removed)
        $insert_student = $pdo->prepare("INSERT INTO students (admission_id, name, email, phone, password, status, created_at) VALUES (?, ?, ?, ?, ?, 'active', NOW())");
        $insert_student->execute([$admission_id, $name, $email, $phone, $password]);
        
        $new_student_id = $pdo->lastInsertId();

        // 2. Insert into enrollments table
        if (!empty($course_id)) {
            $insert_enrollment = $pdo->prepare("INSERT INTO enrollments (student_id, course_id, status) VALUES (?, ?, 'active')");
            $insert_enrollment->execute([$new_student_id, $course_id]);
        }

        $pdo->commit();
        $success_msg = "New student registered and enrolled successfully!";
    } catch (PDOException $e) {
        $pdo->rollBack();
        $error_msg = "Failed to add student. Email or Admission ID might already exist.";
    }
}

// ---------------------------------------------------------
// 3. FETCH ALL STUDENTS (Updated for Enrollments Table)
// ---------------------------------------------------------
$students = [];
try {
    // Using GROUP_CONCAT to show multiple courses if a student is enrolled in more than one
    $stmt = $pdo->query("
        SELECT 
            s.id, s.admission_id, s.name, s.email, s.phone, s.created_at, s.status, s.profile_photo, s.is_trial,
            COALESCE(GROUP_CONCAT(c.title SEPARATOR '<br>'), 'Unassigned') as course,
            (SELECT COUNT(*) FROM exam_result er WHERE er.student_id = s.id) * 10 as progress
        FROM students s 
        LEFT JOIN enrollments e ON s.id = e.student_id
        LEFT JOIN courses c ON e.course_id = c.id 
        GROUP BY s.id
        ORDER BY s.id DESC
    ");
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_msg = "Database Error: " . $e->getMessage();
}

// Fetch Courses for Dropdown
$courses = [];
try { 
    $courses = $pdo->query("SELECT id, title FROM courses WHERE status='active' ORDER BY title ASC")->fetchAll(PDO::FETCH_ASSOC); 
} catch (Exception $e) {}
?>

<style>
    /* Premium Theme Colors */
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }

    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding-bottom: 50px; font-family: 'Outfit', sans-serif; }
    .fade-up { animation: fadeInUp 0.4s ease-out forwards; }
    @keyframes fadeInUp { 0% { opacity: 0; transform: translateY(15px); } 100% { opacity: 1; transform: translateY(0); } }

    /* Header & Mobile Menu */
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 25px; border-left: 6px solid var(--theme-green); }
    #sidebarToggle { display: none; width: 45px; height: 45px; border-radius: 12px; background: #f1f5f9; border: 1px solid #e2e8f0; color: var(--theme-green); cursor: pointer; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; }
    #sidebarToggle:hover { background: var(--theme-green); color: #fff; }
    
    .btn-theme { background: var(--theme-green); color: #fff; border-radius: 12px; padding: 12px 24px; font-weight: 700; border: none; transition: 0.3s; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
    .btn-theme:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); box-shadow: 0 8px 15px rgba(6, 78, 59, 0.2); }

    /* Action Bar (Search & Filter) */
    .action-bar { background: #fff; padding: 20px; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.02); margin-bottom: 25px; border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px; }
    .search-box { position: relative; max-width: 400px; width: 100%; }
    .search-box input { padding: 12px 20px 12px 45px; border-radius: 50px; border: 2px solid #f1f5f9; background: #f8fafc; font-size: 14px; width: 100%; transition: 0.3s; font-weight: 500; }
    .search-box input:focus { border-color: var(--theme-green); background: #fff; outline: none; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); }
    .search-box i { position: absolute; left: 18px; top: 50%; transform: translateY(-50%); color: #94a3b8; }

    /* Desktop Table Styles */
    .desktop-table-card { background: #fff; border-radius: 20px; border: 1px solid #e2e8f0; box-shadow: 0 10px 40px rgba(0,0,0,0.02); overflow: hidden; border-top: 5px solid var(--theme-green); }
    .table thead th { background-color: #f1f5f9; color: #64748b; font-size: 11px; text-transform: uppercase; font-weight: 800; padding: 18px 20px; border: none; letter-spacing: 0.5px; }
    .table tbody tr:hover { background-color: #f8fafc; }
    .table td { padding: 15px 20px; vertical-align: middle; font-size: 14px; color: #334155; border-bottom: 1px solid #f1f5f9; }
    
    /* Avatars & Badges */
    .std-avatar { width: 45px; height: 45px; border-radius: 12px; background: rgba(6, 78, 59, 0.1); color: var(--theme-green); display: flex; align-items: center; justify-content: center; font-weight: 800; overflow: hidden; font-size: 16px; }
    
    .badge-status { padding: 6px 14px; border-radius: 8px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; }
    .status-active { background: #ecfdf5; color: #059669; border: 1px solid #d1fae5; }
    .status-inactive { background: #fef2f2; color: #ef4444; border: 1px solid #ffe4e6; }
    
    .trial-tag { background: #fffbeb; color: #d97706; font-size: 9px; padding: 3px 8px; border-radius: 6px; border: 1px solid #fef3c7; margin-left: 8px; vertical-align: middle; }
    .course-badge { background: rgba(212, 175, 55, 0.1); border: 1px solid rgba(212, 175, 55, 0.3); color: var(--theme-dark); font-size: 11px; padding: 5px 12px; border-radius: 8px; font-weight: 800; display: inline-block; margin-bottom: 4px; }

    /* Action Buttons */
    .act-btn { width: 34px; height: 34px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; transition: 0.3s; margin: 0 3px; text-decoration: none; cursor: pointer; border: none; }
    .act-view { background: #f1f5f9; color: var(--theme-green); }
    .act-view:hover { background: var(--theme-green); color: #fff; }
    .act-edit { background: rgba(212, 175, 55, 0.15); color: var(--theme-dark); }
    .act-edit:hover { background: var(--theme-gold); color: #fff; }
    .act-delete { background: #fef2f2; color: #ef4444; }
    .act-delete:hover { background: #ef4444; color: #fff; }

    /* Modal Styling */
    .modal-content { border-radius: 24px; border: none; box-shadow: 0 20px 50px rgba(0,0,0,0.1); }
    .modal-header { border-bottom: 1px solid #f1f5f9; padding: 20px 30px; }
    .modal-body { padding: 30px; }
    .form-control, .form-select { border-radius: 12px; border: 2px solid #f1f5f9; padding: 12px 15px; font-size: 14px; background: #f8fafc; transition: 0.3s; }
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); }

    /* 📱 Mobile Specific Styles (Card View) */
    .student-mobile-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; transition: 0.3s; }
    
    @media (max-width: 991.98px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { padding: 20px; flex-direction: column; align-items: flex-start !important; gap: 15px; }
        .dashboard-header .header-top { width: 100%; display: flex; justify-content: flex-start; align-items: center; gap: 15px; }
        .dashboard-header .btn-theme { width: 100%; }
        .header-title { font-size: 1.2rem; }
        .action-bar { flex-direction: column; align-items: stretch; padding: 15px; }
        .search-box { max-width: 100%; }
        .filter-box { max-width: 100% !important; }
    }
    @media (min-width: 992px) {
        #sidebarToggle { display: none !important; }
    }
</style>

<div class="main-content p-3 p-md-4">

    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="header-top">
            <button id="sidebarToggle" class="shadow-sm"><i class="fas fa-bars fs-5"></i></button>
            <div>
                <h4 class="mb-0 fw-bold text-dark header-title"><i class="fas fa-users me-2" style="color: var(--theme-green);"></i> Student Management</h4>
                <p class="text-muted fw-semibold mb-0 d-none d-md-block" style="font-size: 13px;">Overview of all registered students and trial accounts</p>
            </div>
        </div>
        <button class="btn-theme shadow-sm mt-3 mt-md-0" data-bs-toggle="modal" data-bs-target="#addStudentModal">
            <i class="fas fa-user-plus me-2"></i> Register Student
        </button>
    </div>

    <?php if($success_msg): ?> 
        <div class="alert alert-success d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #10b981 !important;">
            <i class="fas fa-check-circle me-3 fa-2x text-success"></i> 
            <div><strong class="d-block text-success">Success!</strong><span class="text-muted small"><?= $success_msg ?></span></div>
        </div>
    <?php endif; ?>
    
    <?php if($error_msg): ?> 
        <div class="alert alert-danger d-flex align-items-center mb-4 rounded-4 border-0 shadow-sm fade-up" style="border-left: 5px solid #ef4444 !important;">
            <i class="fas fa-exclamation-triangle me-3 fa-2x text-danger"></i> 
            <div><strong class="d-block text-danger">Error!</strong><span class="text-muted small"><?= $error_msg ?></span></div>
        </div>
    <?php endif; ?>

    <div class="action-bar fade-up" style="animation-delay: 0.1s;">
        <div class="search-box">
            <i class="fas fa-search"></i>
            <input type="text" id="studentSearch" placeholder="Search by name, email or ID...">
        </div>
        <div class="w-100 filter-box" style="max-width: 250px;">
            <select class="form-select border-2 shadow-sm fw-bold text-muted" style="border-radius: 50px;">
                <option selected>All Status</option>
                <option>Active Students</option>
                <option>Trial Users</option>
                <option>Inactive</option>
            </select>
        </div>
    </div>

    <div class="desktop-table-card d-none d-lg-block fade-up" style="animation-delay: 0.2s;">
        <div class="table-responsive">
            <table class="table align-middle mb-0 border-0">
                <thead>
                    <tr>
                        <th class="ps-4">Student & ID</th>
                        <th>Course Info</th>
                        <th>Progress</th>
                        <th>Status</th>
                        <th class="text-end pe-4">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(!empty($students)): foreach($students as $std): 
                        $prog = min(100, (int)$std['progress']);
                    ?>
                    <tr>
                        <td class="ps-4 py-3">
                            <div class="d-flex align-items-center">
                                <div class="std-avatar shadow-sm">
                                    <?php if($std['profile_photo']): ?>
                                        <img src="../<?= $std['profile_photo'] ?>" style="width:100%; height:100%; object-fit:cover;">
                                    <?php else: ?>
                                        <?= strtoupper(substr($std['name'], 0, 1)) ?>
                                    <?php endif; ?>
                                </div>
                                <div class="ms-3">
                                    <div class="fw-bold" style="color: var(--theme-dark); font-size: 15px;"><?= htmlspecialchars($std['name']) ?> 
                                        <?php if($std['is_trial']): ?><span class="trial-tag">Trial</span><?php endif; ?>
                                    </div>
                                    <div class="text-muted fw-bold mt-1" style="font-size: 12px;"><i class="fas fa-id-badge me-1"></i> #<?= htmlspecialchars($std['admission_id'] ?? $std['id']) ?> &bull; <?= htmlspecialchars($std['email']) ?></div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <?php 
                            if ($std['course'] !== 'Unassigned') {
                                $courses_arr = explode('<br>', $std['course']);
                                foreach($courses_arr as $c_name) {
                                    echo "<span class='course-badge shadow-sm'><i class='fas fa-book-open me-1'></i> " . htmlspecialchars($c_name) . "</span><br>";
                                }
                            } else {
                                echo "<span class='badge bg-light text-danger border px-3 py-2 rounded-pill'>Unassigned</span>";
                            }
                            ?>
                        </td>
                        <td>
                            <div class="d-flex align-items-center gap-2">
                                <div class="progress shadow-sm" style="height: 8px; width: 100px; border-radius: 50px; background: #e2e8f0;">
                                    <div class="progress-bar" style="width: <?= $prog ?>%; background: var(--theme-green); border-radius: 50px;"></div>
                                </div>
                                <span class="small fw-bold text-dark"><?= $prog ?>%</span>
                            </div>
                        </td>
                        <td>
                            <span class="badge-status <?= $std['status'] == 'active' ? 'status-active' : 'status-inactive' ?>">
                                <?= strtoupper($std['status']) ?>
                            </span>
                        </td>
                        <td class="text-end pe-4">
                            <a href="view_student.php?id=<?= $std['id'] ?>" class="act-btn act-view shadow-sm" title="View"><i class="fas fa-eye"></i></a>
                            <a href="edit_student.php?id=<?= $std['id'] ?>" class="act-btn act-edit shadow-sm" title="Edit"><i class="fas fa-pen"></i></a>
                            <a href="?delete_id=<?= $std['id'] ?>" class="act-btn act-delete shadow-sm" onclick="return confirm('Delete this student permanently?');" title="Delete"><i class="fas fa-trash-alt"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; else: ?>
                    <tr><td colspan="5" class="text-center py-5 text-muted fw-bold"><i class="fas fa-users-slash fa-2x mb-3 d-block opacity-25"></i> No students found!</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="d-block d-lg-none fade-up" style="animation-delay: 0.2s;">
        <div class="row g-3">
            <?php if(!empty($students)): foreach($students as $std): 
                $prog = min(100, (int)$std['progress']);
            ?>
            <div class="col-12 mobile-student-item">
                <div class="student-mobile-card p-3">
                    <div class="d-flex align-items-center gap-3 mb-3 pb-3 border-bottom">
                        <div class="std-avatar shadow-sm" style="width: 50px; height: 50px; font-size: 20px;">
                            <?php if($std['profile_photo']): ?>
                                <img src="../<?= $std['profile_photo'] ?>" style="width:100%; height:100%; object-fit:cover;">
                            <?php else: ?>
                                <?= strtoupper(substr($std['name'], 0, 1)) ?>
                            <?php endif; ?>
                        </div>
                        <div class="w-100">
                            <div class="d-flex justify-content-between align-items-start">
                                <h6 class="fw-bold text-dark mb-1" style="font-size: 15px;">
                                    <?= htmlspecialchars($std['name']) ?>
                                    <?php if($std['is_trial']): ?><span class="trial-tag">Trial</span><?php endif; ?>
                                </h6>
                                <span class="badge-status <?= $std['status'] == 'active' ? 'status-active' : 'status-inactive' ?>" style="padding: 4px 8px; font-size: 9px;">
                                    <?= strtoupper($std['status']) ?>
                                </span>
                            </div>
                            <small class="text-muted fw-bold" style="font-size: 11px;"><i class="fas fa-id-badge me-1"></i> #<?= htmlspecialchars($std['admission_id'] ?? $std['id']) ?></small>
                        </div>
                    </div>
                    
                    <div class="mb-3 px-2 bg-light p-3 rounded-3 border">
                        <div class="mb-3 d-flex align-items-center">
                            <i class="fas fa-envelope text-muted me-2" style="width: 15px;"></i>
                            <span class="text-dark fw-bold" style="font-size: 12px;"><?= htmlspecialchars($std['email']) ?></span>
                        </div>
                        <div class="mb-3 d-flex align-items-center">
                            <i class="fas fa-phone-alt text-muted me-2" style="width: 15px;"></i>
                            <span class="text-muted fw-bold" style="font-size: 12px;"><?= htmlspecialchars($std['phone']) ?></span>
                        </div>
                        <div class="mb-3">
                            <small class="text-muted text-uppercase fw-bold d-block mb-2" style="font-size: 10px;">Enrolled Courses</small>
                            <?php 
                            if ($std['course'] !== 'Unassigned') {
                                $courses_arr = explode('<br>', $std['course']);
                                foreach($courses_arr as $c_name) {
                                    echo "<span class='course-badge bg-white shadow-sm w-100 text-start'><i class='fas fa-book-open me-2 text-primary'></i> " . htmlspecialchars($c_name) . "</span>";
                                }
                            } else {
                                echo "<span class='badge bg-white text-danger border w-100 text-start py-2'>Unassigned</span>";
                            }
                            ?>
                        </div>
                        <div>
                            <div class="d-flex justify-content-between mb-1">
                                <small class="text-muted text-uppercase fw-bold" style="font-size: 10px;">Progress</small>
                                <small class="text-success fw-bold" style="font-size: 10px;"><?= $prog ?>%</small>
                            </div>
                            <div class="progress" style="height: 6px; border-radius: 50px; background: #e2e8f0;">
                                <div class="progress-bar" style="width: <?= $prog ?>%; background: var(--theme-green); border-radius: 50px;"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <a href="view_student.php?id=<?= $std['id'] ?>" class="btn btn-light border flex-grow-1 fw-bold text-primary" style="font-size: 12px; padding: 10px;"><i class="fas fa-eye me-1"></i> View</a>
                        <a href="edit_student.php?id=<?= $std['id'] ?>" class="btn btn-light border flex-grow-1 fw-bold text-warning" style="font-size: 12px; padding: 10px;"><i class="fas fa-pen me-1"></i> Edit</a>
                        <a href="?delete_id=<?= $std['id'] ?>" class="btn btn-light border flex-grow-1 fw-bold text-danger" style="font-size: 12px; padding: 10px;" onclick="return confirm('Delete student?');"><i class="fas fa-trash-alt me-1"></i> Delete</a>
                    </div>
                </div>
            </div>
            <?php endforeach; else: ?>
                <div class="col-12 text-center py-5 bg-white rounded-4 border shadow-sm">
                    <i class="fas fa-users-slash fa-3x text-muted opacity-25 mb-3 d-block"></i>
                    <h6 class="fw-bold text-muted">No students found!</h6>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

<div class="modal fade" id="addStudentModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-dark"><i class="fas fa-user-plus me-2" style="color: var(--theme-green);"></i> Register New Student</h5>
                <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form action="" method="POST">
                    <div class="row g-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Admission ID <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-id-badge"></i></span>
                                <input type="text" name="admission_id" class="form-control border-start-0 ps-0 fw-bold text-primary" placeholder="E.g. ADM-1020" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Full Name <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-user"></i></span>
                                <input type="text" name="name" class="form-control border-start-0 ps-0" placeholder="Full name of student" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Email Address <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-envelope"></i></span>
                                <input type="email" name="email" class="form-control border-start-0 ps-0" placeholder="email@domain.com" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Phone Number <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-phone-alt"></i></span>
                                <input type="text" name="phone" class="form-control border-start-0 ps-0" placeholder="+8801..." required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Assign Course</label>
                            <div class="input-group">
                                <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-book"></i></span>
                                <select name="course_id" class="form-select border-start-0 ps-0 fw-bold" style="color: var(--theme-green);">
                                    <option value="">-- Save without course --</option>
                                    <?php foreach($courses as $c): ?>
                                        <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['title']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Set Login Password <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text border-2 border-end-0 bg-light text-muted"><i class="fas fa-lock"></i></span>
                                <input type="text" name="password" class="form-control border-start-0 ps-0 fw-bold" value="<?= substr(str_shuffle("0123456789"), 0, 6) ?>" required>
                            </div>
                            <small class="text-muted d-block mt-1" style="font-size: 11px;">Auto-generated 6-digit PIN.</small>
                        </div>
                    </div>
                    <div class="text-end mt-5 border-top pt-4">
                        <button type="submit" name="add_student" class="btn btn-theme px-5 py-3 w-100-mobile shadow-sm">
                            <i class="fas fa-save me-2"></i> Confirm Registration
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Sidebar Toggle for Mobile
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar') || document.getElementById('sidebarMenu');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }

        // Advanced Live Search Logic (Works for both Table & Mobile Cards)
        const searchInput = document.getElementById('studentSearch');
        if(searchInput) {
            searchInput.addEventListener('keyup', function() {
                let filter = this.value.toLowerCase();
                
                // Filter Desktop Table Rows
                let rows = document.querySelectorAll('tbody tr');
                rows.forEach(row => {
                    let text = row.innerText.toLowerCase();
                    row.style.display = text.includes(filter) ? '' : 'none';
                });
                
                // Filter Mobile Cards
                let mobileCards = document.querySelectorAll('.mobile-student-item');
                mobileCards.forEach(card => {
                    let text = card.innerText.toLowerCase();
                    card.style.display = text.includes(filter) ? '' : 'none';
                });
            });
        }
    });
</script>

<?php include 'includes/footer.php'; ?>