$(function () {
    loadNotifications();
    loadCount();

    setInterval(() => {
        loadNotifications();
        loadCount();
    }, 10000);
});

function loadNotifications() {
    $.get('api/notifications.php?action=list', function (res) {

        let html = '';

        res.data.forEach(n => {
            html += `
<a href="${n.url || '#'}" 
   class="text-decoration-none text-dark"
   onclick="markRead(${n.id})">

    <div class="border-bottom p-2 ${n.is_read==0?'bg-light':''}">
        <strong>${n.title}</strong><br>
        <small>${n.message}</small>
    </div>

</a>`;
        });

        $('#notifList').html(html);
    }, 'json');
}

function loadCount() {
    $.get('api/notifications.php?action=count', function (res) {
        $('#notifCount').text(res.count > 0 ? res.count : '');
    }, 'json');
}
function markRead(id) {
    $.post('api/notifications.php?action=mark_one', { id: id });
}

$('#markAll').click(function () {
    $.post('api/notifications.php?action=mark_read', function () {
        loadNotifications();
        loadCount();
    });
});