<?php
// Classrooms Tab Component
// Located at: components/teacher/tab-classrooms.php
?>
<div id="classrooms" class="tab-content">
    <div class="card" style="margin-bottom: 25px;">
        <div class="card-body">
            <div class="info-card-badge"
                style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px;">
                <div>
                    <h4 style="margin: 0 0 5px 0; color: var(--primary-color);">🏫 Bilik
                        Darjah Online</h4>
                    <p style="margin: 0; color: #666; font-size: 0.9rem;">Urus kelas dalam
                        talian (Google Meet/Zoom) dan kehadiran pelajar.</p>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title">🏫 Senarai Kelas Online</h3>
            <div style="display: flex; gap: 10px; align-items: center;">
                <select class="form-control form-select" id="classFilterStudent" onchange="filterClassesByStudentV3()"
                    style="width: auto; max-width: 200px;">
                    <option value="all">Semua Pelajar</option>
                    <!-- Populated dynamically via JS -->
                </select>
                <button class="btn btn-primary btn-sm" onclick="showAddClassModalV3()">
                    <span>➕</span> Buat Kelas
                </button>
            </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 MODALS -->
<div class="modal-overlay" id="classModal">
    <div class="modal" style="max-width: 800px;">
        <div class="modal-header">
            <h3 class="modal-title">🏫 Buat Kelas Online</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="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Tajuk Kelas <span class="required">*</span></label>
                        <input type="text" class="form-control" name="title" id="classTitle" required
                            placeholder="cth: Kelas Matematik Online">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Subjek <span class="required">*</span></label>
                        <select class="form-control form-select" name="subject" id="classSubject" required
                            onchange="loadStudentsV2ForSelection('class')">
                            <option value="">Pilih Subjek</option>
                            <?php foreach ($teacherSubjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject); ?>">
                                    <?php echo htmlspecialchars($subject); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Tarikh <span class="required">*</span></label>
                        <input type="date" class="form-control" name="class_date" id="classDate" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Akses Kelas</label>
                        <select class="form-control form-select" id="classAccessType"
                            onchange="toggleStudentSelection('class')">
                            <option value="all">Semua Pelajar</option>
                            <option value="specific">Pelajar Tertentu</option>
                        </select>
                    </div>
                </div>

                <!-- Student Selection Section -->
                <div id="classStudentSelection"
                    style="display: none; margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                    <div
                        style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                        <label class="form-label" style="margin: 0;"><strong>Pilih Pelajar:</strong></label>
                        <div>
                            <button type="button" class="btn btn-sm btn-secondary"
                                onclick="selectAllStudents('class')">Pilih Semua</button>
                            <button type="button" class="btn btn-sm btn-secondary"
                                onclick="deselectAllStudents('class')">Batalkan Semua</button>
                        </div>
                    </div>
                    <div style="max-height: 150px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px; padding: 10px; background: white;"
                        id="classStudentList">
                        <p class="text-muted text-center">Sila pilih subjek terlebih dahulu</p>
                    </div>
                </div>

                <div class="form-row" style="grid-template-columns: 1fr 1fr; margin-top: 15px;">
                    <div class="form-group">
                        <label class="form-label">Masa Mula <span class="required">*</span></label>
                        <input type="time" class="form-control" name="start_time" id="classStartTime" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Masa Tamat</label>
                        <input type="time" class="form-control" name="end_time" id="classEndTime">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Pautan Sertai (Zoom/Google Meet)</label>
                    <input type="url" class="form-control" name="join_link" id="classJoinLink"
                        placeholder="https://zoom.us/j/...">
                </div>

                <div class="form-group">
                    <label class="form-label">Penerangan</label>
                    <textarea class="form-control" name="description" id="classDescription" rows="3"
                        placeholder="Penerangan kelas..."></textarea>
                </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 Kelas</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 = [];

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

        // Load students for filter first if not loaded
        if (taughtStudentsForFilterV3.length === 0) {
            loadTaughtStudentsV3();
        }

        fetch(API_PATH + '?action=get_teacher_classes')
            .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;"><p class="text-muted">Tiada kelas dijadualkan</p><button class="btn btn-primary" onclick="showAddClassModalV3()">Buat Kelas Pertama</button></div>';
                }
            })
            .catch(function (err) {
                console.error('Error loading classes:', err);
            });
    }

    function loadTaughtStudentsV3() {
        fetch(API_PATH + '?action=get_teacher_enrollments&status=Approved')
            .then(function (res) { return res.json(); })
            .then(function (result) {
                if (result.success && result.enrollments) {
                    var uniqueStudents = [];
                    var studentIds = new Set();
                    result.enrollments.forEach(function (e) {
                        if (!studentIds.has(e.student_id)) {
                            studentIds.add(e.student_id);
                            uniqueStudents.push(e);
                        }
                    });
                    taughtStudentsForFilterV3 = uniqueStudents;

                    // Populate filter
                    var select = document.getElementById('classFilterStudent');
                    if (select) {
                        var html = '<option value="all">Semua Pelajar</option>';
                        uniqueStudents.forEach(function (s) {
                            html += '<option value="' + s.student_id + '">' + s.student_name + '</option>';
                        });
                        select.innerHTML = html;
                    }
                }
            });
    }

    function filterClassesByStudentV3() {
        displayFilteredClassesV3();
    }

    function displayFilteredClassesV3() {
        var studentId = document.getElementById('classFilterStudent').value;
        var container = document.getElementById('classList');

        var filtered = allClassesDataV3;
        if (studentId !== 'all') {
            filtered = allClassesDataV3.filter(function (c) {
                if (!c.selected_students) return true; // Public class
                try {
                    var selected = JSON.parse(c.selected_students);
                    return selected.includes(studentId);
                } catch (e) { return true; }
            });
        }

        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 tapisan ini</p></div>';
            return;
        }

        var html = '';
        filtered.forEach(function (c) {
            var isUpcoming = new Date(c.class_date + 'T' + c.start_time) > new Date();
            var statusBadge = isUpcoming ? '<span class="badge badge-success">Akan Datang</span>' : '<span class="badge badge-secondary">Selesai</span>';
            var studentCount = c.selected_students ? JSON.parse(c.selected_students).length : 'Semua';

            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(c.class_date) + '</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>';

            if (c.join_link) {
                html += '<a href="' + c.join_link + '" target="_blank" class="btn btn-outline-primary btn-block" style="margin-bottom: 10px;">🔗 Sertai Kelas</a>';
            }

            html += '<div style="display: flex; justify-content: space-between; align-items: center; border-top: 1px solid #eee; padding-top: 10px;">';
            html += '<button class="btn btn-sm btn-link" onclick="viewClassStudentsV3(' + c.id + ', \'' + (c.title) + '\')">👥 ' + (studentCount === 'Semua' ? 'Semua' : studentCount) + ' Pelajar</button>';
            html += '<button class="btn btn-sm btn-danger" onclick="deleteClassV3(' + c.id + ')">🗑️</button>';
            html += '</div></div></div>';
        });

        container.innerHTML = html;
    }

    function showAddClassModalV3() {
        openModal('classModal');
        var classForm = document.getElementById('classForm');
        var classId = document.getElementById('classId');
        if (classForm) classForm.reset();
        if (classId) classId.value = '';
    }

    function saveClassV3(event) {
        event.preventDefault();
        var formData = new FormData(document.getElementById('classForm'));
        var id = document.getElementById('classId').value;
        formData.append('action', id ? 'update_class' : 'add_class'); // Handle update if needed later

        // Handle specific students
        var accessType = document.getElementById('classAccessType').value;
        if (accessType === 'specific') {
            var selectedStudents = [];
            document.querySelectorAll('#classStudentList input[type="checkbox"]:checked').forEach(function (cb) {
                selectedStudents.push(cb.value);
            });
            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('Kelas berjaya disimpan', 'success');
                    closeModal('classModal');
                    loadClassesV3();
                } else {
                    showNotificationV2(result.message, 'error');
                }
            })
            .catch(function (err) {
                showNotificationV2('Ralat sambungan', 'error');
            });
    }

    function deleteClassV3(id) {
        // Get portal theme color
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

        Swal.fire({
            title: 'Padam Kelas?',
            text: 'Kelas ini akan dipadamkan secara kekal.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: themeColor,
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Padam',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_class');
                formData.append('id', id);

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

    function viewClassStudentsV3(classId, classTitle) {
        document.getElementById('classDetailTitle').textContent = classTitle;
        var list = document.getElementById('classStudentsList');
        list.innerHTML = '<p class="text-center text-muted">Memuatkan...</p>';
        openModal('classStudentsModal');

        // Find class from memory
        var cls = allClassesDataV3.find(c => c.id == classId);
        if (!cls) {
            list.innerHTML = '<p class="text-center text-danger">Kelas data tidak ditemui</p>';
            return;
        }

        if (!cls.selected_students) {
            list.innerHTML = '<p class="text-center text-success">Semua pelajar yang mengambil subjek ' + cls.subject + ' dijemput.</p>';
            return;
        }

        try {
            var studentIds = JSON.parse(cls.selected_students);
            if (studentIds.length === 0) {
                list.innerHTML = '<p class="text-center text-muted">Tiada pelajar khusus dipilih.</p>';
                return;
            }

            // Fetch students details (or use cached enrollments)
            // Simplified: Fetch all teacher's students and match IDs
            fetch(API_PATH + '?action=get_teacher_enrollments&status=Approved')
                .then(r => r.json())
                .then(res => {
                    if (res.success && res.enrollments) {
                        var matched = res.enrollments.filter(e => studentIds.includes(e.student_id));
                        // Deduplicate by student name/id
                        var unique = [];
                        var seen = new Set();
                        matched.forEach(m => {
                            if (!seen.has(m.student_id)) {
                                seen.add(m.student_id);
                                unique.push(m);
                            }
                        });

                        if (unique.length > 0) {
                            var html = '<ul class="list-group">';
                            unique.forEach(s => {
                                html += '<li class="list-group-item">' + s.student_name + '</li>';
                            });
                            html += '</ul>';
                            list.innerHTML = html;
                        } else {
                            list.innerHTML = '<p class="text-center text-muted">Tiada data pelajar ditemui.</p>';
                        }
                    }
                });

        } catch (e) {
            list.innerHTML = '<p class="text-center text-danger">Ralat data.</p>';
        }
    }
</script>