<?php
// Announcements Tab Component
// Located at: components/teacher/tab-announcements.php
?>
<div id="announcements" 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);">📢 Pengumuman
                    </h4>
                    <p style="margin: 0; color: #666; font-size: 0.9rem;">Hantar makluman
                        penting kepada pelajar atau guru lain.</p>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title">📢 Senarai Pengumuman</h3>
            <button class="btn btn-primary btn-sm" onclick="showAddAnnouncementModalV3()">
                <span>➕</span> Buat Pengumuman
            </button>
        </div>
        <div class="card-body">
            <div id="announcementsList" style="display: flex; flex-direction: column; gap: 15px;">
                <p class="text-center text-muted">Memuatkan pengumuman...</p>
            </div>
        </div>
    </div>
</div>

<!-- ANNOUNCEMENT MODALS -->
<div class="modal-overlay" id="announcementModal">
    <div class="modal" style="max-width: 650px;">
        <div class="modal-header">
            <h3 class="modal-title">📢 Buat Pengumuman</h3>
            <button class="modal-close" onclick="closeModal('announcementModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="announcementForm" onsubmit="saveAnnouncementV3(event)">
                <input type="hidden" name="id" id="announcementId">

                <div class="form-group">
                    <label class="form-label">Tajuk <span class="required">*</span></label>
                    <input type="text" class="form-control" name="title" id="announcementTitle" required
                        placeholder="cth: Pengumuman Penting">
                </div>

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Kategori <span class="required">*</span></label>
                        <select class="form-control form-select" name="category" id="announcementCategory" required>
                            <option value="Umum">Umum</option>
                            <option value="Akademik">Akademik</option>
                            <option value="Aktiviti">Aktiviti</option>
                            <option value="Lain-lain">Lain-lain</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Sasaran <span class="required">*</span></label>
                        <select class="form-control form-select" name="target_audience" id="announcementTarget"
                            required>
                            <option value="Semua">Semua (Guru & Pelajar)</option>
                            <option value="Guru Sahaja">Guru Sahaja</option>
                            <option value="Pelajar">Pelajar Sahaja</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Priority</label>
                    <select class="form-control form-select" name="priority" id="announcementPriority">
                        <option value="Normal">Normal</option>
                        <option value="Penting">Penting</option>
                        <option value="Urgent">Urgent</option>
                    </select>
                </div>

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

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

<!-- Edit Announcement Modal -->
<div class="modal-overlay" id="editAnnouncementModal">
    <div class="modal" style="max-width: 600px;">
        <div class="modal-header">
            <h3 class="modal-title">✏️ Kemaskini Pengumuman</h3>
            <button class="modal-close" onclick="closeModal('editAnnouncementModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="editAnnouncementForm" onsubmit="updateAnnouncementV3(event)">
                <input type="hidden" name="id" id="editAnnouncementId">

                <div class="form-group">
                    <label class="form-label">Tajuk <span class="required">*</span></label>
                    <input type="text" class="form-control" name="title" id="editAnnouncementTitle" required>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div class="form-group">
                        <label class="form-label">Sasaran <span class="required">*</span></label>
                        <select class="form-control form-select" name="target_audience" id="editAnnouncementTarget"
                            required>
                            <option value="Semua">Semua</option>
                            <option value="Guru Sahaja">Guru Sahaja</option>
                            <option value="Pelajar">Pelajar Sahaja</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Priority</label>
                        <select class="form-control form-select" name="priority" id="editAnnouncementPriority">
                            <option value="Normal">Normal</option>
                            <option value="Penting">Penting</option>
                            <option value="Urgent">Urgent</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Kandungan <span class="required">*</span></label>
                    <textarea class="form-control" name="content" id="editAnnouncementContent" rows="5"
                        required></textarea>
                </div>

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

