<?php 
    use App\Models\BellNotification;

    // সর্বশেষ ৫টা notification
    $notifications = BellNotification::latest()
        ->take(5)
        ->get();

    // মোট unread count
    $unreadCount = BellNotification::whereNull('read_at')->count();
?>

<style>
    .notify-badge {
        position: absolute;
        top: -17px;
        right: -16px;
        background: #ff3b30;
        color: #ffffff;
        border-radius: 50%;
        font-size: 11px;
        min-width: 18px;
        min-height: 18px;
        padding: 0 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        line-height: 1;
        z-index: 10;
    }
    .nav-link-notify-wrapper {
        position: relative;
        display: inline-block;
    }

    .single_notify {
        padding: 8px 12px;
        border-bottom: 1px solid #f1f3f5;
        transition: background-color 0.2s ease, border-left-color 0.2s ease, opacity 0.2s ease;
        cursor: pointer;
    }

    .single_notify.notify-unread {
        background: #e9f3ff;
        border-left: 3px solid #0d6efd;
    }
    .single_notify.notify-unread .notify_content h5 {
        font-weight: 600;
    }

    .single_notify.notify-read {
        background: #ffffff;
        border-left: 3px solid transparent;
        opacity: 0.85;
    }
</style>

<div class="header_notification_warp d-flex align-items-center">
    <li>
        <div class="nav-link-notify-wrapper">
            <a class="bell_notification_clicker nav-link-notify" href="#">
                <i class="bi bi-bell"></i>

                <span id="notify-count" class="notify-badge"
                      <?php if($unreadCount == 0): ?> style="display:none" <?php endif; ?>>
                    <?php echo e($unreadCount); ?>

                </span>
            </a>
        </div>

        <div class="Menu_NOtification_Wrap">
            <div class="notification_Header d-flex justify-content-between align-items-center">
                <h4>Notifications</h4>
                <button type="button" class="btn btn-sm btn-link p-0" id="mark-all-read">
                    Mark all as read
                </button>
            </div>

            <div class="Notification_body" id="notify-list">
                <?php echo $__env->make('admin.partials.notifications-list', ['notifications' => $notifications], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
            </div>

            <div class="nofity_footer">
                <div class="submit_button text-center pt_20">
                    <a href="<?php echo e(route('notifications.index')); ?>" class="btn_1">See More</a>
                </div>
            </div>
        </div>
    </li>
</div>

<script>
    // Blade থেকে safe URL গুলো
    const pollUrl        = <?php echo json_encode(route('notifications.poll'), 15, 512) ?>;
    const markReadBase   = <?php echo json_encode(url('/notifications'), 15, 512) ?>;
    const markAllReadUrl = <?php echo json_encode(route('notifications.readAll'), 15, 512) ?>;

    const csrfTokenMeta = document.querySelector('meta[name="csrf-token"]');
    const csrfToken = csrfTokenMeta ? csrfTokenMeta.getAttribute('content') : '';

    function updateBadge(count) {
        const countEl = document.getElementById('notify-count');
        if (!countEl) return;

        countEl.textContent = count;
        countEl.style.display = count > 0 ? 'flex' : 'none';
    }

    // প্রতি কল-এ সার্ভার থেকে fresh data আনবে
    function refreshNotifications() {
        fetch(pollUrl, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            }
        })
        .then(res => {
            if (!res.ok) throw new Error('Poll HTTP ' + res.status);
            return res.json();
        })
        .then(data => {
            if (typeof data.count !== 'undefined') {
                updateBadge(data.count);
            }

            if (data.html) {
                const listEl = document.getElementById('notify-list');
                if (listEl) {
                    listEl.innerHTML = data.html;
                    // নতুন HTML load হলে আর কিছু লাগবে না,
                    // নিচের event delegation নিজে থেকেই কাজ করবে
                }
            }
        })
        .catch(err => console.error('Notification poll error:', err));
    }

    document.addEventListener('DOMContentLoaded', function () {
        const listContainer = document.getElementById('notify-list');
        const markAllBtn    = document.getElementById('mark-all-read');

        // 🔁 Event delegation: যেকোন .single_notify item এ click ধরবে
        if (listContainer && csrfToken) {
            listContainer.addEventListener('click', function (e) {
                const item = e.target.closest('.single_notify');
                if (!item) return;

                const id = item.getAttribute('data-id');
                if (!id) return;

                fetch(`${markReadBase}/${id}/read`, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify({})
                })
                .then(res => {
                    if (!res.ok) throw new Error('Mark read HTTP ' + res.status);
                    return res.json();
                })
                .then(data => {
                    if (!data || !data.success) return;

                    item.classList.remove('notify-unread');
                    item.classList.add('notify-read');

                    if (typeof data.count !== 'undefined') {
                        updateBadge(data.count);
                    }
                })
                .catch(err => console.error('Mark read error:', err));
            });
        }

        // Mark all as read
        if (markAllBtn && csrfToken) {
            markAllBtn.addEventListener('click', function () {
                fetch(markAllReadUrl, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify({})
                })
                .then(res => {
                    if (!res.ok) throw new Error('Mark all HTTP ' + res.status);
                    return res.json();
                })
                .then(data => {
                    if (!data || !data.success) return;

                    updateBadge(0);

                    const items = document.querySelectorAll('#notify-list .single_notify');
                    items.forEach(item => {
                        item.classList.remove('notify-unread');
                        item.classList.add('notify-read');
                    });
                })
                .catch(err => console.error('Mark all read error:', err));
            });
        }

        // প্রথমবার data load
        refreshNotifications();

        // 🔁 প্রতি ১০ সেকেন্ডে refresh
        setInterval(function () {
            refreshNotifications();
        }, 10000);
    });
</script>
<?php /**PATH /home/ecareba2/new1.rkmotorsbike.top/resources/views/layouts/admin.blade.php ENDPATH**/ ?>