<?php
/**
 * Teacher Dashboard - Tab Pengurusan Pelajar (Refactored)
 * Bahagian I: Rekod Pelajar Aktif
 * Bahagian II: Permohonan Baru
 */
?>
<div id="student-management" class="card border-0 shadow-sm" style="border-radius: 15px; overflow: hidden;">
    <div class="card-header bg-white py-4 px-4 border-0">
        <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
            <div>
                <h4 class="fw-bold mb-1" style="color: var(--primary-color);">👨‍🎓 Pengurusan Pelajar</h4>
                <p class="text-muted small mb-0">Urus maklumat pelajar, edit profil, dan lihat status pendaftaran.</p>
            </div>
            <div class="d-flex align-items-center gap-2">
                <span class="badge bg-secondary bg-opacity-10 text-dark p-2 px-3 rounded-pill"
                    style="font-size: 0.85rem;">
                    📚 Subjek: <?php echo isset($teacherSubjects) ? count($teacherSubjects) : 0; ?>
                </span>
                <button class="btn btn-secondary btn-sm rounded-pill px-3" id="btn-refresh-student-management"
                    onclick="loadStudentManagementDataV2()">
                    🔄 Refresh
                </button>
                <button class="btn btn-primary btn-sm rounded-pill px-3 d-flex align-items-center"
                    onclick="showAddStudentModal()">
                    <i class="fas fa-plus-circle me-1"></i> Tambah Pelajar Manual
                </button>
            </div>
        </div>
    </div>
    <div class="card-body p-0">
        <!-- Main Tabs Navigation -->
        <div class="d-flex border-bottom" style="overflow-x: auto;">
            <button class="btn btn-link text-decoration-none py-3 px-4 active-tab-btn" id="tab-btn-active"
                onclick="switchMainTabV2('active')"
                style="color: #4b5563; border-bottom: 2px solid transparent; font-weight: 500; white-space: nowrap;">
                📋 I. Rekod Pelajar Aktif
                <span class="badge bg-secondary bg-opacity-10 text-dark rounded-pill ms-2"
                    id="badge-active-count">0</span>
            </button>
            <button class="btn btn-link text-decoration-none py-3 px-4" id="tab-btn-new"
                onclick="switchMainTabV2('new')"
                style="color: #6b7280; border-bottom: 2px solid transparent; font-weight: 500; white-space: nowrap;">
                📝 II. Permohonan Baru
                <span class="badge bg-warning text-dark rounded-pill ms-2" id="badge-new-count">0</span>
            </button>
            <button class="btn btn-link text-decoration-none py-3 px-4" id="tab-btn-my" onclick="switchMainTabV2('my')"
                style="color: #6b7280; border-bottom: 2px solid transparent; font-weight: 500; white-space: nowrap;">
                👨‍🏫 III. Senarai Pelajar Saya
                <span class="badge bg-primary bg-opacity-10 text-primary rounded-pill ms-2" id="badge-my-count">0</span>
            </button>
        </div>

        <!-- Content Area -->
        <div class="p-4">

            <!-- INFO PERANAN (GUIDE) -->
            <div class="alert shadow-sm border-0 mb-4"
                style="background: linear-gradient(to right, #f8f9ff, #ffffff); border-left: 4px solid #2563eb !important;">
                <div class="d-flex align-items-start">
                    <div class="me-3 p-2 bg-primary bg-opacity-10 rounded-circle text-primary">
                        <i class="fas fa-info-circle fs-5"></i>
                    </div>
                    <div class="flex-grow-1">
                        <h6 class="fw-bold mb-2 text-dark">Panduan Peranan Tutor</h6>
                        <div class="row g-3">
                            <div class="col-md-6 border-end">
                                <div class="d-flex align-items-center mb-1">
                                    <span class="badge bg-success bg-opacity-10 text-success rounded-pill me-2">Mentor
                                        Utama</span>
                                    <span class="small text-muted fw-bold">Ketua Penjaga</span>
                                </div>
                                <p class="small text-muted mb-0">Hanya Mentor Utama boleh <b>Mengemaskini (Edit)</b>,
                                    <b>Memadam</b>, dan menjana <b>PDF Profil</b> pelajar. Bertanggungjawab penuh ke
                                    atas rekod pelajar.
                                </p>
                            </div>
                            <div class="col-md-6 ps-md-4">
                                <div class="d-flex align-items-center mb-1">
                                    <span class="badge bg-warning bg-opacity-10 text-warning rounded-pill me-2">Tutor
                                        Subjek</span>
                                    <span class="small text-muted fw-bold">Tenaga Pengajar</span>
                                </div>
                                <p class="small text-muted mb-0">Tutor yang mengajar subjek tertentu. Mempunyai hak
                                    untuk <b>Melihat Profil</b> sahaja tanpa hak pentadbiran (Edit/Delete).</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- BAHAGIAN I: REKOD PELAJAR AKTIF (GLOBAL) -->
            <div id="view-active-records">
                <div class="row g-3 mb-4 align-items-center">
                    <div class="col-12 col-md-auto">
                        <div class="input-group shadow-sm rounded-pill overflow-hidden border"
                            style="max-width: 320px;">
                            <span class="input-group-text bg-white border-0 ps-3">
                                <i class="fas fa-search text-muted"></i>
                            </span>
                            <input type="text" class="form-control border-0 ps-1 py-2" id="search-active"
                                placeholder="Cari semua rekod..." onkeyup="filterActiveRecords()"
                                style="box-shadow: none; font-size: 0.9rem;">
                        </div>
                    </div>
                    <div class="col-12 col-md-auto">
                        <select class="form-select shadow-sm rounded-pill border py-2 px-3 fw-medium"
                            id="filter-subject-active" onchange="filterActiveRecords()"
                            style="width: auto; min-width: 180px; font-size: 0.9rem; border-color: #dee2e6;">
                            <option value="">📚 Semua Subjek</option>
                            <!-- Will be populated by JS -->
                        </select>
                    </div>
                    <div class="col-12 col-md text-md-end">
                        <span class="text-muted small">
                            <i class="fas fa-filter me-1"></i> Tapis mengikut subjek atau nama
                        </span>
                    </div>
                </div>

                <div class="table-responsive rounded border">
                    <table class="table table-hover align-middle mb-0" id="table-active">
                        <thead class="bg-light">
                            <tr>
                                <th class="ps-4">Nama Pelajar</th>
                                <th>Maklumat Hubungi</th>
                                <th>Pendidikan</th>
                                <th>Subjek</th>
                                <th>Status</th>
                                <th>Tindakan</th>
                            </tr>
                        </thead>
                        <tbody id="list-active-records">
                            <tr>
                                <td colspan="6" class="text-center py-5 text-muted">Memuatkan data...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- BAHAGIAN II: PERMOHONAN BARU -->
            <div id="view-new-applications" style="display: none;">
                <div class="alert alert-info border-0 bg-info bg-opacity-10 d-flex align-items-center mb-4">
                    <div class="me-3 fs-4">💡</div>
                    <div>
                        <h6 class="fw-bold mb-1">Permohonan Menunggu Kata Laluan</h6>
                        <p class="mb-0 small">Pelajar ini telah mendaftar tetapi belum mempunyai kata laluan. Sila
                            tetapkan kata laluan. Anda akan automatik menjadi <b>Mentor</b> kepada pelajar yang
                            diluluskan.</p>
                    </div>
                </div>

                <div class="row g-3 mb-4 align-items-center">
                    <div class="col-12 col-md-auto">
                        <div class="input-group shadow-sm rounded-pill overflow-hidden border"
                            style="max-width: 320px;">
                            <span class="input-group-text bg-white border-0 ps-3">
                                <i class="fas fa-search text-muted"></i>
                            </span>
                            <input type="text" class="form-control border-0 ps-1 py-2" id="search-new"
                                placeholder="Cari permohonan..." onkeyup="filterNewApplications()"
                                style="box-shadow: none; font-size: 0.9rem;">
                        </div>
                    </div>
                    <div class="col-12 col-md text-md-end d-flex justify-content-md-end gap-2 flex-wrap">
                        <button class="btn btn-outline-danger btn-sm rounded-pill px-3"
                            onclick="generateAllStudentsPDFV2('active')">
                            📥 PDF Senarai (Global)
                        </button>
                    </div>
                </div>

                <div class="table-responsive rounded border">
                    <table class="table table-hover align-middle mb-0" id="table-new">
                        <thead class="bg-light">
                            <tr>
                                <th class="ps-4">Nama Pelajar</th>
                                <th>Tarikh Daftar</th>
                                <th>Tahap</th>
                                <th>Subjek Diminta</th>
                                <th class="text-end pe-4">Tindakan</th>
                            </tr>
                        </thead>
                        <tbody id="list-new-applications">
                            <tr>
                                <td colspan="5" class="text-center py-5 text-muted">Memuatkan data...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- BAHAGIAN III: SENARAI PELAJAR SAYA -->
            <div id="view-my-students" style="display: none;">
                <div class="row g-3 mb-4 align-items-center">
                    <div class="col-12 col-md-auto">
                        <div class="input-group shadow-sm rounded-pill overflow-hidden border"
                            style="max-width: 320px;">
                            <span class="input-group-text bg-white border-0 ps-3">
                                <i class="fas fa-search text-muted"></i>
                            </span>
                            <input type="text" class="form-control border-0 ps-1 py-2" id="search-my"
                                placeholder="Cari pelajar saya..." onkeyup="filterMyStudents()"
                                style="box-shadow: none; font-size: 0.9rem;">
                        </div>
                    </div>
                    <div class="col-12 col-md-auto">
                        <select class="form-select shadow-sm rounded-pill border py-2 px-3 fw-medium"
                            id="filter-subject-my" onchange="filterMyStudents()"
                            style="width: auto; min-width: 180px; font-size: 0.9rem; border-color: #dee2e6;">
                            <option value="">📚 Semua Subjek</option>
                            <!-- Will be populated by JS -->
                        </select>
                    </div>
                    <div class="col-12 col-md text-md-end">
                        <div class="dropdown">
                            <button class="btn btn-outline-primary btn-sm rounded-pill px-3 dropdown-toggle shadow-sm"
                                type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="fas fa-print me-1"></i> Laporan Mentor
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end shadow border-0" style="border-radius: 12px;">
                                <li><button class="dropdown-item py-2" onclick="generateAllStudentsPDF('my')">
                                        <i class="fas fa-file-pdf me-2 text-danger"></i> Senarai Pelajar Saya
                                    </button></li>
                            </ul>
                        </div>
                    </div>
                </div>

                <div class="table-responsive rounded border">
                    <table class="table table-hover align-middle mb-0" id="table-my">
                        <thead class="bg-light">
                            <tr>
                                <th class="ps-4">Nama Pelajar</th>
                                <th>Maklumat Hubungi</th>
                                <th>Pendidikan</th>
                                <th>Subjek</th>
                                <th>Status</th>
                                <th>Tindakan</th>
                            </tr>
                        </thead>
                        <tbody id="list-my-students">
                            <tr>
                                <td colspan="6" class="text-center py-5 text-muted">Memuatkan data...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>
