<?php
/**
 * Teacher Dashboard - Tugasan (Assignments) Component
 * Add to Modul tab to manage assignments
 */
?>

<!-- Tugasan Section in Modul Tab -->
<div class="card" style="margin-top: 25px;">
    <div class="card-header">
        <h3 class="card-title">📝 Tugasan / Kerja Rumah</h3>
        <button class="btn btn-primary btn-sm" onclick="showAddAssignmentModal()">
            <span>➕</span> Tambah Tugasan
        </button>
    </div>
    <div class="card-body">
        <div id="assignmentsList" style="display: flex; flex-direction: column; gap: 15px;">
            <p class="text-center text-muted">Memuatkan tugasan...</p>
        </div>
    </div>
</div>

<!-- Add/Edit Assignment Modal -->
<div class="modal-overlay" id="assignmentModal" style="display: none !important;">
    <div class="modal" style="max-width: 600px;">
        <div class="modal-header">
            <h3 class="modal-title" id="assignmentModalTitle">➕ Tambah Tugasan Baru</h3>
            <button class="modal-close" onclick="closeModal('assignmentModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="assignmentForm" onsubmit="saveAssignment(event)">
                <input type="hidden" id="assignmentId" name="id">

                <div class="form-row" style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div class="form-group">
                        <label class="form-label">Jenis Tugasan</label>
                        <select class="form-control" name="type" id="assignmentType" required="">
                            <option value="Kerja">📋 Kerja Rumah</option>
                            <option value="Kuiz">📝 Kuiz</option>
                            <option value="Nota Pocket">📒 Nota Pocket</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Tarikh Tamat (Opsional)</label>
                        <input type="date" class="form-control" name="due_date" id="assignmentDueDate">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Tajuk Tugasan <span class="required">*</span></label>
                    <input type="text" class="form-control" name="title" id="assignmentTitle" required=""
                        placeholder="Contoh: Latihan Bab 3 - Pecahan">
                </div>

                <div class="form-group">
                    <label class="form-label">Penerangan</label>
                    <textarea class="form-control" name="description" id="assignmentDescription" rows="3"
                        placeholder="Arahan atau nota untuk pelajar..."></textarea>
                </div>

                <div class="form-group">
                    <label class="form-label">Pautan (Boleh tambah berbilang)</label>
                    <div id="linksContainer">
                        <div class="link-row" style="display: flex; gap: 10px; margin-bottom: 10px;">
                            <input type="text" class="form-control" placeholder="Label (cth: Google Form)"
                                style="flex: 1;">
                            <input type="url" class="form-control" placeholder="https://..." style="flex: 2;">
                            <button type="button" class="btn btn-success btn-sm" onclick="addLinkRow()">+</button>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Pilih Emoji</label>
                    <div id="assignmentEmojiPicker" style="display: flex; flex-wrap: wrap; gap: 8px;">
                        <?php
                        $emojis = ['📝', '📋', '📒', '📖', '✍️', '💡', '🎯', '⭐', '🏆', '📊', '🔬', '🎨', '🎵', '⚽', '📐'];
                        foreach ($emojis as $emoji): ?>
                            <span class="emoji-option" data-emoji="<?php echo $emoji; ?>"
                                onclick="selectAssignmentEmoji(this)"
                                style="cursor: pointer; font-size: 1.5rem; padding: 5px; border-radius: 8px; border: 2px solid transparent; transition: all 0.2s;">
                                <?php echo $emoji; ?>
                            </span>
                        <?php endforeach; ?>
                    </div>
                    <input type="hidden" name="emoji" id="assignmentSelectedEmoji" value="📝">
                </div>

                <div class="form-group" style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary"
                        onclick="closeModal('assignmentModal')">Batal</button>
                    <button type="submit" class="btn btn-primary">💾 Simpan Tugasan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Assignment Modal (with comments) -->
