<?php
/**
 * Teacher Dashboard - Tab Pengurusan Pelajar (Refactored)
 * Bahagian I: Rekod Pelajar Aktif
 * Bahagian II: Permohonan Baru
 */
?>
<div id="student-management" class="tab-content">
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
            <div>
                <h4 class="card-title mb-1">Pengurusan Pelajar (Versi 2.0)</h4>
                <p class="text-muted small mb-0">Uruskan rekod pelajar dan permohonan baru</p>
            </div>
            <div class="header-actions">
                <button class="btn btn-outline-primary btn-sm" id="btn-refresh-student-management"
                    onclick="loadStudentManagementDataV2()">
                    🔄 Refresh
                </button>
            </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">

                <!-- BAHAGIAN I: REKOD PELAJAR AKTIF (GLOBAL) -->
                <div id="view-active-records">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div class="d-flex gap-2 align-items-center flex-wrap">
                            <div class="input-group" style="max-width: 300px;">
                                <span class="input-group-text bg-white"><i class="fas fa-search"></i></span>
                                <input type="text" class="form-control border-start-0 ps-0" id="search-active"
                                    placeholder="Cari semua rekod..." onkeyup="filterActiveRecords()">
                            </div>
                            <select class="form-select w-auto" id="filter-subject-active"
                                onchange="filterActiveRecords()">
                                <option value="">Semua Subjek</option>
                                <!-- Will be populated by JS -->
                            </select>
                        </div>
                        <div class="dropdown">
                            <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button"
                                data-bs-toggle="dropdown" aria-expanded="false">
                                🖨️ Jana PDF
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><button class="dropdown-item" onclick="generateAllStudentsPDF('global')">📋 Senarai
                                        Penuh
                                        Pelajar</button></li>
                            </ul>
                        </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="d-flex justify-content-between align-items-center mb-4">
                        <div class="d-flex gap-2">
                            <input type="text" class="form-control" id="search-new" style="max-width: 300px;"
                                placeholder="Cari permohonan..." onkeyup="filterNewApplications()">
                        </div>
                        <button class="btn btn-outline-danger btn-sm" onclick="generateAllStudentsPDFV2('active')">
                            📥 PDF Senarai (Global)
                        </button>
                        <a href="../register.php?teacher_id=<?php echo $_SESSION['user_id']; ?>" class="btn btn-primary"
                            target="_blank">
                            ➕ Tambah Pelajar Manual
                        </a>
                    </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="d-flex justify-content-between align-items-center mb-4">
                        <div class="d-flex gap-2 align-items-center flex-wrap">
                            <div class="input-group" style="max-width: 300px;">
                                <span class="input-group-text bg-white text-primary"><i
                                        class="fas fa-search"></i></span>
                                <input type="text" class="form-control border-start-0 ps-0" id="search-my"
                                    placeholder="Cari pelajar saya..." onkeyup="filterMyStudents()">
                            </div>
                            <select class="form-select w-auto" id="filter-subject-my" onchange="filterMyStudents()">
                                <option value="">Semua Subjek</option>
                            </select>
                        </div>
                        <div class="dropdown">
                            <button class="btn btn-primary btn-sm dropdown-toggle" type="button"
                                data-bs-toggle="dropdown" aria-expanded="false">
                                🖨️ Laporan Mentor
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><button class="dropdown-item" onclick="generateAllStudentsPDF('my')">📄 Senarai
                                        Pelajar Saya</button></li>
                            </ul>
                        </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>