</div>

<!-- TEMPLATES FOR PDF GENERATION (HIDDEN) -->
<div id="pdf-templates" style="display: none;">
    <!-- 1. All Students List Template -->
    <div id="template-all-students" style="padding: 20px; font-family: sans-serif;">
        <div style="text-align: center; margin-bottom: 20px; border-bottom: 2px solid #333; padding-bottom: 15px;">
            <h2 style="margin: 0; color: #2563eb;" id="pdf-list-title">Rekod Pelajar Aktif</h2>
            <p style="margin: 5px 0 0; color: #666;">TutorKita System</p>
            <p style="margin: 5px 0 0; font-size: 12px; color: #888;">Dijana pada: <span class="pdf-date"></span></p>
        </div>
        <table style="width: 100%; border-collapse: collapse; font-size: 12px;">
            <thead>
                <tr style="background-color: #f3f4f6;">
                    <th style="border: 1px solid #ddd; padding: 10px; text-align: left;">Nama Pelajar</th>
                    <th style="border: 1px solid #ddd; padding: 10px; text-align: left;">Umur</th>
                    <th style="border: 1px solid #ddd; padding: 10px; text-align: left;">No. Telefon / Penjaga</th>
                    <th style="border: 1px solid #ddd; padding: 10px; text-align: left;">Pendidikan</th>
                    <th style="border: 1px solid #ddd; padding: 10px; text-align: left;">Subjek</th>
                </tr>
            </thead>
            <tbody id="template-all-students-body">
                <!-- Content will be injected here -->
            </tbody>
        </table>
        <div style="margin-top: 20px; text-align: right; font-size: 10px; color: #aaa;">
            <p>Generated by TutorKita</p>
        </div>
    </div>

    <!-- 2. Individual Student Profile Template -->
    <div id="template-individual-student"
        style="padding: 30px; font-family: sans-serif; max-width: 800px; margin: 0 auto;">
        <div
            style="border: 1px solid #eee; border-radius: 15px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05);">
            <!-- Header -->
            <div
                style="background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: white; padding: 30px; text-align: center;">
                <div style="font-size: 40px; margin-bottom: 10px;" id="pdf-profile-emoji">👨‍🎓</div>
                <h1 style="margin: 0; font-size: 24px;" id="pdf-profile-name">Nama Pelajar</h1>
                <p style="margin: 5px 0 0; opacity: 0.8;" id="pdf-profile-id">ID: 001</p>
            </div>

            <!-- Body -->
            <div style="padding: 30px; background: white;">
                <h3 style="color: #333; border-bottom: 2px solid #f3f4f6; padding-bottom: 10px; margin-top: 0;">Maklumat
                    Peribadi</h3>
                <table style="width: 100%; margin-bottom: 20px;">
                    <tr>
                        <td style="padding: 8px 0; color: #666; width: 150px;"><strong>Umur:</strong></td>
                        <td style="padding: 8px 0; color: #333;" id="pdf-profile-age">-</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; color: #666;"><strong>No. Telefon:</strong></td>
                        <td style="padding: 8px 0; color: #333;" id="pdf-profile-phone">-</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; color: #666;"><strong>Nama Penjaga:</strong></td>
                        <td style="padding: 8px 0; color: #333;" id="pdf-profile-guardian">-</td>
                    </tr>
                </table>

                <h3 style="color: #333; border-bottom: 2px solid #f3f4f6; padding-bottom: 10px; margin-top: 20px;">
                    Pendidikan</h3>
                <table style="width: 100%; margin-bottom: 20px;">
                    <tr>
                        <td style="padding: 8px 0; color: #666; width: 150px;"><strong>Tahap:</strong></td>
                        <td style="padding: 8px 0; color: #333;" id="pdf-profile-education">-</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px 0; color: #666;"><strong>Tahun/Tingkatan:</strong></td>
                        <td style="padding: 8px 0; color: #333;" id="pdf-profile-grade">-</td>
                    </tr>
                </table>

                <h3 style="color: #333; border-bottom: 2px solid #f3f4f6; padding-bottom: 10px; margin-top: 20px;">
                    Subjek Diambil</h3>
                <div id="pdf-profile-subjects" style="padding: 10px 0;">
                    <!-- Badges -->
                </div>
            </div>

            <!-- Footer -->
            <div
                style="background: #f9fafb; padding: 15px; text-align: center; font-size: 12px; color: #666; border-top: 1px solid #eee;">
                Rekod Pelajar TutorKita &bull; Dijana pada <span class="pdf-date"></span>
            </div>
        </div>
    </div>
