<?php
// Announcements Tab Component
// Located at: components/teacher/tab-announcements.php
?>
<div id="announcements" 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;">Pengumuman
                    </h4>
                    <p style="margin: 0; color: #6b7280; font-size: 0.95rem; line-height: 1.5;">Hantar makluman penting
                        kepada pelajar atau guru lain.</p>
                </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-bullhorn"></i>
                </div>
                <h3 class="card-title" style="margin: 0; font-size: 1.15rem; font-weight: 700; color: #1a1a2e;">Senarai
                    Pengumuman</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="showAddAnnouncementModalV3()"
                style="background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%); border: none; font-weight: 600; transition: transform 0.2s;">
                <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>