<?php
// Forum Tab Component
// Located at: components/teacher/tab-forum.php
?>
<div id="forum" 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;">Forum
                        Perbincangan & Semakan Tugasan</h4>
                    <p style="margin: 0; color: #6b7280; font-size: 0.95rem; line-height: 1.5;">Ruang interaksi antara
                        tutor dan pelajar untuk sesi soal jawab dan perkongsian ilmu secara masa nyata.</p>
                </div>
                <div class="d-none d-md-block">
                    <div
                        style="background: rgba(102, 126, 234, 0.05); padding: 10px 20px; border-radius: 12px; border: 1px dashed rgba(102, 126, 234, 0.3);">
                        <span style="color: var(--primary-color); font-weight: 600; font-size: 0.85rem;">Status: Aktif
                            🟢</span>
                    </div>
                </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-folder-open"></i>
                </div>
                <h3 class="card-title" style="margin: 0; font-size: 1.15rem; font-weight: 700; color: #1a1a2e;">Senarai
                    Topik Perbincangan</h3>
            </div>
            <button class="btn btn-primary btn-sm rounded-pill px-4 py-2 shadow-sm d-flex align-items-center gap-2"
                onclick="showAddForumModalV3()"
                style="background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%); border: none; font-weight: 600; transition: transform 0.2s;">
                <span>➕</span> Topik Baru
            </button>
        </div>
        <div class="card-body" style="padding: 25px;">
            <div id="forumList" style="display: flex; flex-direction: column; gap: 20px;">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Memuatkan perbincangan...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- FORUM MODALS -->
<div class="modal-overlay" id="forumModal">
    <div class="modal" style="max-width: 750px;">
        <div class="modal-header">
            <h3 class="modal-title">💬 Tambah Forum</h3>
            <button class="modal-close" onclick="closeModal('forumModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="forumForm" onsubmit="saveForumV3(event)">
                <input type="hidden" name="id" id="forumId">

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Tajuk <span class="required">*</span></label>
                        <input type="text" class="form-control" name="title" id="forumTitle" required
                            placeholder="cth: Soalan Matematik">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Subjek <span class="required">*</span></label>
                        <select class="form-control form-select" name="subject" id="forumSubject" required
                            onchange="loadStudentsV2ForSelection('forum')">
                            <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">Sasaran</label>
                        <select class="form-control form-select" name="target_audience" id="forumTarget"
                            onchange="toggleStudentSelection('forum')">
                            <option value="all">Semua (Guru & Pelajar)</option>
                            <option value="students">Pelajar Saya Sahaja</option>
                            <option value="teachers">Guru Sahaja</option>
                            <option value="specific">Pelajar Tertentu (Checklist)</option>
                        </select>
                    </div>

                    <!-- Student Selection Section for Forum (Removed intermediate step) -->
                </div>

                <!-- Student Selection Section -->
                <div id="forumStudentSelection"
                    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('forum')">Pilih Semua</button>
                            <button type="button" class="btn btn-sm btn-secondary"
                                onclick="deselectAllStudents('forum')">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="forumStudentList">
                        <p class="text-muted text-center">Sila pilih subjek terlebih dahulu</p>
                    </div>
                </div>

                <div class="form-group" style="margin-top: 15px;">
                    <label class="form-label">Pautan Rujukan (Video/Dokumen)</label>
                    <input type="url" class="form-control" name="link" id="forumLink"
                        placeholder="https://youtube.com/... atau https://docs.google.com/...">
                </div>

                <div class="form-group" style="margin-top: 15px;">
                    <label class="form-label">Lampiran (Imej/PDF)</label>
                    <input type="file" class="form-control" name="attachment" id="forumAttachment"
                        accept="image/jpeg,image/png,application/pdf">
                    <small class="text-muted" style="font-size: 0.8rem;">Pilihan: Muat naik gambar atau document PDF
                        untuk rujukan pelajar.</small>
                </div>

                <div class="form-group">
                    <label class="form-label">Kandungan <span class="required">*</span></label>
                    <textarea class="form-control" name="content" id="forumContent" rows="5" required
                        placeholder="Tulis soalan atau topik..."></textarea>
                </div>

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