<div class="modal-overlay" id="viewAssignmentModal">
    <div class="modal" style="max-width: 650px;">
        <div class="modal-header">
            <h3 class="modal-title" id="viewAssignmentTitle">📝 Tajuk Tugasan</h3>
            <button class="modal-close" onclick="closeModal('viewAssignmentModal')">×</button>
        </div>
        <div class="modal-body">
            <div id="viewAssignmentContent"></div>

            <!-- Comments Section -->
            <div style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 15px;">
                <h4 style="margin: 0 0 15px 0; color: var(--primary-color);">💬 Komen & Perbincangan</h4>
                <div id="assignmentCommentsList" style="max-height: 250px; overflow-y: auto; margin-bottom: 15px;">
                </div>

                <form onsubmit="submitAssignmentComment(event)" style="display: flex; gap: 10px;">
                    <input type="hidden" id="currentAssignmentId">
                    <input type="text" class="form-control" id="assignmentCommentInput" placeholder="Tulis komen..."
                        style="flex: 1;">
                    <button type="submit" class="btn btn-primary">Hantar</button>
                </form>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeModal('viewAssignmentModal')">Tutup</button>
            <button class="btn btn-warning" id="editAssignmentBtn" onclick="editCurrentAssignment()">✏️ Edit</button>
            <button class="btn btn-danger" id="deleteAssignmentBtn" onclick="deleteCurrentAssignment()">🗑️
                Padam</button>
        </div>
    </div>
</div>