</div>

<!-- Include html2pdf library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

<!-- Modal Approval (Set Password) -->
<!-- Custom Modal Style (Matches the rest of the app) -->
<div class="modal-overlay" id="studentApprovalModal" style="display: none !important;">
    <div class="modal" style="max-width: 750px;">
        <div class="modal-header bg-success text-white">
            <h3 class="modal-title" style="color: white; margin: 0;">✅ Luluskan & Aktifkan Pelajar</h3>
            <button type="button" class="modal-close" onclick="closeModal('studentApprovalModal')"
                style="color: white; border: none; background: transparent; font-size: 24px;">×</button>
        </div>
        <div class="modal-body p-4" style="overflow-y: auto; max-height: 75vh;">
            <div class="alert alert-warning border-0 bg-warning bg-opacity-10 py-2 px-3 mb-3"
                style="background-color: #fff3cd; border-radius: 8px; padding: 10px; margin-bottom: 15px;">
                <small>⚠️ Pelajar ini memerlukan kata laluan untuk log masuk.</small>
            </div>

            <form id="approvalForm" onsubmit="handleApproveV2(event)">
                <input type="hidden" id="approvalStudentId">
                <div class="mb-3 text-center" style="margin-bottom: 20px;">
                    <h4 class="mb-1" id="approvalStudentName" style="margin-bottom: 5px;">Nama Pelajar</h4>
                    <p class="text-muted small mb-0" id="approvalStudentDetails">Darjah/Tingkatan</p>
                </div>

                <div class="card bg-light border-0 p-3 mb-3"
                    style="background-color: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" id="useDefaultPassword" checked
                            onchange="togglePasswordInputV2()">
                        <label class="form-check-label fw-bold" for="useDefaultPassword">
                            Guna Kata Laluan Default (pelajar)
                        </label>
                    </div>
                    <div class="text-muted small mt-1">Kata laluan: <code class="fw-bold text-dark">pelajar</code></div>
                </div>

                <div class="mb-3" id="customPasswordGroup" style="display: none; margin-bottom: 15px;">
                    <label class="form-label" style="display: block; margin-bottom: 5px;">Tetapkan Kata Laluan
                        Baru</label>
                    <input type="text" class="form-control" id="customPassword" placeholder="Masukkan kata laluan"
                        style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
                </div>

                <div class="d-grid" style="margin-top: 20px;">
                    <button type="submit" class="btn btn-success"
                        style="width: 100%; padding: 12px; background-color: #28a745; color: white; border: none; border-radius: 8px; font-weight: bold; cursor: pointer;">
                        Sah & Aktifkan Akaun
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // CURRENT_TEACHER_ID is defined globally in index-v2.php

    function switchMainTabV2(tab) {
        // Toggle Views
        document.getElementById('view-active-records').style.display = tab === 'active' ? 'block' : 'none';
        document.getElementById('view-new-applications').style.display = tab === 'new' ? 'block' : 'none';
        document.getElementById('view-my-students').style.display = tab === 'my' ? 'block' : 'none';

        // Toggle Buttons
        const activeBtn = document.getElementById('tab-btn-active');
        const newBtn = document.getElementById('tab-btn-new');
        const myBtn = document.getElementById('tab-btn-my');

        // Reset styles active
        [activeBtn, newBtn, myBtn].forEach(btn => {
            btn.style.color = '#6b7280';
            btn.style.borderBottomColor = 'transparent';
            btn.classList.remove('active-tab-btn');
        });

        // Set Active Style
        const selectedBtn = tab === 'active' ? activeBtn : (tab === 'new' ? newBtn : myBtn);
        selectedBtn.style.color = '#2563eb'; // Primary blue
        selectedBtn.style.borderBottomColor = '#2563eb';
        selectedBtn.classList.add('active-tab-btn');
    }

    function loadStudentManagementDataV2() {
        console.log('loadStudentManagementDataV2 started');
        const refreshBtn = document.getElementById('btn-refresh-student-management');
        if (refreshBtn) {
            refreshBtn.innerHTML = '🔄 Loading...';
            refreshBtn.disabled = true;
        }

        const activeBody = document.getElementById('list-active-records');
        if (activeBody) {
            activeBody.innerHTML = `<tr><td colspan="6" class="text-center py-5">
                <div class="spinner-border spinner-border-sm text-primary me-2"></div> Memuatkan data dari pelayan...
            </td></tr>`;
        }

        fetch('../api.php?action=get_student_management_data&t=' + new Date().getTime())
            .then(response => {
                if (!response.ok) throw new Error('HTTP ' + response.status);
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    activeRecords = result.active_records || [];
                    newApplications = result.new_applications || [];
                    myStudents = result.my_students || [];

                    if (activeRecords.length === 0 && newApplications.length === 0 && myStudents.length === 0) {
                        if (activeBody) activeBody.innerHTML = `<tr><td colspan="6" class="text-center py-5 text-muted">Akses Berjaya: Tiada rekod dijumpai.</td></tr>`;
                    }

                    populateSubjectFilter(activeRecords, 'filter-subject-active');
                    populateSubjectFilter(myStudents, 'filter-subject-my');

                    renderActiveRecords();
                    renderNewApplications();
                    renderMyStudents();

                    document.getElementById('badge-active-count').textContent = activeRecords.length;
                    document.getElementById('badge-new-count').textContent = newApplications.length;
                    document.getElementById('badge-my-count').textContent = myStudents.length;

                    // SYNC DASHBOARD CARDS: Ensure counts match this list exactly
                    const dashMyCount = document.getElementById('dashboardMyStudentCount');
                    const dashGlobalCount = document.getElementById('studentCountValue');

                    if (dashMyCount) {
                        const currentVal = parseInt(dashMyCount.textContent) || 0;
                        if (typeof animateValue === 'function') {
                            animateValue('dashboardMyStudentCount', currentVal, myStudents.length, 1000);
                        } else {
                            dashMyCount.textContent = myStudents.length;
                        }
                    }

                    if (dashGlobalCount) {
                        const currentGlobal = parseInt(dashGlobalCount.textContent) || 0;
                        if (typeof animateValue === 'function') {
                            animateValue('studentCountValue', currentGlobal, activeRecords.length, 1000);
                        } else {
                            dashGlobalCount.textContent = activeRecords.length;
                        }
                    }

                } else {
                    if (activeBody) activeBody.innerHTML = `<tr><td colspan="6" class="text-center py-5 text-danger">Ralat API: ${result.message}</td></tr>`;
                }
            })
            .catch(err => {
                console.error('Fetch Error:', err);
                if (activeBody) {
                    activeBody.innerHTML = `<tr><td colspan="6" class="text-center py-5 text-danger">
                        <div class="mb-2">❌ Ralat Sambungan</div>
                        <div class="small">${err.message}</div>
                        <button class="btn btn-sm btn-outline-danger mt-3" onclick="loadStudentManagementDataV2()">Cuba Lagi</button>
                    </td></tr>`;
                }
            })
            .finally(() => {
                if (refreshBtn) {
                    refreshBtn.innerHTML = '🔄 Refresh';
                    refreshBtn.disabled = false;
                }
            });
    }

    // Initialize immediately if script is loaded after DOM
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        setTimeout(initStudentManagement, 100);
    } else {
        document.addEventListener('DOMContentLoaded', initStudentManagement);
    }

    function initStudentManagement() {
        if (document.getElementById('student-management')) {
            loadStudentManagementDataV2();
            switchMainTabV2('active');
        }
    }

    function renderActiveRecords() {
        renderStudentTable(activeRecords, 'search-active', 'filter-subject-active', 'list-active-records', false);
    }

    function assignStudentV2(id) {
        Swal.fire({
            title: 'Sahkan Ambil Pelajar',
            text: 'Adakah anda pasti mahu mengambil pelajar ini di bawah seliaan anda?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#2563eb',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Ya, Ambil',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                const formData = new FormData();
                formData.append('action', 'assign_student_mentor');
                formData.append('student_id', id);

                fetch('../api.php', {
                    method: 'POST',
                    body: formData
                })
                    .then(res => res.json())
                    .then(res => {
                        if (res.success) {
                            Swal.fire({
                                title: 'Berjaya',
                                text: res.message,
                                icon: 'success'
                            });
                            loadStudentManagementDataV2();
                            switchMainTabV2('my');
                        } else {
                            Swal.fire('Ralat', res.message || 'Ralat berlaku', 'error');
                        }
                    })
                    .catch(e => {
                        console.error(e);
                        Swal.fire('Ralat', 'Ralat sambungan', 'error');
                    });
            }
        });
    }

    function resignMentorV2(id) {
        Swal.fire({
            title: 'Tolak Mentor',
            text: 'Adakah anda pasti mahu melepaskan tanggungjawab sebagai mentor utama untuk pelajar ini?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Ya, Lepaskan',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                const formData = new FormData();
                formData.append('action', 'resign_mentor');
                formData.append('student_id', id);

                fetch('../api.php', {
                    method: 'POST',
                    body: formData
                })
                    .then(res => res.json())
                    .then(res => {
                        if (res.success) {
                            Swal.fire({
                                title: 'Berjaya',
                                text: res.message,
                                icon: 'success'
                            });
                            loadStudentManagementDataV2();
                        } else {
                            Swal.fire('Ralat', res.message || 'Ralat berlaku', 'error');
                        }
                    })
                    .catch(e => {
                        console.error(e);
                        Swal.fire('Ralat', 'Ralat sambungan', 'error');
                    });
            }
        });
    }

    function renderMyStudents() {
        renderStudentTable(myStudents, 'search-my', 'filter-subject-my', 'list-my-students', true);
    }

    function renderStudentTable(data, searchId, filterId, tbodyId, isMyStudents) {
        const term = document.getElementById(searchId).value.toLowerCase();
        const subjectFilter = document.getElementById(filterId);
        const filterVal = subjectFilter ? subjectFilter.value : '';
        const tbody = document.getElementById(tbodyId);

        const filtered = data.filter(s => {
            const matchesTerm = s.full_name.toLowerCase().includes(term) || (s.phone && s.phone.includes(term));

            let matchesSubject = true;
            if (filterVal) {
                try {
                    const subs = JSON.parse(s.required_subjects || '[]');
                    matchesSubject = subs.includes(filterVal);
                } catch (e) { matchesSubject = false; }
            }

            return matchesTerm && matchesSubject;
        });

        if (filtered.length === 0) {
            const msg = isMyStudents ? "Tiada pelajar di bawah bimbingan anda." : "Tiada rekod pelajar aktif dijumpai.";
            tbody.innerHTML = `<tr><td colspan="6" class="text-center py-5 text-muted">${msg}</td></tr>`;
            return;
        }

        let html = '';
        filtered.forEach(s => {
            // Parse subjects
            let subjects = [];
            try {
                subjects = JSON.parse(s.required_subjects || '[]');
            } catch (e) { }

            const subjectBadges = subjects.map(sub => `<span class="badge bg-light text-dark border me-1 mb-1">${sub}</span>`).join('');

            // ROLE BADGE LOGIC
            let roleBadge = '';
            const isPrimaryMentor = (s.enrolled_by == CURRENT_TEACHER_ID);

            if (isMyStudents) {
                if (isPrimaryMentor) {
                    roleBadge = `<span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 rounded-pill mb-1">Mentor Utama</span>`;
                } else {
                    roleBadge = `<span class="badge bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25 rounded-pill mb-1">Tutor Subjek</span>`;
                }
            } else {
                // For Global View: Only show "Belum ada mentor" if applicable
                if (!s.enrolled_by) {
                    roleBadge = `<span class="badge bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25 rounded-pill mb-1">⚠️ Belum ada mentor utama</span>`;
                }
            }

            // ACTION BUTTONS Group
            let actions = '';
            if (!isMyStudents) {
                // Check if already in "My Students" list (using ID comparison)
                const alreadyMyStudent = myStudents.some(ms => Number(ms.id) === Number(s.id));
                const noMentor = !s.enrolled_by;

                if (noMentor) {
                    // Priority: If NO mentor, always show "Jadi mentor" button
                    actions += `<button class="btn btn-sm btn-primary mb-1 me-1 w-100" onclick="assignStudentV2(${s.id})">➕ Jadi mentor pelajar ini</button>`;
                } else if (alreadyMyStudent) {
                    // Has mentor, and I am already teaching them
                    actions += `<button class="btn btn-sm btn-light border w-100" onclick="viewStudentDetailsV2(${s.id})" title="Lihat Profil">👁️ Lihat Profil</button>`;
                } else {
                    // Has mentor, and I am NOT teaching them
                    actions += `<button class="btn btn-sm btn-outline-primary mb-1 me-1 w-100" onclick="assignStudentV2(${s.id})">➕ Ajar pelajar ini</button>`;
                }
            } else {
                // MY STUDENTS VIEW: Standard Actions + Role specific ones
                actions += `<div class="btn-group">`;

                // PDF is for everyone who teaches the student (or just mentor? user said "jana PDF profil... hanya pada mentor utama" but let's see)
                // Actually user said "buang tindakan (jana PDF profil, Edit), tindakan ini hanya pada mentor utama sahaja".
                // So PDF also ONLY for primary mentor.
                if (isPrimaryMentor) {
                    actions += `<button class="btn btn-sm btn-light border" onclick="generateIndividualPDFV2(${s.id})" title="Jana PDF Profil">📄</button>`;
                    actions += `<button class="btn btn-sm btn-light border" onclick="editStudentV2(${s.id})" title="Edit">✏️</button>`;
                    actions += `<button class="btn btn-sm btn-light border text-danger" onclick="deleteStudentV2(${s.id})" title="Padam">🗑️</button>`;
                    actions += `<button class="btn btn-sm btn-outline-warning border ms-1" onclick="resignMentorV2(${s.id})" title="Tolak Mentor">🚫 Tolak Mentor</button>`;
                } else {
                    // Guru Subjek maybe only view?
                    actions += `<button class="btn btn-sm btn-light border" onclick="viewStudentDetailsV2(${s.id})" title="Lihat Profil">👁️</button>`;
                }

                actions += `</div>`;
            }

            html += `
            <tr>
                <td class="ps-4">
                    <div class="d-flex align-items-center">
                        <div class="avatar-sm rounded-circle bg-primary bg-opacity-10 text-primary d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px; font-weight: bold;">
                            ${s.profile_emoji || getInitials(s.full_name)}
                        </div>
                        <div>
                            <div class="fw-bold text-dark">${s.full_name}</div>
                            <small class="text-muted">ID: ${s.id}</small>
                        </div>
                    </div>
                </td>
                <td>
                    <div>📞 ${s.phone}</div>
                    <small class="text-muted">Penjaga: ${s.parent_guardian_name || '-'}</small>
                </td>
                <td>
                    <span class="badge bg-info bg-opacity-10 text-info border border-info border-opacity-25 rounded-pill">
                        ${s.education_level}
                    </span>
                    <div class="small mt-1 text-muted">${s.grade_level}</div>
                </td>
                <td style="max-width: 250px;">
                    <div class="d-flex flex-wrap">
                        ${subjectBadges || '<span class="text-muted small">-</span>'}
                    </div>
                </td>
                <td>
                    ${roleBadge}
                    <div class="mt-1">
                        <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 rounded-pill">
                            ✅ Aktif
                        </span>
                    </div>
                    ${!s.enrolled_by ? '<br><small class="text-danger">⚠️ Tiada Mentor</small>' : ''}
                </td>
                <td>
                     ${actions}
                </td>
            </tr>
            `;
        });
        tbody.innerHTML = html;
    }

    function renderNewApplications() {
        const term = document.getElementById('search-new').value.toLowerCase();
        const tbody = document.getElementById('list-new-applications');

        const filtered = newApplications.filter(s =>
            s.full_name.toLowerCase().includes(term)
        );

        if (filtered.length === 0) {
            tbody.innerHTML = `<tr><td colspan="5" class="text-center py-5">
                <div class="d-flex flex-column align-items-center">
                    <div class="mb-3 text-muted" style="font-size: 3rem;">✨</div>
                    <h5 class="text-muted">Tiada permohonan baru</h5>
                    <p class="text-muted small">Semua pendaftaran telah diproses.</p>
                </div>
            </td></tr>`;
            return;
        }

        let html = '';
        filtered.forEach(s => {
            // Parse subjects
            let subjects = [];
            try {
                subjects = JSON.parse(s.required_subjects || '[]');
            } catch (e) { }
            const subjectBadges = subjects.map(sub => `<span class="badge bg-secondary bg-opacity-10 text-dark border me-1">${sub}</span>`).join('');

            html += `
            <tr class="table-warning bg-opacity-10">
                <td class="ps-4">
                   <div class="d-flex align-items-center">
                        <span class="me-3 fs-5">🆕</span>
                        <div>
                            <div class="fw-bold">${s.full_name}</div>
                            <small class="text-muted">${s.age} Tahun</small>
                        </div>
                    </div>
                </td>
                <td>${new Date(s.created_at).toLocaleDateString()}</td>
                <td>${s.grade_level}</td>
                <td>${subjectBadges}</td>
                <td class="text-end pe-4">
                    <button class="btn btn-primary btn-sm shadow-sm" onclick="openStudentApprovalModalV2(${s.id}, '${s.full_name.replace(/'/g, "\\'")}', '${s.grade_level}')">
                        🔑 Tetapkan Kata Laluan
                    </button>
                </td>
            </tr>
            `;
        });
        tbody.innerHTML = html;
    }

    // --- ACTIONS ---

    function getInitials(name) {
        return name ? name.charAt(0).toUpperCase() : '?';
    }

    function filterActiveRecords() {
        renderActiveRecords();
    }

    function filterNewApplications() {
        renderNewApplications();
    }

    function filterMyStudents() {
        renderMyStudents();
    }

    // --- PDF FUNCTIONS ---

    function generateAllStudentsPDF(type) {
        // 1. Fill date
        const now = new Date();
        document.querySelectorAll('.pdf-date').forEach(el => el.textContent = now.toLocaleDateString() + ' ' + now.toLocaleTimeString());

        const titleEl = document.getElementById('pdf-list-title');
        let data = activeRecords;

        if (type === 'my') {
            titleEl.textContent = 'Senarai Pelajar Bimbingan Saya';
            data = myStudents;
        } else {
            titleEl.textContent = 'Rekod Pelajar Aktif (Global)';
        }

        // 2. Populate Table
        const tbody = document.getElementById('template-all-students-body');
        let html = '';
        data.forEach((s, index) => {
            let subjects = [];
            try { subjects = JSON.parse(s.required_subjects || '[]'); } catch (e) { }

            html += `
                <tr style="border-bottom: 1px solid #eee; background-color: ${index % 2 === 0 ? '#fff' : '#f9fafb'};">
                    <td style="padding: 8px;"><b>${s.full_name}</b></td>
                    <td style="padding: 8px;">${s.age} Tahun</td>
                    <td style="padding: 8px;">${s.phone}<br><span style="color:#888; font-size:10px;">Penjaga: ${s.parent_guardian_name || '-'}</span></td>
                    <td style="padding: 8px;">${s.education_level}<br><span style="color:#888; font-size:10px;">${s.grade_level}</span></td>
                    <td style="padding: 8px;">${subjects.join(', ')}</td>
                </tr>
            `;
        });
        tbody.innerHTML = html;

        // 3. Generate PDF
        const element = document.getElementById('template-all-students');
        const filename = type === 'my' ? 'Senarai_Pelajar_Saya.pdf' : 'Senarai_Semua_Pelajar.pdf';
        const opt = {
            margin: 10,
            filename: filename,
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: { scale: 2 },
            jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' }
        };

        html2pdf().set(opt).from(element).save();
    }

    function generateIndividualPDFV2(id) {
        // Search in both arrays
        const s = activeRecords.find(stu => stu.id == id) || myStudents.find(stu => stu.id == id);
        if (!s) return;

        // 1. Fill Data
        const now = new Date();
        document.querySelectorAll('.pdf-date').forEach(el => el.textContent = now.toLocaleDateString());

        document.getElementById('pdf-profile-emoji').textContent = s.profile_emoji || '👨‍🎓';
        document.getElementById('pdf-profile-name').textContent = s.full_name;
        document.getElementById('pdf-profile-id').textContent = 'ID Pelajar: ' + s.id;
        document.getElementById('pdf-profile-age').textContent = s.age + ' Tahun';
        document.getElementById('pdf-profile-phone').textContent = s.phone;
        document.getElementById('pdf-profile-guardian').textContent = s.parent_guardian_name || '-';
        document.getElementById('pdf-profile-education').textContent = s.education_level;
        document.getElementById('pdf-profile-grade').textContent = s.grade_level;

        let subjects = [];
        try { subjects = JSON.parse(s.required_subjects || '[]'); } catch (e) { }

        const subjHtml = subjects.map(sub =>
            `<span style="display:inline-block; background:#f3f4f6; padding:5px 10px; border-radius:15px; margin-right:5px; margin-bottom:5px; font-size:12px; border:1px solid #ddd;">${sub}</span>`
        ).join('');

        document.getElementById('pdf-profile-subjects').innerHTML = subjHtml || '-';

        // 2. Generate PDF
        const element = document.getElementById('template-individual-student');
        const opt = {
            margin: 10,
            filename: 'Profil_Pelajar_' + s.full_name.replace(/\s+/g, '_') + '.pdf',
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: { scale: 2 },
            jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
        };

        html2pdf().set(opt).from(element).save();
    }

    // --- APPROVAL MODAL ---

    function openStudentApprovalModalV2(id, name, level) {
        document.getElementById('approvalStudentId').value = id;
        document.getElementById('approvalStudentName').textContent = name;
        document.getElementById('approvalStudentDetails').textContent = level;

        // Use default checked
        const checkBox = document.getElementById('useDefaultPassword');
        if (checkBox) {
            checkBox.checked = true;
            togglePasswordInputV2();
        }

        // Show Modal using Standard Helper
        if (typeof openModal === 'function') {
            openModal('studentApprovalModal');
        } else {
            // Fallback if openModal is not globally available (though it should be)
            const modalEl = document.getElementById('studentApprovalModal');
            modalEl.style.display = 'flex';
            modalEl.classList.add('active'); // Some systems use active class
        }
    }

    function togglePasswordInputV2() {
        const useDefault = document.getElementById('useDefaultPassword').checked;
        document.getElementById('customPasswordGroup').style.display = useDefault ? 'none' : 'block';
    }

    function handleApproveV2(e) {
        e.preventDefault();

        const studentId = document.getElementById('approvalStudentId').value;
        const useDefault = document.getElementById('useDefaultPassword').checked;
        const customPass = document.getElementById('customPassword').value;

        if (!useDefault && !customPass) {
            Swal.fire('Perhatian', 'Sila masukkan kata laluan!', 'warning');
            return;
        }

        const formData = new FormData();
        formData.append('action', 'approve_student_application');
        formData.append('student_id', studentId);
        formData.append('use_default', useDefault);
        formData.append('password', customPass);

        fetch('../api.php', {
            method: 'POST',
            body: formData
        })
            .then(res => res.json())
            .then(res => {
                if (res.success) {
                    // Close modal using standard helper
                    if (typeof closeModal === 'function') {
                        closeModal('studentApprovalModal');
                    } else {
                        document.getElementById('studentApprovalModal').classList.remove('active');
                        document.body.style.overflow = '';
                    }

                    // Show success (SweetAlert2 if available, else alert)
                    if (typeof Swal !== 'undefined') {
                        Swal.fire('Berjaya', 'Pelajar telah diaktifkan!', 'success');
                    } else {
                        Swal.fire('Berjaya', 'Pelajar telah diaktifkan!', 'success');
                    }

                    // Refresh data
                    loadStudentManagementDataV2();

                    // Switch to Active tab to see the new student
                    switchMainTabV2('active');
                } else {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire('Ralat', res.message || 'Ralat berlaku', 'error');
                    } else {
                        alert(res.message || 'Ralat berlaku');
                    }
                }
            })
            .catch(e => {
                console.error(e);
                alert('Ralat sambungan');
            });
    }

