<?php
// Classrooms Tab Component
// Located at: components/teacher/tab-classrooms.php
?>
<div id="classrooms" class="tab-content">
    <div class="card"
        style="margin-bottom: 25px; border-radius: 20px; overflow: hidden; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.05); animation: fadeInDown 0.6s ease-out;">
        <div style="height: 6px; background: linear-gradient(90deg, var(--primary-color) 0%, #764ba2 100%);"></div>
        <div class="card-body" style="padding: 25px;">
            <div style="display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
                <div
                    style="background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%); width: 60px; height: 60px; border-radius: 16px; display: flex; align-items: center; justify-content: center; font-size: 1.8rem; box-shadow: 0 8px 16px rgba(102, 126, 234, 0.25); color: white;">
                    🏫
                </div>
                <div style="flex: 1; min-width: 200px;">
                    <h4 style="margin: 0 0 5px 0; color: #1a1a2e; font-size: 1.4rem; font-weight: 800;">Bilik Darjah
                        Online
                    </h4>
                    <p style="margin: 0; color: #6b7280; font-size: 0.95rem; line-height: 1.5;">Urus kelas dalam talian
                        (Google Meet/Zoom) dan kehadiran pelajar.</p>
                </div>
            </div>
        </div>
    </div>

    <div class="card"
        style="border-radius: 20px; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.05); overflow: hidden; animation: fadeInUp 0.6s ease-out 0.2s both;">
        <div class="card-header bg-white"
            style="padding: 20px 25px; border-bottom: 1px solid #f0f0f0; display: flex; justify-content: space-between; align-items: center;">
            <div style="display: flex; align-items: center; gap: 12px;">
                <div
                    style="background: #f0f4ff; width: 35px; height: 35px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: var(--primary-color);">
                    <i class="fas fa-video"></i>
                </div>
                <h3 class="card-title" style="margin: 0; font-size: 1.15rem; font-weight: 700; color: #1a1a2e;">Senarai
                    Kelas Online</h3>
            </div>
            <div style="display: flex; gap: 10px; align-items: center;">
                <div class="dropdown" style="position: relative; display: inline-block;">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="classFilterButton" onclick="toggleClassFilterV3()" 
                        style="border-radius: 20px; padding: 5px 15px; border-color: #e2e8f0; background: white; color: #495057; display: flex; align-items: center; gap: 8px;">
                        <span>👥 Semua Pelajar</span>
                    </button>
                    <div id="classFilterDropdown" style="display: none; position: absolute; top: 100%; right: 0; background: white; border: 1px solid rgba(0,0,0,0.15); border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); width: 280px; z-index: 1000; padding: 15px; margin-top: 5px;">
                        <div style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;">
                             <span class="text-muted small" style="font-weight: 600;">Pilih Pelajar:</span>
                             <a href="javascript:void(0)" onclick="resetClassFilterV3()" style="font-size: 0.8rem; text-decoration: none; color: var(--primary-color);">Reset</a>
                        </div>
                        <div id="classFilterChecklist" style="max-height: 250px; overflow-y: auto; margin-bottom: 10px;">
                            <p class="text-center text-muted small">Memuatkan...</p>
                        </div>
                        <button class="btn btn-primary btn-sm btn-block" style="width: 100%; border-radius: 8px;" onclick="applyClassFilterV3()">Tapis Kelas</button>
                    </div>
                </div>
                <div class="text-muted small">
                    <i class="fas fa-info-circle"></i> Jadual diselaraskan automatik
                </div>
            </div>
        </div>
        <div class="card-body">
            <div id="classList"
                style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;">
                <p class="text-center text-muted" style="grid-column: 1/-1;">Memuatkan kelas...</p>
            </div>
        </div>
    </div>
</div>