<script>
    // Forum Logic V3
    function loadForumV3() {
        console.log('Loading Forum V3...');
        fetch(API_PATH + '?action=get_teacher_forums')
            .then(function (response) { return response.json(); })
            .then(function (result) {
                var container = document.getElementById('forumList');
                if (result.success && result.forums && result.forums.length > 0) {
                    var html = '';
                    result.forums.forEach(function (f) {
                        html += `<div class="card hover-effect" style="border-radius: 16px; border: 1px solid #f0f0f0; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); margin-bottom: 5px; box-shadow: 0 4px 12px rgba(0,0,0,0.03);">`;
                        html += `<div class="card-body" style="padding: 20px;">`;
                        html += `    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px;">`;
                        html += `        <div style="display: flex; align-items: center; gap: 12px;">`;
                        html += `            <div style="width: 45px; height: 45px; background: #f3f4ff; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; color: var(--primary-color);">💬</div>`;
                        html += `            <div>`;
                        html += `                <h4 style="margin: 0; font-size: 1.1rem; color: #1a1a2e; font-weight: 700;">${f.title}</h4>`;
                        html += `                <small style="color: #6b7280;">Sertai perbincangan sekarang</small>`;
                        html += `            </div>`;
                        html += `        </div>`;
                        html += `        <span class="badge" style="background: rgba(102, 126, 234, 0.1); color: var(--primary-color); border: 1px solid rgba(102, 126, 234, 0.2); padding: 5px 12px; border-radius: 20px; font-weight: 600; font-size: 0.75rem;">${f.subject}</span>`;
                        html += `    </div>`;
                        html += `    <p style="color: #4b5563; font-size: 0.92rem; line-height: 1.6; margin-bottom: 15px;">${f.content ? (f.content.length > 150 ? f.content.substring(0, 150) + '...' : f.content) : 'Tiada kandungan...'}</p>`;
                        html += `    <div style="display: flex; justify-content: space-between; align-items: center; padding-top: 15px; border-top: 1px dashed #f0f0f0;">`;
                        html += `        <div style="display: flex; align-items: center; gap: 15px;">`;
                        html += `            <small class="text-muted" style="display: flex; align-items: center; gap: 5px;"><i class="far fa-calendar-alt"></i> ${formatDate(f.created_at)}</small>`;
                        html += `            <small class="text-muted" style="display: flex; align-items: center; gap: 5px;"><i class="far fa-comment-dots"></i> Respon: Aktif</small>`;
                        html += `        </div>`;
                        html += `        <div style="display: flex; gap: 10px;">`;
                        html += `            <a href="forum_view.php?id=${f.id}" class="btn btn-outline-primary btn-sm rounded-pill px-4" style="border-color: rgba(102, 126, 234, 0.4); font-weight: 600; color: var(--primary-color);">Buka Forum ➔</a>`;
                        html += `            <button onclick="deleteForumV3(${f.id})" class="btn btn-outline-danger btn-sm rounded-circle" style="width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;"><i class="fas fa-trash-alt"></i></button>`;
                        html += `        </div>`;
                        html += `    </div>`;
                        html += `</div></div>`;
                    });
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<div style="text-align: center; padding: 30px;"><p class="text-muted">Tiada forum belum dibuat</p><p class="text-muted small">Mulakan perbincangan dengan pelajar anda!</p></div>';
                }
            })
            .catch(function (err) {
                console.error('Error loading forum:', err);
                var container = document.getElementById('forumList');
                if (container) container.innerHTML = '<div class="text-center p-4 text-danger">Gagal memuatkan forum. Sila cuba lagi.</div>';
            });
    }

    function showAddForumModalV3() {
        openModal('forumModal');
        var forumForm = document.getElementById('forumForm');
        var forumId = document.getElementById('forumId');
        if (forumForm) forumForm.reset();
        if (forumId) forumId.value = '';

        // Reset specialized visibility if needed
        var studentSelectionContainer = document.getElementById('forumStudentSelectionContainer');
        var selectionDiv = document.getElementById('forumStudentSelection');
        if (studentSelectionContainer) studentSelectionContainer.style.display = 'none';
        if (selectionDiv) selectionDiv.style.display = 'none';
    }

    function saveForumV3(event) {
        event.preventDefault();
        var formData = new FormData(document.getElementById('forumForm'));
        var id = document.getElementById('forumId').value;
        formData.append('action', id ? 'update_forum' : 'add_forum');

        // Handle specific students logic
        var targetAudience = document.getElementById('forumTarget').value;
        if (targetAudience === 'specific') {
            // Direct checklist access for 'specific' target
            var selectedStudents = [];
            document.querySelectorAll('#forumStudentList 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('Forum berjaya disimpan', 'success');
                    closeModal('forumModal');
                    loadForumV3();
                } else {
                    showNotificationV2(result.message, 'error');
                }
            })
            .catch(function (err) {
                showNotificationV2('Ralat sambungan', 'error');
            });
    }

    function deleteForumV3(id) {
        Swal.fire({
            title: 'Adakah anda pasti?',
            text: "Forum ini akan dipadam secara kekal!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Ya, padam!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_forum');
                formData.append('id', id);

                fetch(API_PATH, { method: 'POST', body: formData })
                    .then(function (r) { return r.json(); })
                    .then(function (res) {
                        if (res.success) {
                            showNotificationV2('Forum berjaya dipadam', 'success');
                            loadForumV3();
                        } else {
                            showNotificationV2(res.message, 'error');
                        }
                    })
                    .catch(function (e) {
                        showNotificationV2('Ralat sambungan', 'error');
                    });
            }
        });
    }

    // Shared Student Selection Logic for Forum
    var cachedTeacherStudentsV3 = null;

    function toggleStudentSelection(context) {
        var targetSelect = document.getElementById(context + 'Target');
        var accessSelect = document.getElementById(context + 'AccessType');
        var container = document.getElementById(context + 'StudentSelection');
        var secondaryContainer = document.getElementById(context + 'StudentSelectionContainer');

        var showList = false;

        if (context === 'forum') {
            // For forum, we have Target Audience -> Specific -> Checklist
            var target = targetSelect.value;
            if (target === 'specific') {
                showList = true;
            }
        } else {
            // Modules/Classrooms usually just have AccessType
            if (accessSelect && accessSelect.value === 'specific') {
                showList = true;
            }
        }

        if (showList) {
            container.style.display = 'block';
            loadStudentSelectionListV3(context);
        } else {
            container.style.display = 'none';
        }
    }

    function loadStudentSelectionListV3(context) {
        var listContainer = document.getElementById(context + 'StudentList');
        if (!listContainer) return;

        // Use cached if available
        if (cachedTeacherStudentsV3) {
            renderStudentChecklistV3(cachedTeacherStudentsV3, context);
            return;
        }

        listContainer.innerHTML = '<p class="text-center text-muted">Memuatkan senarai pelajar...</p>';

        fetch(API_PATH + '?action=get_teacher_enrollments&status=Approved')
            .then(function (res) { return res.json(); })
            .then(function (result) {
                if (result.success && result.enrollments) {
                    // Deduplicate
                    var unique = [];
                    var seen = new Set();
                    result.enrollments.forEach(function (e) {
                        if (!seen.has(e.student_id)) {
                            seen.add(e.student_id);
                            unique.push(e);
                        }
                    });
                    cachedTeacherStudentsV3 = unique;
                    renderStudentChecklistV3(unique, context);
                } else {
                    listContainer.innerHTML = '<p class="text-center text-muted">Tiada pelajar dijumpai.</p>';
                }
            })
            .catch(function (err) {
                console.error(err);
                listContainer.innerHTML = '<p class="text-center text-danger">Ralat memuatkan pelajar.</p>';
            });
    }

    function renderStudentChecklistV3(students, context) {
        var listContainer = document.getElementById(context + 'StudentList');
        if (!students || students.length === 0) {
            listContainer.innerHTML = '<p class="text-center text-muted">Tiada pelajar berdaftar.</p>';
            return;
        }

        var html = '';
        students.forEach(function (s) {
            html += `<div class="form-check">
                        <input class="form-check-input" type="checkbox" value="${s.student_id}" id="${context}_student_${s.student_id}">
                        <label class="form-check-label" for="${context}_student_${s.student_id}">
                            ${s.student_name}
                        </label>
                     </div>`;
        });
        listContainer.innerHTML = html;
    }

    function selectAllStudents(context) {
        var container = document.getElementById(context + 'StudentList');
        if (container) {
            container.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = true);
        }
    }

    function deselectAllStudents(context) {
        var container = document.getElementById(context + 'StudentList');
        if (container) {
            container.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
        }
    }

    // Backwards compatibility alias if needed
    window.loadStudentsV2ForSelection = function (ctx) { toggleStudentSelection(ctx); };

</script>