<?php
// Forum Tab Component
// Located at: components/teacher/tab-forum.php
?>
<div id="forum" 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);">💬 Forum
                        Perbincangan</h4>
                    <p style="margin: 0; color: #666; font-size: 0.9rem;">Ruang interaksi
                        antara guru dan pelajar untuk sesi soal jawab.</p>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title">💬 Forum & Soalan</h3>
            <button class="btn btn-primary btn-sm" onclick="showAddForumModalV3()">
                <span>➕</span> Topik Baru
            </button>
        </div>
        <div class="card-body">
            <div id="forumList" style="display: flex; flex-direction: column; gap: 15px;">
                <p class="text-center text-muted">Memuatkan forum...</p>
            </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</option>
                        </select>
                    </div>

                    <!-- Student Selection Section for Forum -->
                    <div class="form-group" id="forumStudentSelectionContainer" style="display: none;">
                        <label class="form-label">Akses Forum</label>
                        <select class="form-control form-select" id="forumAccessType"
                            onchange="toggleStudentSelection('forum')">
                            <option value="all_students">Semua Pelajar Saya</option>
                            <option value="specific_students">Pelajar Tertentu</option>
                        </select>
                    </div>
                </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">
                    <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"><div class="card-body">';
                        html += '<div style="display: flex; justify-content: space-between;">';
                        html += '<h4 style="margin: 0 0 5px 0;">' + f.title + '</h4>';
                        html += '<span class="badge badge-info">' + f.subject + '</span></div>';
                        html += '<p class="text-muted" style="font-size: 0.9rem;">' + (f.content ? f.content.substring(0, 150) + '...' : '') + '</p>';
                        html += '<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px;">';
                        html += '<small class="text-muted">📅 ' + formatDate(f.created_at) + '</small>';
                        html += '<a href="forum_view.php?id=' + f.id + '" class="btn btn-outline-primary btn-sm">Lihat Perbincangan ➔</a>';
                        html += '</div></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') {
            var forumAccessType = document.getElementById('forumAccessType').value;
            if (forumAccessType === 'specific_students') {
                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');
            });
    }
</script>