<!-- CLASS UPDATE MODAL -->
<div class="modal-overlay" id="classModal">
    <div class="modal" style="max-width: 600px;">
        <div class="modal-header">
            <h3 class="modal-title">🔗 Kemaskini Pautan Kelas</h3>
            <button class="modal-close" onclick="closeModal('classModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="classForm" onsubmit="saveClassV3(event)">
                <input type="hidden" name="id" id="classId">

                <div class="alert alert-info">
                    <small>Info kelas (Tarikh/Masa) diambil dari Jadual. Sila kemaskini pautan dan penerangan
                        sahaja.</small>
                </div>

                <div class="form-group">
                    <label class="form-label">Tajuk Kelas</label>
                    <input type="text" class="form-control" id="classTitle" disabled style="background: #f0f0f0;">
                </div>

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Tarikh</label>
                        <input type="text" class="form-control" id="classDate" disabled style="background: #f0f0f0;">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Masa</label>
                        <input type="text" class="form-control" id="classTime" disabled style="background: #f0f0f0;">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Pautan Sertai (Zoom/Google Meet) <span class="required">*</span></label>
                    <input type="url" class="form-control" name="join_link" id="classJoinLink"
                        placeholder="https://zoom.us/j/..." required>
                    <small class="text-muted">Masukkan pautan penuh (termasuk https://)</small>
                </div>

                <div class="form-group">
                    <label class="form-label">Penerangan / Nota Kepada Pelajar</label>
                    <textarea class="form-control" name="description" id="classDescription" rows="3"
                        placeholder="Sila sertai 5 minit awal..."></textarea>
                </div>

                <div class="form-group">
                    <label class="form-label">Akses Pelajar (Pilih pelajar yang boleh lihat kelas ini)</label>
                    <div id="classStudentChecklist" style="max-height: 150px; overflow-y: auto; border: 1px solid #eee; padding: 10px; border-radius: 8px; background: #fafafa;">
                        <p class="text-muted small">Memuatkan...</p>
                    </div>
                    <small class="text-muted">Biarkan kosong untuk semua pelajar (jika tiada sekatan khusus).</small>
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;"
                        onclick="closeModal('classModal')">Batal</button>
                    <button type="submit" class="btn btn-primary" style="flex: 1;">💾 Simpan Pautan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal-overlay" id="classStudentsModal">
    <div class="modal" style="max-width: 500px;">
        <div class="modal-header">
            <h3 class="modal-title">👥 Pelajar - <span id="classDetailTitle"></span></h3>
            <button class="modal-close" onclick="closeModal('classStudentsModal')">×</button>
        </div>
        <div class="modal-body">
            <div id="classStudentsList" style="max-height: 300px; overflow-y: auto;">
                <p class="text-center text-muted">Memuatkan...</p>
            </div>

            <div style="margin-top: 20px;">
                <button type="button" class="btn btn-secondary" style="width: 100%;"
                    onclick="closeModal('classStudentsModal')">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script>
    // Classroom Logic V3
    var allClassesDataV3 = [];
    var taughtStudentsForFilterV3 = [];
    var selectedStudentIdsForFilter = []; // Array of selected IDs

    function loadClassesV3() {
        console.log('Loading Classes V3...');

        var studentPromise = (taughtStudentsForFilterV3.length === 0) 
            ? loadTaughtStudentsV3() 
            : Promise.resolve();

        studentPromise.then(function() {
            fetch(API_PATH + '?action=get_teacher_classes') // Now fetches from SCHEDULE table
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (result.success && result.classes) {
                        allClassesDataV3 = result.classes;
                        displayFilteredClassesV3();
                    } else {
                        document.getElementById('classList').innerHTML = '<div style="grid-column: 1/-1; text-align: center; padding: 40px;"><p class="text-muted">Tiada kelas dijadualkan dalam Jadual Waktu</p></div>';
                    }
                })
                .catch(function (err) {
                    console.error('Error loading classes:', err);
                });
        });
    }

    function loadTaughtStudentsV3() {
        return fetch(API_PATH + '?action=get_teacher_students')
            .then(function (res) { return res.json(); })
            .then(function (result) {
                if (result.success && result.students) {
                    var uniqueStudents = [];
                    var studentIds = new Set();
                    result.students.forEach(function (s) {
                        if (!studentIds.has(s.id)) {
                            studentIds.add(s.id);
                            // Normalize to match expected format: student_id and student_name
                            uniqueStudents.push({
                                student_id: s.id,
                                student_name: s.full_name
                            });
                        }
                    });
                    taughtStudentsForFilterV3 = uniqueStudents;

                    // Populate filter checklist
                    var container = document.getElementById('classFilterChecklist');
                    if (container) {
                        var html = '';
                        if (uniqueStudents.length === 0) {
                            html = '<p class="text-muted text-center small">Tiada pelajar.</p>';
                        } else {
                            uniqueStudents.forEach(function (s) {
                                html += `<div class="form-check" style="margin-bottom: 5px;">
                                            <input class="form-check-input" type="checkbox" value="${s.student_id}" id="filter_student_${s.student_id}">
                                            <label class="form-check-label small" for="filter_student_${s.student_id}" style="cursor: pointer;">
                                                ${s.student_name}
                                            </label>
                                         </div>`;
                            });
                        }
                        container.innerHTML = html;
                    }
                }
            });
    }

    function toggleClassFilterV3() {
        var dd = document.getElementById('classFilterDropdown');
        if (dd.style.display === 'none' || dd.style.display === '') {
            dd.style.display = 'block';
        } else {
            dd.style.display = 'none';
        }
    }

    function applyClassFilterV3() {
        var checked = document.querySelectorAll('#classFilterChecklist input[type="checkbox"]:checked');
        selectedStudentIdsForFilter = [];
        checked.forEach(function(cb) {
            selectedStudentIdsForFilter.push(cb.value);
        });

        // Update button text
        var btn = document.getElementById('classFilterButton');
        if (selectedStudentIdsForFilter.length === 0) {
            btn.innerHTML = '<span>👥 Semua Pelajar</span>';
        } else {
            btn.innerHTML = '<span>👥 ' + selectedStudentIdsForFilter.length + ' Pelajar Dipilih</span>';
        }

        document.getElementById('classFilterDropdown').style.display = 'none';
        displayFilteredClassesV3();
    }

    function resetClassFilterV3() {
        document.querySelectorAll('#classFilterChecklist input[type="checkbox"]').forEach(cb => cb.checked = false);
        selectedStudentIdsForFilter = [];
        document.getElementById('classFilterButton').innerHTML = '<span>👥 Semua Pelajar</span>';
        document.getElementById('classFilterDropdown').style.display = 'none';
        displayFilteredClassesV3();
    }

    function filterClassesByStudentV3() {
        // Deprecated, replaced by applyClassFilterV3
        displayFilteredClassesV3();
    }

    function displayFilteredClassesV3() {
        var container = document.getElementById('classList');
        var filtered = allClassesDataV3;

        // Filter by selected students if any
        if (selectedStudentIdsForFilter.length > 0) {
            filtered = filtered.filter(function(c) {
                // Check if class is assigned to any of the selected students
                // Assuming c.student_id exists (for 1-on-1) or we check enrollment/subject
                // For V3 schedule, usually student_id is present if specific.
                // If c.student_id is null (group class), we might show it if subject matches? 
                // Let's assume strict filtering: if student_id matches one of selected.
                // Or if it's a group class, maybe we can't filter easily without more data.
                // For now: Filter by student_id
                if (c.student_id) {
                    return selectedStudentIdsForFilter.includes(c.student_id.toString());
                }
                return false; // Hide if no student_id and filter is active (safe default)
            });
        }

        if (filtered.length === 0) {
            container.innerHTML = '<div style="grid-column: 1/-1; text-align: center; padding: 20px;"><p class="text-muted">Tiada kelas dijumpai untuk kriteria ini.</p></div>';
            return;
        }

        var html = '';
        filtered.forEach(function (c) {
            var dateVal = c.schedule_date || c.class_date; // Handle both fields just in case
            var isUpcoming = new Date(dateVal + 'T' + c.start_time) > new Date();
            var statusBadge = isUpcoming ? '<span class="badge badge-success">Akan Datang</span>' : '<span class="badge badge-secondary">Selesai</span>';

            // Check Link
            var hasLink = c.join_link && c.join_link.trim() !== '';
            var linkHtml = '';

            if (hasLink) {
                linkHtml = '<a href="' + c.join_link + '" target="_blank" class="btn btn-outline-success btn-block" style="margin-bottom: 10px; border-radius: 10px;">🔗 Sertai Kelas</a>';
            } else {
                linkHtml = '<div class="alert alert-warning p-2 text-center small mb-2" style="border-radius: 10px;">⚠️ Sila masukkan pautan kelas</div>';
            }

            html += '<div class="card"><div class="card-body">';
            html += '<div style="display: flex; justify-content: space-between; margin-bottom: 10px;">';
            html += statusBadge;
            html += '<span class="text-muted" style="font-size: 0.9rem;">' + formatDate(dateVal) + '</span></div>';
            html += '<h4 style="margin: 0 0 5px 0;">' + c.title + '</h4>';
            html += '<p style="color: var(--primary-color); margin: 0 0 10px 0; font-weight: 500;">' + c.subject + '</p>';
            html += '<p style="font-size: 0.9rem; margin-bottom: 10px;">⏰ ' + formatTime(c.start_time) + ' - ' + formatTime(c.end_time) + '</p>';

            // Show involved students
            var involvedStudentNames = [];
            var involvedIds = [];
            
            // Check student_id (1-on-1)
            if (c.student_id) {
                involvedIds.push(c.student_id.toString());
            }
            
            // Check selected_students (Group)
            if (c.selected_students) {
                var groupIds = [];
                if (Array.isArray(c.selected_students)) {
                    groupIds = c.selected_students;
                } else if (typeof c.selected_students === 'string') {
                    try {
                        groupIds = JSON.parse(c.selected_students);
                    } catch (e) {
                        groupIds = [];
                    }
                }
                groupIds.forEach(function(gid) {
                    if (!involvedIds.includes(gid.toString())) {
                        involvedIds.push(gid.toString());
                    }
                });
            }

            // Map IDs to Names
            involvedIds.forEach(function(uid) {
                var st = taughtStudentsForFilterV3.find(function(s) { return s.student_id == uid; });
                if (st) {
                    involvedStudentNames.push(st.student_name);
                }
            });

            if (involvedStudentNames.length > 0) {
                html += '<div style="background: #f8fafc; padding: 8px 12px; border-radius: 8px; margin-bottom: 15px; font-size: 0.85rem; border: 1px solid #edf2f7;">';
                html += '<div style="display: flex; align-items: start; gap: 8px;">';
                html += '<div style="margin-top: 2px;">🎓</div>';
                html += '<div style="line-height: 1.4; color: #4a5568;">' + involvedStudentNames.join(', ') + '</div>';
                html += '</div></div>';
            } else {
                 html += '<div style="background: #fff9f0; padding: 8px 12px; border-radius: 8px; margin-bottom: 15px; font-size: 0.85rem; border: 1px solid #ffeeba; color: #856404;">';
                 html += '👥 Terbuka kepada semua pelajar</div>';
            }

            html += linkHtml;

            html += '<div style="display: flex; justify-content: space-between; align-items: center; border-top: 1px solid #eee; padding-top: 10px;">';

            // Update Link Button
            html += '<button class="btn btn-sm btn-primary" onclick="showUpdateLinkModalV3(' + c.id + ')">✏️ Kemaskini Pautan</button>';

            html += '</div></div></div>';
        });

        container.innerHTML = html;
    }

    function showUpdateLinkModalV3(id) {
        var cls = allClassesDataV3.find(c => c.id == id);
        if (!cls) return;

        openModal('classModal');
        document.getElementById('classId').value = cls.id;
        document.getElementById('classTitle').value = cls.title;
        document.getElementById('classDate').value = formatDate(cls.schedule_date || cls.class_date);
        document.getElementById('classTime').value = formatTime(cls.start_time) + ' - ' + formatTime(cls.end_time);

        document.getElementById('classJoinLink').value = cls.join_link || '';
        document.getElementById('classDescription').value = cls.description || '';

        // Handle checklist population
        var checkedIds = [];
        if (cls.selected_students && Array.isArray(cls.selected_students)) {
            checkedIds = cls.selected_students;
        } else if (cls.selected_students && typeof cls.selected_students === 'string') {
            try {
                checkedIds = JSON.parse(cls.selected_students);
            } catch (e) {
                checkedIds = [];
            }
        } else if (cls.student_id) {
            checkedIds.push(cls.student_id.toString());
        }

        renderClassStudentChecklistV3(checkedIds);
    }

    function renderClassStudentChecklistV3(checkedIds = []) {
        var container = document.getElementById('classStudentChecklist');
        if (!container) return;
        
        container.innerHTML = '<p class="text-muted small">Memuatkan...</p>';

        // Ensure checkedIds are strings
        checkedIds = checkedIds.map(String);

        if (taughtStudentsForFilterV3.length === 0) {
            fetch(API_PATH + '?action=get_teacher_students')
                .then(res => res.json())
                .then(result => {
                    if (result.success && result.students) {
                        var uniqueStudents = [];
                        var studentIds = new Set();
                        result.students.forEach(function (s) {
                            if (!studentIds.has(s.id)) {
                                studentIds.add(s.id);
                                uniqueStudents.push({
                                    student_id: s.id,
                                    student_name: s.full_name
                                });
                            }
                        });
                        taughtStudentsForFilterV3 = uniqueStudents;
                        _renderChecklistInternalV3(container, taughtStudentsForFilterV3, checkedIds);
                    } else {
                        container.innerHTML = '<p class="text-muted small">Tiada pelajar.</p>';
                    }
                })
                .catch(err => {
                    container.innerHTML = '<p class="text-danger small">Ralat memuatkan pelajar.</p>';
                });
        } else {
            _renderChecklistInternalV3(container, taughtStudentsForFilterV3, checkedIds);
        }
    }

    function _renderChecklistInternalV3(container, students, checkedIds) {
        if (students.length === 0) {
            container.innerHTML = '<p class="text-muted small">Tiada pelajar.</p>';
            return;
        }
        var html = '';
        students.forEach(function (s) {
            var isChecked = checkedIds.includes(s.student_id.toString()) ? 'checked' : '';
            html += `<div class="form-check" style="margin-bottom: 5px;">
                        <input class="form-check-input" type="checkbox" name="selected_students[]" value="${s.student_id}" id="class_student_modal_${s.student_id}" ${isChecked}>
                        <label class="form-check-label small" for="class_student_modal_${s.student_id}" style="cursor: pointer;">
                            ${s.student_name}
                        </label>
                     </div>`;
        });
        container.innerHTML = html;
    }

    function saveClassV3(event) {
        event.preventDefault();
        var formData = new FormData(document.getElementById('classForm'));
        // action is update_class, which maps to updating schedule link/desc
        formData.append('action', 'update_class');

        // Handle selected students
        var selectedStudents = [];
        document.querySelectorAll('#classStudentChecklist input[type="checkbox"]:checked').forEach(function (cb) {
            selectedStudents.push(cb.value);
        });
        
        // Always send as JSON string
        formData.append('selected_students', JSON.stringify(selectedStudents));

        fetch(API_PATH, { method: 'POST', body: formData })
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success) {
                    showNotificationV2('Pautan kelas berjaya dikemaskini', 'success');
                    closeModal('classModal');
                    loadClassesV3();
                } else {
                    showNotificationV2(result.message, 'error');
                }
            })
            .catch(function (err) {
                showNotificationV2('Ralat sambungan', 'error');
            });
    }

    // Delete removed as we only sync from schedule. To delete, go to Schedule tab.
</script>