</script>

<!-- Modal Add Student Manual -->
<!-- Modal Add Student Manual -->
<div class="modal-overlay" id="addStudentModal">
    <div class="modal" style="max-width: 800px;">
        <div class="modal-header bg-primary text-white">
            <h3 class="modal-title" style="color: white; margin: 0;">➕ Tambah Pelajar Manual</h3>
            <button type="button" class="modal-close" onclick="closeModal('addStudentModal')"
                style="color: white; border: none; background: transparent; font-size: 24px;">×</button>
        </div>
        <div class="modal-body p-0" style="height: 80vh; overflow: hidden;">
            <iframe id="addStudentFrame" src="" style="width: 100%; height: 100%; border: none;"></iframe>
        </div>
    </div>
</div>

<script>
    // --- ADD STUDENT MANUAL (IFRAME) ---
    function showAddStudentModal() {
        // Reload iframe to ensure fresh state
        var iframe = document.getElementById('addStudentFrame');
        if (iframe) {
            iframe.src = '../register.php?teacher_id=<?php echo $_SESSION['user_id']; ?>&embedded=true';
        }

        if (typeof openModal === 'function') {
            openModal('addStudentModal');
        } else {
            document.getElementById('addStudentModal').classList.add('active');
            document.body.style.overflow = 'hidden';
        }
    }

    // Helper data (Match the reality in DB dump: 'Tahun' instead of 'Darjah')
    const gradeOptions = {
        'Sekolah Rendah': ['Tahun 1', 'Tahun 2', 'Tahun 3', 'Tahun 4', 'Tahun 5', 'Tahun 6'],
        'Sekolah Menengah': ['Tingkatan 1', 'Tingkatan 2', 'Tingkatan 3', 'Tingkatan 4', 'Tingkatan 5']
    };

    // Deprecated static subjectOptions - now fetching dynamic subjects
    // const subjectOptions = { ... }; 

    function populateSubjectFilter(students, selectId) {
        const select = document.getElementById(selectId);
        if (!select) return;
        const currentVal = select.value;

        // Get all unique subjects
        let allSubjects = new Set();
        students.forEach(s => {
            try {
                const subs = JSON.parse(s.required_subjects || '[]');
                if (Array.isArray(subs)) {
                    subs.forEach(subj => allSubjects.add(subj));
                }
            } catch (e) { }
        });

        // Clear except first
        if (select.options) {
            while (select.options.length > 1) {
                select.remove(1);
            }
        }

        // Add sorted subjects
        Array.from(allSubjects).sort().forEach(subj => {
            const opt = document.createElement('option');
            opt.value = subj;
            opt.textContent = subj;
            select.appendChild(opt);
        });

        select.value = currentVal;
    }

    function updateGradeLevels(level) {
        const gradeSelect = document.getElementById('inputGradeLevel');
        gradeSelect.innerHTML = '<option value="" selected disabled>Pilih Tahun/Tingkatan</option>';

        if (gradeOptions[level]) {
            gradeOptions[level].forEach(grade => {
                gradeSelect.innerHTML += `<option value="${grade}">${grade}</option>`;
            });
        }

        // Update subjects too
        updateSubjectCheckboxes(level);
    }

    function updateSubjectCheckboxes(level) {
        const container = document.getElementById('subjectCheckboxes');
        container.innerHTML = '<div class="col-12 text-muted small">Memuatkan subjek...</div>';

        // Fetch subjects from API based on level
        fetch('../api.php?action=get_subjects_by_level&level=' + encodeURIComponent(level))
            .then(res => res.json())
            .then(data => {
                container.innerHTML = '';
                if (data.success && data.subjects && data.subjects.length > 0) {
                    data.subjects.forEach(sub => {
                        const subName = sub.subject_name; // Use DB column
                        container.innerHTML += `
                            <div class="col-md-4 col-sm-6 mb-2">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="required_subjects[]" value="${subName}" id="sub_${sub.id}">
                                    <label class="form-check-label" for="sub_${sub.id}">${subName}</label>
                                </div>
                            </div>
                        `;
                    });
                } else {
                    container.innerHTML = '<div class="col-12 text-muted small">Tiada subjek tersedia untuk tahap ini.</div>';
                }
            })
            .catch(err => {
                console.error(err);
                container.innerHTML = '<div class="col-12 text-danger small">Ralat memuatkan subjek.</div>';
            });
    }