</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>
    console.log('✅ tab-student-management-v2.php LOADED');
    let activeRecords = [];
    let newApplications = [];
    let myStudents = [];

    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 => {
                console.log('Response received:', response.status);
                if (!response.ok) throw new Error('HTTP ' + response.status);
                return response.json();
            })
            .then(result => {
                console.log('Data parsed:', 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;

                } else {
                    console.error('API Error:', result.message);
                    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() {
        console.log('initStudentManagement called');
        if (document.getElementById('student-management')) {
            loadStudentManagementDataV2();
            switchMainTabV2('active');
        } else {
            console.warn('student-management element not found');
        }
    }


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

    function assignStudentV2(id) {
        if (!confirm('Adakah anda pasti mahu mengambil pelajar ini di bawah seliaan anda?')) return;

        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) {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire('Berjaya', res.message, 'success');
                    } else {
                        alert(res.message);
                    }
                    loadStudentManagementDataV2();
                    // Switch to 'My Students' to see the change result
                    switchMainTabV2('my');
                } else {
                    alert(res.message || 'Ralat berlaku');
                }
            })
            .catch(e => {
                console.error(e);
                if (typeof Swal !== 'undefined') {
                    Swal.fire('Ralat', 'Ralat sambungan', 'error');
                } else {
                    alert('Ralat sambungan');
                }
            });
    }

    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 seliaan 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('');
            const myBadge = isMyStudents ? `<span class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 rounded-pill mb-1">Mentor</span>` : '';

            // Assign button logic: Show in Active Records (not My Students)
            // If enrolled_by is NULL, they become Primary Mentor.
            // If enrolled_by exists, they become Additional Teacher.
            let actions = '';
            if (!isMyStudents) {
                const btnLabel = !s.enrolled_by ? '➕ Jadi Mentor Utama' : '➕ Ajar Pelajar Ini';
                const btnClass = !s.enrolled_by ? 'btn-primary' : 'btn-outline-primary';

                actions += `<button class="btn btn-sm ${btnClass} mb-1 me-1" onclick="assignStudentV2(${s.id})">${btnLabel}</button>`;
            }

            actions += `
                <div class="btn-group">
                    <button class="btn btn-sm btn-light border" onclick="generateIndividualPDFV2(${s.id})" title="Jana PDF Profil">📄</button>
                    <button class="btn btn-sm btn-light border" onclick="editStudentV2(${s.id})" title="Edit">✏️</button>
                    <button class="btn btn-sm btn-light border text-danger" onclick="deleteStudentV2(${s.id})" title="Padam">🗑️</button>
                </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>
                    ${myBadge}
                    <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 rounded-pill">
                        ✅ Aktif
                    </span>
                    ${!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-4">
            <form id="addStudentForm" onsubmit="handleAddStudentV2(event)">
                <div class="row g-3">
                    <!-- Personal Info -->
                    <div class="col-12">
                        <h6 class="text-primary fw-bold border-bottom pb-2">Maklumat Peribadi</h6>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
                        <div>
                            <label class="form-label required">Nama Penuh</label>
                            <input type="text" class="form-control" name="full_name" required
                                placeholder="Contoh: Ali Bin Abu">
                        </div>
                        <div>
                            <label class="form-label required">Umur</label>
                            <input type="number" class="form-control" name="age" required min="4" max="19"
                                placeholder="Contoh: 15">
                        </div>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
                        <div>
                            <label class="form-label required">No. Telefon Pelajar/Penjaga</label>
                            <input type="tel" class="form-control" name="phone" required placeholder="0123456789">
                        </div>
                        <div>
                            <label class="form-label required">Nama Penjaga</label>
                            <input type="text" class="form-control" name="parent_guardian_name" required>
                        </div>
                    </div>

                    <!-- Academic Info -->
                    <div class="col-12 mt-4">
                        <h6 class="text-primary fw-bold border-bottom pb-2">Maklumat Akademik</h6>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
                        <div>
                            <label class="form-label required">Tahap Pendidikan</label>
                            <select class="form-select" name="education_level" required
                                onchange="updateGradeLevels(this.value)">
                                <option value="" selected disabled>Pilih Tahap</option>
                                <option value="Prasekolah">Prasekolah</option>
                                <option value="Sekolah Rendah">Sekolah Rendah</option>
                                <option value="Sekolah Menengah">Sekolah Menengah</option>
                            </select>
                        </div>
                        <div>
                            <label class="form-label required">Tahun / Tingkatan</label>
                            <select class="form-select" name="grade_level" id="inputGradeLevel" required>
                                <option value="" selected disabled>Sila pilih tahap dahulu</option>
                            </select>
                        </div>
                    </div>

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

                    <!-- Login Info -->
                    <div class="col-12 mt-4">
                        <h6 class="text-primary fw-bold border-bottom pb-2">Tetapan Log Masuk</h6>
                    </div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
                        <div>
                            <label class="form-label required">Nama Pengguna (Username)</label>
                            <input type="text" class="form-control" name="username" required
                                placeholder="username_unik">
                        </div>
                        <div>
                            <label class="form-label required">Kata Laluan</label>
                            <div style="display: flex; gap: 5px;">
                                <input type="text" class="form-control" name="password" value="pelajartutor123"
                                    required>
                                <button class="btn btn-secondary" type="button" style="padding: 10px;"
                                    onclick="document.querySelector('[name=password]').value = Math.random().toString(36).slice(-8)">🎲</button>
                            </div>
                            <small class="text-muted">Default: <code>pelajartutor123</code></small>
                        </div>
                    </div>

                </div>

                <div class="d-grid mt-4" style="margin-top: 20px;">
                    <button type="submit" class="btn btn-primary"
                        style="width: 100%; padding: 12px; border-radius: 8px; font-weight: bold;">
                        💾 Simpan & Tambah Pelajar
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // --- ADD STUDENT MANUAL ---
    function showAddStudentModal() {
        // Reset form
        document.getElementById('addStudentForm').reset();
        document.getElementById('inputGradeLevel').innerHTML = '<option value="" selected disabled>Sila pilih tahap dahulu</option>';
        document.getElementById('subjectCheckboxes').innerHTML = '<div class="col-12 text-muted small">Sila pilih tahap pendidikan untuk melihat subjek.</div>';

        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 = {
        'Prasekolah': ['4 Tahun', '5 Tahun', '6 Tahun'],
        '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']
    };

    const subjectOptions = {
        'Prasekolah': ['Bahasa Melayu', 'English', 'Matematik', 'Sains', 'Jawi'],
        'Sekolah Rendah': ['Bahasa Melayu', 'English', 'Matematik', 'Sains', 'Sejarah', 'Pendidikan Islam', 'Bahasa Inggeris'],
        'Sekolah Menengah': ['Bahasa Melayu', 'English', 'Matematik', 'Sains', 'Sejarah', 'Geografi', 'Fizik', 'Kimia', 'Biologi', 'Add Math', 'Pendidikan Islam', 'Asas Sains Komputer']
    };

    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 = '';

        if (subjectOptions[level]) {
            subjectOptions[level].forEach(sub => {
                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="${sub}" id="sub_${sub.replace(/\s+/g, '')}">
                            <label class="form-check-label" for="sub_${sub.replace(/\s+/g, '')}">${sub}</label>
                        </div>
                    </div>
                `;
            });
        } else {
            container.innerHTML = '<div class="col-12 text-muted small">Tiada subjek tersedia.</div>';
        }
    }

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

        const form = e.target;
        // Scope subjects search to THIS form
        const subjects = form.querySelectorAll('input[name="required_subjects[]"]:checked');
        if (subjects.length === 0) {
            alert('Sila pilih sekurang-kurangnya satu subjek.');
            return;
        }

        const formData = new FormData(form);
        formData.set('action', 'add_student_manual'); // Ensure action is set correctly

        fetch('../api.php', {
            method: 'POST',
            body: formData
        })
            .then(res => res.text()) // Get text first to debug json errors
            .then(text => {
                try {
                    return JSON.parse(text);
                } catch (e) {
                    console.error('SERVER RAW:', text);
                    throw new Error('Respon pelayan tidak sah');
                }
            })
            .then(res => {
                if (res.success) {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire('Berjaya', 'Pelajar baru berjaya ditambah!', 'success');
                    } else {
                        Swal.fire('Berjaya', 'Pelajar baru berjaya ditambah!', 'success');
                    }

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

                    loadStudentManagementDataV2();
                    // Switch to 'Active' usually, as manual add = Active immediately
                    switchMainTabV2('active');
                } else {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire('Ralat', res.message || 'Gagal menambah pelajar', 'error');
                    } else {
                        alert(res.message || 'Gagal menambah pelajar');
                    }
                }
            })
            .catch(err => {
                console.error(err);
                alert('Ralat sistem: ' + err.message);
            });
    }


</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="Prasekolah">Prasekolah</option>
                                    <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>