<script>
    var assignmentsData = [];
    var currentAssignment = null;

    // Load assignments on page load
    document.addEventListener('DOMContentLoaded', function () {
        loadAssignments();
    });

    async function loadAssignments() {
        try {
            const response = await fetch('../api.php?action=get_teacher_assignments');
            const result = await response.json();

            if (result.success) {
                assignmentsData = result.assignments || [];
                displayAssignments();
            }
        } catch (error) {
            console.error('Error loading assignments:', error);
        }
    }

    function displayAssignments() {
        const container = document.getElementById('assignmentsList');

        if (!assignmentsData || assignmentsData.length === 0) {
            container.innerHTML = `
            <div style="text-align: center; padding: 40px; color: #888;">
                <div style="font-size: 3rem; margin-bottom: 10px;">📝</div>
                <p>Tiada tugasan. Klik butang di atas untuk tambah.</p>
            </div>`;
            return;
        }

        let html = '';
        assignmentsData.forEach(function (a) {
            const typeColors = {
                'Kuiz': '#f093fb',
                'Kerja': '#667eea',
                'Nota Pocket': '#38ef7d'
            };
            const color = typeColors[a.type] || '#667eea';
            const dueDate = a.due_date ? new Date(a.due_date).toLocaleDateString('ms-MY') : 'Tiada';
            const isPastDue = a.due_date && new Date(a.due_date) < new Date();

            html += `
            <div class="card" style="border-left: 4px solid ${color}; cursor: pointer;" onclick="viewAssignment(${a.id})">
                <div class="card-body" style="padding: 15px;">
                    <div style="display: flex; justify-content: space-between; align-items: start;">
                        <div style="flex: 1;">
                            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 8px;">
                                <span style="font-size: 1.5rem;">${a.emoji || '📝'}</span>
                                <h5 style="margin: 0; color: #333;">${a.title}</h5>
                                <span class="badge" style="background: ${color}; color: white; font-size: 0.75rem;">${a.type}</span>
                            </div>
                            <p style="margin: 0; color: #666; font-size: 0.9rem;">${a.description || 'Tiada penerangan'}</p>
                        </div>
                        <div style="text-align: right; font-size: 0.85rem;">
                            <div style="color: ${isPastDue ? '#e53e3e' : '#666'};">📅 ${dueDate}</div>
                            <div style="color: #888;">💬 ${a.comment_count || 0} komen</div>
                        </div>
                    </div>
                </div>
            </div>`;
        });

        container.innerHTML = html;
    }

    function showAddAssignmentModal() {
        document.getElementById('assignmentForm').reset();
        document.getElementById('assignmentId').value = '';
        document.getElementById('assignmentModalTitle').textContent = '➕ Tambah Tugasan Baru';
        document.getElementById('linksContainer').innerHTML = `
        <div class="link-row" style="display: flex; gap: 10px; margin-bottom: 10px;">
            <input type="text" class="form-control" placeholder="Label (cth: Google Form)" style="flex: 1;">
            <input type="url" class="form-control" placeholder="https://..." style="flex: 2;">
            <button type="button" class="btn btn-success btn-sm" onclick="addLinkRow()">+</button>
        </div>`;
        openModal('assignmentModal');
    }

    function addLinkRow() {
        const container = document.getElementById('linksContainer');
        const row = document.createElement('div');
        row.className = 'link-row';
        row.style.cssText = 'display: flex; gap: 10px; margin-bottom: 10px;';
        row.innerHTML = `
        <input type="text" class="form-control" placeholder="Label" style="flex: 1;">
        <input type="url" class="form-control" placeholder="https://..." style="flex: 2;">
        <button type="button" class="btn btn-danger btn-sm" onclick="this.parentElement.remove()">-</button>`;
        container.appendChild(row);
    }

    function selectAssignmentEmoji(el) {
        document.querySelectorAll('#assignmentEmojiPicker .emoji-option').forEach(opt => {
            opt.style.border = '2px solid transparent';
            opt.style.background = 'transparent';
        });
        el.style.border = '2px solid var(--primary-color)';
        el.style.background = '#f0f4ff';
        document.getElementById('assignmentSelectedEmoji').value = el.dataset.emoji;
    }

    function getLinksFromForm() {
        const rows = document.querySelectorAll('#linksContainer .link-row');
        const links = [];
        rows.forEach(row => {
            const label = row.querySelector('input[type="text"]').value.trim();
            const url = row.querySelector('input[type="url"]').value.trim();
            if (label && url) {
                links.push({ label, url });
            }
        });
        return JSON.stringify(links);
    }

    async function saveAssignment(event) {
        event.preventDefault();

        const formData = new FormData();
        formData.append('action', document.getElementById('assignmentId').value ? 'update_assignment' : 'add_assignment');
        formData.append('id', document.getElementById('assignmentId').value);
        formData.append('title', document.getElementById('assignmentTitle').value);
        formData.append('description', document.getElementById('assignmentDescription').value);
        formData.append('type', document.getElementById('assignmentType').value);
        formData.append('due_date', document.getElementById('assignmentDueDate').value);
        formData.append('emoji', document.getElementById('assignmentSelectedEmoji').value);
        formData.append('links', getLinksFromForm());

        try {
            const response = await fetch('../api.php', { method: 'POST', body: formData });
            const result = await response.json();

            if (result.success) {
                Swal.fire('Berjaya!', result.message, 'success');
                closeModal('assignmentModal');
                loadAssignments();
            } else {
                Swal.fire('Ralat', result.message, 'error');
            }
        } catch (error) {
            console.error('Error:', error);
            Swal.fire('Ralat', 'Gagal menyimpan tugasan', 'error');
        }
    }

    function viewAssignment(id) {
        currentAssignment = assignmentsData.find(a => a.id == id);
        if (!currentAssignment) return;

        document.getElementById('viewAssignmentTitle').innerHTML = `${currentAssignment.emoji || '📝'} ${currentAssignment.title}`;
        document.getElementById('currentAssignmentId').value = id;

        let links = [];
        try { links = JSON.parse(currentAssignment.links || '[]'); } catch (e) { }

        let linksHtml = '';
        if (links.length > 0) {
            linksHtml = '<div style="margin-top: 15px;"><strong>🔗 Pautan:</strong><div style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px;">';
            links.forEach(link => {
                linksHtml += `<a href="${link.url}" target="_blank" class="btn btn-outline-primary btn-sm">${link.label}</a>`;
            });
            linksHtml += '</div></div>';
        }

        document.getElementById('viewAssignmentContent').innerHTML = `
        <div style="display: flex; gap: 15px; margin-bottom: 15px;">
            <span class="badge" style="background: #667eea; color: white;">${currentAssignment.type}</span>
            <span>📅 Tarikh Tamat: ${currentAssignment.due_date || 'Tiada'}</span>
        </div>
        <p style="color: #555;">${currentAssignment.description || 'Tiada penerangan'}</p>
        ${linksHtml}`;

        loadAssignmentComments(id);
        openModal('viewAssignmentModal');
    }

    async function loadAssignmentComments(assignmentId) {
        try {
            const response = await fetch(`../api.php?action=get_assignment_comments&assignment_id=${assignmentId}`);
            const result = await response.json();

            const container = document.getElementById('assignmentCommentsList');
            if (result.success && result.comments && result.comments.length > 0) {
                let html = '';
                result.comments.forEach(c => {
                    const isTeacher = c.user_type === 'teacher';
                    html += `
                    <div style="background: ${isTeacher ? '#f0f4ff' : '#fff'}; padding: 12px; border-radius: 10px; margin-bottom: 10px; border: 1px solid #eee;">
                        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 5px;">
                            <span style="font-size: 1.2rem;">${c.user_emoji || '👤'}</span>
                            <strong style="color: ${isTeacher ? 'var(--primary-color)' : '#333'};">${c.user_name}</strong>
                            <small style="color: #999;">${new Date(c.created_at).toLocaleString('ms-MY')}</small>
                        </div>
                        <p style="margin: 0; color: #555;">${c.content}</p>
                    </div>`;
                });
                container.innerHTML = html;
            } else {
                container.innerHTML = '<p class="text-center text-muted">Tiada komen lagi</p>';
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

    async function submitAssignmentComment(event) {
        event.preventDefault();

        const content = document.getElementById('assignmentCommentInput').value.trim();
        const assignmentId = document.getElementById('currentAssignmentId').value;

        if (!content) return;

        const formData = new FormData();
        formData.append('action', 'add_assignment_comment');
        formData.append('assignment_id', assignmentId);
        formData.append('content', content);

        try {
            const response = await fetch('../api.php', { method: 'POST', body: formData });
            const result = await response.json();

            if (result.success) {
                document.getElementById('assignmentCommentInput').value = '';
                loadAssignmentComments(assignmentId);
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

    function editCurrentAssignment() {
        if (!currentAssignment) return;

        closeModal('viewAssignmentModal');

        document.getElementById('assignmentId').value = currentAssignment.id;
        document.getElementById('assignmentTitle').value = currentAssignment.title;
        document.getElementById('assignmentDescription').value = currentAssignment.description || '';
        document.getElementById('assignmentType').value = currentAssignment.type;
        document.getElementById('assignmentDueDate').value = currentAssignment.due_date || '';
        document.getElementById('assignmentSelectedEmoji').value = currentAssignment.emoji || '📝';
        document.getElementById('assignmentModalTitle').textContent = '✏️ Edit Tugasan';

        // Load links
        let links = [];
        try { links = JSON.parse(currentAssignment.links || '[]'); } catch (e) { }

        const container = document.getElementById('linksContainer');
        container.innerHTML = '';
        if (links.length > 0) {
            links.forEach((link, i) => {
                const row = document.createElement('div');
                row.className = 'link-row';
                row.style.cssText = 'display: flex; gap: 10px; margin-bottom: 10px;';
                row.innerHTML = `
                <input type="text" class="form-control" placeholder="Label" style="flex: 1;" value="${link.label}">
                <input type="url" class="form-control" placeholder="https://..." style="flex: 2;" value="${link.url}">
                <button type="button" class="btn btn-${i === 0 ? 'success' : 'danger'} btn-sm" onclick="${i === 0 ? 'addLinkRow()' : 'this.parentElement.remove()'}">
                    ${i === 0 ? '+' : '-'}
                </button>`;
                container.appendChild(row);
            });
        } else {
            addLinkRow();
        }

        openModal('assignmentModal');
    }

    async function deleteCurrentAssignment() {
        if (!currentAssignment) return;

        const result = await Swal.fire({
            title: 'Padam Tugasan?',
            text: 'Tugasan ini akan dipadam secara kekal.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e53e3e',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Padam',
            cancelButtonText: 'Batal'
        });

        if (result.isConfirmed) {
            const formData = new FormData();
            formData.append('action', 'delete_assignment');
            formData.append('id', currentAssignment.id);

            try {
                const response = await fetch('../api.php', { method: 'POST', body: formData });
                const result = await response.json();

                if (result.success) {
                    Swal.fire('Dipadam!', 'Tugasan telah dipadam.', 'success');
                    closeModal('viewAssignmentModal');
                    loadAssignments();
                } else {
                    Swal.fire('Ralat', result.message, 'error');
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }
    }
</script>