</script>

<!-- Modal Edit Student -->
<!-- Modal Edit Student -->
<div class="modal-overlay" id="editStudentModal">
    <div class="modal" style="max-width: 800px;">
        <div class="modal-header bg-warning text-dark">
            <h3 class="modal-title" style="margin: 0;">✏️ Kemaskini Maklumat Pelajar</h3>
            <button type="button" class="modal-close" onclick="closeModal('editStudentModal')"
                style="border: none; background: transparent; font-size: 24px;">×</button>
        </div>
        <div class="modal-body p-4">
            <form id="editStudentForm" onsubmit="handleUpdateStudentV2(event)">
                <input type="hidden" name="student_id" id="edit_student_id">

                <div class="d-flex align-items-center gap-3 mb-4 pb-3 border-bottom"
                    style="display: flex; align-items: center; gap: 15px; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee;">
                    <div
                        style="width: 60px; height: 60px; font-size: 30px; background: #f8f9fa; border-radius: 50%; display: flex; align-items: center; justify-content: center; border: 1px solid #ddd;">
                        👨‍🎓
                    </div>
                    <div>
                        <h4 class="fw-bold mb-1" id="edit_display_name" style="margin: 0;">Nama Pelajar</h4>
                        <p class="text-muted mb-0 small" style="margin: 0; font-size: 0.85rem;">ID: <span
                                id="edit_display_id"></span> &bull; <span id="edit_display_status" class="badge"
                                style="background-color: #28a745; color: white; padding: 2px 8px; border-radius: 10px;">Active</span>
                        </p>
                    </div>
                </div>

                <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist"
                    style="display: flex; list-style: none; padding: 0; gap: 10px; margin-bottom: 20px; border-bottom: 1px solid #eee; padding-bottom: 10px;">
                    <li class="nav-item">
                        <button class="nav-link active" data-bs-toggle="pill" data-bs-target="#pills-info"
                            type="button">Maklumat & Akademik</button>
                    </li>
                    <li class="nav-item">
                        <button class="nav-link" data-bs-toggle="pill" data-bs-target="#pills-login" type="button">Log
                            Masuk & Kata Laluan</button>
                    </li>
                </ul>

                <div class="tab-content" id="pills-tabContent">

                    <!-- TAB 1: INFO -->
                    <div class="tab-pane fade show active" id="pills-info">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                            <div>
                                <label class="form-label">Nama Penuh</label>
                                <input type="text" class="form-control" name="full_name" id="edit_full_name" required>
                            </div>
                            <div>
                                <label class="form-label">Umur</label>
                                <input type="number" class="form-control" name="age" id="edit_age" required>
                            </div>
                        </div>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                            <div>
                                <label class="form-label">No. Telefon</label>
                                <input type="text" class="form-control" name="phone" id="edit_phone" required>
                            </div>
                            <div>
                                <label class="form-label">Nama Penjaga</label>
                                <input type="text" class="form-control" name="parent_guardian_name"
                                    id="edit_parent_guardian_name" required>
                            </div>
                        </div>

                        <hr style="margin: 20px 0; border: none; border-top: 1px solid #eee;">

                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                            <div>
                                <label class="form-label">Tahap Pendidikan</label>
                                <select class="form-select" name="education_level" id="edit_education_level"
                                    onchange="updateGradeLevelsEdit(this.value); updateEditSubjectCheckboxes(this.value)">
                                    <option value="Sekolah Rendah">Sekolah Rendah</option>
                                    <option value="Sekolah Menengah">Sekolah Menengah</option>
                                </select>
                            </div>
                            <div>
                                <label class="form-label">Tahun / Tingkatan</label>
                                <select class="form-select" name="grade_level" id="edit_grade_level">
                                    <!-- Populated via JS -->
                                </select>
                            </div>
                        </div>

                        <div class="col-12" style="margin-top: 15px;">
                            <label class="form-label">Subjek Yang Diambil</label>
                            <div class="card p-3 bg-light"
                                style="background-color: #f8f9fa; padding: 15px; border-radius: 8px;">
                                <div id="editSubjectCheckboxes"
                                    style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px;">
                                    <div class="text-muted small">Sila pilih tahap pendidikan.</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- TAB 2: LOGIN -->
                    <div class="tab-pane fade" id="pills-login">
                        <div class="mb-3">
                            <label class="form-label">Nama Pengguna (Username)</label>
                            <input type="text" class="form-control" name="username" id="edit_username" required>
                        </div>

                        <div class="alert alert-warning"
                            style="background: #fff3cd; padding: 10px; border-radius: 8px; margin-bottom: 15px;">
                            <small>⚠️ Biarkan kosong bahagian kata laluan jika tidak mahu menukarnya.</small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Tukar Kata Laluan Baru</label>
                            <div style="display: flex; gap: 5px;">
                                <input type="text" class="form-control" name="password" id="edit_password"
                                    placeholder="Masukkan kata laluan baru jika perlu">
                                <button class="btn btn-secondary" type="button" style="padding: 10px;"
                                    onclick="document.querySelector('#edit_password').value = Math.random().toString(36).slice(-8)">🎲</button>
                            </div>
                        </div>
                    </div>

                </div>

                <div class="d-flex justify-content-end mt-4 pt-3 border-top"
                    style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee;">
                    <button type="button" class="btn btn-secondary"
                        onclick="closeModal('editStudentModal')">Batal</button>
                    <button type="submit" class="btn btn-warning"
                        style="background-color: #ffc107; color: #212529; border: none; padding: 10px 20px; font-weight: bold; border-radius: 8px; cursor: pointer;">
                        Simpan Perubahan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // ... Existing JS ...

    // --- EDIT STUDENT ---
    function editStudentV2(id) {
        // Search student in local tab arrays or global dashboard array
        let s = activeRecords.find(stu => stu.id == id) ||
            myStudents.find(stu => stu.id == id) ||
            (window.studentsData ? window.studentsData.find(stu => (stu.id == id || stu.student_id == id)) : null);

        if (!s) {
            // If still not found, fetch from server
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    title: 'Memuatkan data pelajar...',
                    didOpen: () => { Swal.showLoading(); }
                });
            }

            fetch('../api.php?action=get_student_profile&student_id=' + id)
                .then(res => res.json())
                .then(result => {
                    if (typeof Swal !== 'undefined') Swal.close();
                    if (result.success && result.profile) {
                        openEditStudentModalV2(result.profile);
                    } else {
                        alert('Pelajar tidak dijumpai: ' + (result.message || ''));
                    }
                })
                .catch(err => {
                    if (typeof Swal !== 'undefined') Swal.close();
                    console.error(err);
                    alert('Ralat sambungan server.');
                });
            return;
        }

        openEditStudentModalV2(s);
    }

    function openEditStudentModalV2(s) {
        // Fill Form
        const stuId = s.id || s.student_id;
        document.getElementById('edit_student_id').value = stuId;
        document.getElementById('edit_display_name').textContent = s.full_name || s.student_name || '';
        document.getElementById('edit_display_id').textContent = stuId;

        document.getElementById('edit_full_name').value = s.full_name || s.student_name || '';
        document.getElementById('edit_age').value = s.age || '';
        document.getElementById('edit_phone').value = s.phone || s.student_phone || '';
        document.getElementById('edit_parent_guardian_name').value = s.parent_guardian_name || '';

        document.getElementById('edit_education_level').value = s.education_level || '';

        // Update grade options first
        updateGradeLevelsEdit(s.education_level, s.grade_level);

        // Parse current subjects
        let currentSubjects = [];
        try {
            currentSubjects = typeof s.required_subjects === 'string' ? JSON.parse(s.required_subjects) : s.required_subjects;
        } catch (e) { currentSubjects = []; }

        updateEditSubjectCheckboxes(s.education_level, currentSubjects);



        document.getElementById('edit_username').value = s.username || '';
        document.getElementById('edit_password').value = ''; // Reset password field

        if (typeof resetEditTabs === 'function') resetEditTabs();

        if (typeof openModal === 'function') {
            openModal('editStudentModal');
        } else {
            document.getElementById('editStudentModal').classList.add('active');
            document.body.style.overflow = 'hidden';
        }
    }

    function updateGradeLevelsEdit(level, selectedGrade = null) {
        const gradeSelect = document.getElementById('edit_grade_level');
        gradeSelect.innerHTML = '';

        if (gradeOptions[level]) {
            gradeOptions[level].forEach(grade => {
                const opt = document.createElement('option');
                opt.value = grade;
                opt.textContent = grade;
                if (selectedGrade && grade === selectedGrade) opt.selected = true;
                gradeSelect.appendChild(opt);
            });
        }
    }

    function updateEditSubjectCheckboxes(level, selectedSubjects = []) {
        const container = document.getElementById('editSubjectCheckboxes');
        container.innerHTML = '<div class="col-12 text-center text-muted"><div class="spinner-border spinner-border-sm"></div> Memuatkan subjek...</div>';

        if (!level) {
            container.innerHTML = '<div class="col-12 text-muted small">Sila pilih tahap pendidikan.</div>';
            return;
        }

        // Fetch from API
        fetch(`../api.php?action=get_subjects_by_level&level=${encodeURIComponent(level)}`)
            .then(res => res.json())
            .then(result => {
                if (result.success) {
                    container.innerHTML = '';
                    if (result.subjects.length > 0) {
                        result.subjects.forEach(sub => {
                            const subName = sub.subject_name; // Adjust based on DB column name
                            const isChecked = selectedSubjects.includes(subName) ? 'checked' : '';
                            container.innerHTML += `
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="required_subjects[]" value="${subName}" id="edit_sub_${subName.replace(/\s+/g, '')}" ${isChecked}>
                                    <label class="form-check-label" for="edit_sub_${subName.replace(/\s+/g, '')}">${subName}</label>
                                </div>
                            `;
                        });
                    } else {
                        container.innerHTML = '<div class="col-12 text-muted small">Tiada subjek tersedia untuk tahap ini.</div>';
                    }
                } else {
                    container.innerHTML = '<div class="col-12 text-danger small">Gagal memuatkan subjek.</div>';
                }
            })
            .catch(err => {
                console.error(err);
                container.innerHTML = '<div class="col-12 text-danger small">Ralat sambungan.</div>';
            });
    }

    function deleteStudentV2(id) {
        if (!confirm('Adakah anda pasti mahu memadam/menyahaktifkan rekod pelajar ini?')) return;

        const formData = new FormData();
        formData.append('action', 'delete_student');
        formData.append('id', id);

        fetch('../api.php', {
            method: 'POST',
            body: formData
        })
            .then(res => res.json())
            .then(res => {
                if (res.success) {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire('Berjaya', res.message, 'success');
                    } else {
                        alert(res.message);
                    }
                    loadStudentManagementDataV2();
                } else {
                    alert(res.message || 'Ralat berlaku');
                }
            })
            .catch(e => {
                console.error(e);
                alert('Ralat sambungan');
            });
    }

    function handleUpdateStudentV2(e) {
        e.preventDefault();

        const form = e.target;
        const formData = new FormData(form);
        formData.set('action', 'update_student');

        fetch('../api.php', {
            method: 'POST',
            body: formData
        })
            .then(res => res.json())
            .then(res => {
                if (res.success) {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire('Berjaya', 'Maklumat pelajar dikemaskini!', 'success');
                    } else {
                        Swal.fire('Berjaya', 'Maklumat pelajar dikemaskini!', 'success');
                    }

                    // Reliable Modal Closing
                    if (typeof closeModal === 'function') {
                        closeModal('editStudentModal');
                    } else {
                        document.getElementById('editStudentModal').classList.remove('active');
                        document.body.style.overflow = '';
                    }

                    loadStudentManagementDataV2();
                } else {
                    alert(res.message || 'Gagal mengemaskini.');
                }
            })
            .catch(err => {
                console.error(err);
                alert('Ralat sistem.');
            });
    }