<script>
    // Announcements Logic V3

    function loadAnnouncementsV3() {
        console.log('Loading Announcements V3...');
        fetch(API_PATH + '?action=get_announcements')
            .then(function (response) { return response.json(); })
            .then(function (result) {
                var container = document.getElementById('announcementsList');
                if (result.success && result.announcements && result.announcements.length > 0) {
                    var html = '';
                    result.announcements.forEach(function (a) {
                        var isOwner = (parseInt(a.teacher_id) === CURRENT_USER_ID);
                        var priorityClass = 'badge-info';
                        if (a.priority === 'High' || a.priority === 'Urgent') priorityClass = 'badge-danger';
                        if (a.priority === 'Medium' || a.priority === 'Penting') priorityClass = 'badge-warning';

                        var actionsHtml = '';
                        if (isOwner) {
                            // Encode content to safely pass as JS arguments
                            var titleEnc = encodeURIComponent(a.title);
                            var contentEnc = encodeURIComponent(a.content);
                            actionsHtml = '<div class="announcement-actions" style="margin-top: 10px; display: flex; gap: 8px;">' +
                                '<button class="btn btn-sm btn-outline-primary" style="padding: 4px 10px; font-size: 12px;" onclick="openEditAnnouncementModalV3(' + a.id + ', \'' + titleEnc + '\', \'' + contentEnc + '\', \'' + a.priority + '\', \'' + a.target_audience + '\')">✏️ Edit</button>' +
                                '<button class="btn btn-sm btn-outline-danger" style="padding: 4px 10px; font-size: 12px;" onclick="deleteAnnouncementV3(' + a.id + ')">🗑️ Hapus</button>' +
                                '</div>';
                        }

                        html += '<div class="card" style="margin-bottom: 15px; border-radius: 12px; overflow: hidden; border-left: 4px solid ' + (isOwner ? 'var(--primary-color)' : '#eee') + ';">' +
                            '<div class="card-body" style="padding: 15px;">' +
                            '<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">' +
                            '<span class="badge ' + priorityClass + '" style="font-size: 10px;">' + (a.priority || 'Normal') + '</span>';

                        if (a.target_audience && a.target_audience !== 'Semua') {
                            html += '<span class="badge badge-secondary" style="font-size: 10px; margin-left: 5px;">' + a.target_audience + '</span>';
                        }

                        html += '<small class="text-muted">' + formatDate(a.created_at) + '</small>' +
                            '</div>' +
                            '<h4 style="margin: 0 0 10px 0; color: var(--dark-color); font-size: 16px;">' + a.title + '</h4>' +
                            '<p style="margin: 0; color: #666; font-size: 14px; line-height: 1.5;">' + a.content + '</p>' +
                            '<div style="margin-top: 12px; display: flex; justify-content: justify-content; align-items: center;">' +
                            '<div style="display: flex; align-items: center; gap: 5px;">' +
                            '<div style="width: 24px; height: 24px; background: #f0f2f5; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px;">' + (a.profile_emoji || '👤') + '</div>' +
                            '<small style="color: #888;">' + (a.teacher_name || 'Admin') + '</small>' +
                            '</div>' +
                            '</div>' +
                            actionsHtml +
                            '</div></div>';
                    });
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<div class="empty-state" style="padding: 40px 20px; text-align: center;">' +
                        '<div style="font-size: 40px; margin-bottom: 10px; opacity: 0.5;">📢</div>' +
                        '<p class="text-muted">Tiada pengumuman buat masa ini</p>' +
                        '</div>';
                }
            })
            .catch(function (err) {
                console.error('Error loading announcements:', err);
                var container = document.getElementById('announcementsList');
                if (container) container.innerHTML = '<div class="text-center p-4 text-danger">Gagal memuatkan pengumuman</div>';
            });
    }

    function showAddAnnouncementModalV3() {
        openModal('announcementModal');
        var announcementForm = document.getElementById('announcementForm');
        var announcementId = document.getElementById('announcementId');
        if (announcementForm) announcementForm.reset();
        if (announcementId) announcementId.value = '';
    }

    function saveAnnouncementV3(event) {
        event.preventDefault();
        var formData = new FormData(document.getElementById('announcementForm'));
        formData.append('action', 'add_announcement');

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

    function openEditAnnouncementModalV3(id, titleEncoded, contentEncoded, priority, target) {
        document.getElementById('editAnnouncementId').value = id;
        document.getElementById('editAnnouncementTitle').value = decodeURIComponent(titleEncoded);
        document.getElementById('editAnnouncementContent').value = decodeURIComponent(contentEncoded);
        document.getElementById('editAnnouncementPriority').value = priority;
        document.getElementById('editAnnouncementTarget').value = target;

        openModal('editAnnouncementModal');
    }

    function updateAnnouncementV3(event) {
        event.preventDefault();
        var formData = new FormData(document.getElementById('editAnnouncementForm'));
        formData.append('action', 'update_announcement');

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

    function deleteAnnouncementV3(id) {
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';
        Swal.fire({
            title: 'Hapus Pengumuman?',
            text: 'Adakah anda pasti ingin menghapus pengumuman ini? Tindakan ini tidak boleh dibatalkan.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: themeColor,
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Hapus',
            cancelButtonText: 'Batal',
            borderRadius: '15px',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                var formData = new FormData();
                formData.append('action', 'delete_announcement');
                formData.append('id', id);

                fetch(API_PATH, { method: 'POST', body: formData })
                    .then(function (response) { return response.json(); })
                    .then(function (result) {
                        if (result.success) {
                            showNotificationV2('Pengumuman berjaya dihapus', 'success');
                            loadAnnouncementsV3();
                        } else {
                            showNotificationV2(result.message, 'error');
                        }
                    })
                    .catch(function (err) {
                        showNotificationV2('Ralat sambungan', 'error');
                    });
            }
        });
    }
</script>