<?php
/**
 * حارس لمنع تكرار إغلاق الهيكل وإضافة السكربتات مرتين
 */
if (defined('MTE_ADMIN_LAYOUT_FOOTER_RENDERED')) {
    return;
}
define('MTE_ADMIN_LAYOUT_FOOTER_RENDERED', true);
?>

        </div> <!-- /.app-content -->
    </main> <!-- /.app-main -->

    <!--begin::Footer-->
    <footer class="app-footer">
        <div class="float-end d-none d-sm-inline">
            <?= __('admin.powered_by', 'MTEngine') ?>
        </div>
        <strong>
            <?= __('admin.panel_title', 'MTEngine Admin Panel') ?> &copy; <?= date('Y') ?>
        </strong>
    </footer>
    <!--end::Footer-->

</div> <!-- /.app-wrapper -->
<script>
(function () {

    const dropdown = document.getElementById('notificationsDropdown');
    const list     = document.getElementById('notifications-list');
    if (!dropdown || !list) return;

    const csrfToken = '<?= \Core\System\Csrf::token() ?>';

    function updateBadge(count) {
        const existing = document.querySelector('.notification-badge');
        if (count > 0) {
            if (existing) { existing.textContent = count; }
            else {
                const icon = document.querySelector('.notification-icon');
                if (icon) {
                    const b = document.createElement('span');
                    b.className = 'notification-badge';
                    b.textContent = count;
                    icon.appendChild(b);
                }
            }
        } else {
            if (existing) existing.remove();
        }
    }

    function loadNotifications() {
        list.innerHTML = '<div class="text-center py-3 text-muted"><span class="spinner-border spinner-border-sm"></span></div>';

        fetch('/admin/notifications/unread', { credentials: 'same-origin' })
            .then(r => r.ok ? r.json() : [])
            .then(data => {
                if (!data.length) {
                    list.innerHTML = '<div class="text-center py-3 text-muted"><?= __('admin.no_notifications', 'No notifications') ?></div>';
                    return;
                }
                list.innerHTML = '';
                data.forEach(n => {
                    const item = document.createElement('div');
                    item.className = 'dropdown-item d-flex justify-content-between align-items-start';

                    item.innerHTML = `
                        <div>
                            <div class="fw-bold">${n.title}</div>
                            <small class="text-muted">${n.created_at}</small>
                        </div>
                        <button class="btn btn-sm btn-link text-success notif-read-btn" data-id="${n.id}">✓</button>`;

                    item.addEventListener('click', () => {
                        window.location.href = n.link || ('/admin/notifications/show/' + n.id);
                    });

                    item.querySelector('.notif-read-btn').addEventListener('click', e => {
                        e.preventDefault();
                        e.stopPropagation();
                        fetch('/admin/notifications/read-from-dropdown/' + n.id, {
                            method: 'POST',
                            credentials: 'same-origin',
                            headers: { 'X-CSRF-TOKEN': csrfToken }
                        }).then(() => {
                            item.remove();
                            fetch('/admin/notifications/unread-count', { credentials: 'same-origin' })
                                .then(r => r.json())
                                .then(d => updateBadge(d.count || 0))
                                .catch(() => {});
                        }).catch(() => {});
                    });

                    list.appendChild(item);
                });
            })
            .catch(() => {
                list.innerHTML = '<div class="text-center py-3 text-muted"><?= __('admin.no_notifications', 'No notifications') ?></div>';
            });
    }

    dropdown.addEventListener('show.bs.dropdown', loadNotifications);

})();
</script>
<script>
(function () {

    let lastCount = null;

    const audio = new Audio('/admin/assets/sounds/notification.mp3');
    audio.volume = 0.6;

    function updateTeamBadge(count) {
        const badge = document.getElementById('nav-msg-badge');
        if (!badge) return;
        badge.textContent = count > 0 ? Math.min(99, count) : '';
        badge.style.display = count > 0 ? '' : 'none';
    }

    function checkNotifications() {

        fetch('/admin/notifications/unread-count')
            .then(r => r.json())
            .then(data => {
                const existing = document.querySelector('.notification-badge');
                if (data.count > 0) {
                    if (existing) existing.textContent = data.count;
                    else {
                        const icon = document.querySelector('.notification-icon');
                        if (icon) { const b = document.createElement('span'); b.className='notification-badge'; b.textContent = data.count; icon.appendChild(b); }
                    }
                } else if (existing) { existing.remove(); }
                if (lastCount !== null && data.count > lastCount) { audio.play().catch(() => {}); }
                lastCount = data.count;
            })
            .catch(() => {});

        fetch('/admin/team/messages/unread-count')
            .then(r => r.json())
            .then(data => updateTeamBadge(parseInt(data.unread || 0)))
            .catch(() => {});
    }

    // أول فحص بعد التحميل
    checkNotifications();

    // فحص دوري كل 15 ثانية (خفيف جداً)
    setInterval(checkNotifications, 15000);

})();
</script>

<!-- Scripts -->

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.min.js"></script>
<script src="/admin/assets/js/adminlte.js"></script>

</body>
</html>