</script>

<script>
    // Manual Tab Switching for Edit Modal (Safety fallback)
    document.addEventListener('DOMContentLoaded', function () {
        const tabButtons = document.querySelectorAll('#pills-tab button[data-bs-toggle="pill"]');
        tabButtons.forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                // Remove active from all buttons
                tabButtons.forEach(b => b.classList.remove('active'));
                // Add active to clicked
                this.classList.add('active');

                // Allow BS5 default behavior if it works, but also force show content
                const targetId = this.getAttribute('data-bs-target');
                const panes = document.querySelectorAll('.tab-pane');
                panes.forEach(p => {
                    p.classList.remove('show', 'active');
                    p.style.display = 'none'; // Ensure hidden
                });

                const targetPane = document.querySelector(targetId);
                if (targetPane) {
                    targetPane.classList.add('show', 'active');
                    targetPane.style.display = 'block'; // Ensure visible
                }
            });
        });
    });

    // Also Initialize on Open function to ensure first tab is reset
    // Also Initialize on Open function to ensure first tab is reset
    function resetEditTabs() {
        // Ensure Parent Container is Visible
        const tabContent = document.getElementById('pills-tabContent');
        if (tabContent) {
            tabContent.style.display = 'block';
            tabContent.style.opacity = '1';
        }

        // Force Tab 1 Active
        const firstTabBtn = document.querySelector('#pills-tab button[data-bs-target="#pills-info"]');
        const secondTabBtn = document.querySelector('#pills-tab button[data-bs-target="#pills-login"]');

        if (firstTabBtn && secondTabBtn) {
            firstTabBtn.classList.add('active');
            secondTabBtn.classList.remove('active');
        }

        const tab1 = document.getElementById('pills-info');
        const tab2 = document.getElementById('pills-login');

        if (tab1) {
            tab1.classList.add('show', 'active');
            tab1.style.display = 'block';
            tab1.style.opacity = '1';
        }
        if (tab2) {
            tab2.classList.remove('show', 'active');
            tab2.style.display = 'none';
        }
    }
</script>

<style>
    .active-tab-btn {
        background-color: #f3f4f6;
        /* Light gray bg for active */
        border-radius: 5px 5px 0 0;
    }

    .avatar-circle {
        transition: transform 0.2s;
    }

    .avatar-circle:hover {

        transform: scale(1.1);
    }
</style>