<?php
/**
 * Student Dashboard - Tugasan Saya Component
 * View assignments from enrolled teachers
 */
?>

<!-- Tugasan Saya Section -->
<div class="card" style="margin-top: 25px;">
    <div class="card-header">
        <h3 class="card-title">📝 Tugasan Saya</h3>
    </div>
    <div class="card-body">
        <div id="studentAssignmentsList" style="display: flex; flex-direction: column; gap: 15px;">
            <p class="text-center text-muted">Memuatkan tugasan...</p>
        </div>
    </div>
</div>

<!-- View Assignment Modal (Student) -->
<div class="modal-overlay" id="viewStudentAssignmentModal">
    <div class="modal" style="max-width: 650px;">
        <div class="modal-header">
            <h3 class="modal-title" id="viewStudentAssignmentTitle">📝 Tugasan</h3>
            <button class="modal-close" onclick="closeModal('viewStudentAssignmentModal')">×</button>
        </div>
        <div class="modal-body">
            <div id="viewStudentAssignmentContent"></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="studentAssignmentCommentsList"
                    style="max-height: 250px; overflow-y: auto; margin-bottom: 15px;"></div>

                <form onsubmit="submitStudentAssignmentComment(event)" style="display: flex; gap: 10px;">
                    <input type="hidden" id="currentStudentAssignmentId">
                    <input type="text" class="form-control" id="studentAssignmentCommentInput"
                        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('viewStudentAssignmentModal')">Tutup</button>
        </div>
    </div>
</div>

<script>
    var studentAssignmentsData = [];

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

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

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

    function displayStudentAssignments() {
        const container = document.getElementById('studentAssignmentsList');

        if (!studentAssignmentsData || studentAssignmentsData.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 daripada guru anda.</p>
            </div>`;
            return;
        }

        let html = '';
        studentAssignmentsData.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();
            const isUrgent = a.due_date && (new Date(a.due_date) - new Date()) < 86400000 * 2; // 2 days

            html += `
            <div class="card" style="border-left: 4px solid ${color}; cursor: pointer; ${isUrgent && !isPastDue ? 'animation: pulse 2s infinite;' : ''}" onclick="viewStudentAssignment(${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>
                                ${isPastDue ? '<span class="badge badge-danger">Tamat Tempoh</span>' : ''}
                            </div>
                            <p style="margin: 0 0 5px 0; color: #666; font-size: 0.9rem;">${a.description || 'Tiada penerangan'}</p>
                            <small style="color: #888;">👨‍🏫 ${a.teacher_emoji || ''} ${a.teacher_name || 'Guru'}</small>
                        </div>
                        <div style="text-align: right; font-size: 0.85rem;">
                            <div style="color: ${isPastDue ? '#e53e3e' : isUrgent ? '#f6ad55' : '#666'}; font-weight: ${isPastDue || isUrgent ? 'bold' : 'normal'};">📅 ${dueDate}</div>
                            <div style="color: #888;">💬 ${a.comment_count || 0} komen</div>
                        </div>
                    </div>
                </div>
            </div>`;
        });

        container.innerHTML = html;
    }

    function viewStudentAssignment(id) {
        const assignment = studentAssignmentsData.find(a => a.id == id);
        if (!assignment) return;

        document.getElementById('viewStudentAssignmentTitle').innerHTML = `${assignment.emoji || '📝'} ${assignment.title}`;
        document.getElementById('currentStudentAssignmentId').value = id;

        let links = [];
        try { links = JSON.parse(assignment.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-primary btn-sm">${link.label}</a>`;
            });
            linksHtml += '</div></div>';
        }

        const isPastDue = assignment.due_date && new Date(assignment.due_date) < new Date();

        document.getElementById('viewStudentAssignmentContent').innerHTML = `
        <div style="display: flex; gap: 15px; margin-bottom: 15px; flex-wrap: wrap;">
            <span class="badge" style="background: #667eea; color: white;">${assignment.type}</span>
            <span style="color: ${isPastDue ? '#e53e3e' : '#666'};">📅 Tarikh Tamat: ${assignment.due_date || 'Tiada'} ${isPastDue ? '(Tamat)' : ''}</span>
            <span>👨‍🏫 ${assignment.teacher_emoji || ''} ${assignment.teacher_name}</span>
        </div>
        <p style="color: #555;">${assignment.description || 'Tiada penerangan'}</p>
        ${linksHtml}`;

        loadStudentAssignmentComments(id);
        openModal('viewStudentAssignmentModal');
    }

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

            const container = document.getElementById('studentAssignmentCommentsList');
            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} ${isTeacher ? '(Guru)' : ''}</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. Anda boleh bertanya di sini.</p>';
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

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

        const content = document.getElementById('studentAssignmentCommentInput').value.trim();
        const assignmentId = document.getElementById('currentStudentAssignmentId').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('studentAssignmentCommentInput').value = '';
                loadStudentAssignmentComments(assignmentId);
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }
</script>