<?php
    $fullName = $_SESSION['full_name']       ?? $_SESSION['username'] ?? '';
    $roleName = $_SESSION['user_group_name'] ?? '';
?>
<div class="rs-topbar d-flex align-items-center justify-content-between px-3"
     style="height:var(--rs-topbar-h,44px);background:var(--rs-topbar-bg,#fff);border-bottom:1px solid var(--rs-border,#e2e8f0);">

    <div class="d-flex align-items-center gap-3">
        <button type="button" id="rsSidebarCollapse" class="rs-topbar-icon-btn d-none d-lg-inline-flex"
                aria-label="Toggle menu" title="Toggle menu">
            <i class="fas fa-bars"></i>
        </button>
        <div class="text-muted" style="font-size:.78rem;">
            <?= htmlspecialchars($this->v('page_title', 'Dashboard')); ?>
        </div>
    </div>

    <div class="d-flex align-items-center gap-3">
        <!-- Approvals inbox placeholder — will read fin_approvals count in later slice -->
        <a href="<?= PROOT; ?>FinChains/myQueue" class="text-decoration-none text-body position-relative" title="Approvals inbox">
            <i class="fas fa-inbox"></i>
        </a>

        <!-- Notifications: live-count badge + dropdown preview -->
        <div class="dropdown" id="rsNotifWrap">
            <a href="#" class="text-decoration-none text-body position-relative" title="Notifications"
               data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false" id="rsNotifBell">
                <i class="fas fa-bell"></i>
                <span id="rsNotifBadge" class="position-absolute translate-middle badge rounded-pill"
                      style="top:-2px;right:-10px;background:#dc2626;color:#fff;font-size:.55rem;display:none;">0</span>
            </a>
            <ul class="dropdown-menu dropdown-menu-end shadow" style="min-width:340px;max-height:420px;overflow-y:auto;">
                <li class="d-flex align-items-center justify-content-between px-3 py-2 border-bottom">
                    <strong style="font-size:.78rem;">Notifications</strong>
                    <button type="button" class="btn btn-link btn-sm p-0" style="font-size:.7rem;" onclick="rsNotifMarkAll()">Mark all read</button>
                </li>
                <li id="rsNotifList" class="text-center text-muted py-3 small">Loading…</li>
                <li class="border-top text-center py-2">
                    <a href="<?= PROOT; ?>Notifications" class="text-decoration-none small">View all</a>
                </li>
            </ul>
        </div>

        <script>
        (function () {
            const bellBadge = document.getElementById('rsNotifBadge');
            const list      = document.getElementById('rsNotifList');
            if (!bellBadge || !list) return;

            function esc(s){ return (s||'').toString().replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"}[m])); }

            function refresh() {
                fetch('<?= PROOT; ?>Notifications/recentAj').then(r => r.json()).then(j => {
                    if (!j || !j.ok) return;
                    const n = parseInt(j.unread, 10) || 0;
                    bellBadge.textContent = n > 99 ? '99+' : n;
                    bellBadge.style.display = n > 0 ? '' : 'none';
                    if (!j.items || j.items.length === 0) {
                        list.innerHTML = '<div class="text-center text-muted py-3 small">You\'re all caught up.</div>';
                        return;
                    }
                    list.outerHTML = '<ul id="rsNotifList" class="list-unstyled mb-0">' +
                        j.items.map(it => {
                            const bg = it.read ? '' : 'background:#fff8e6;';
                            const url = it.target_url ? ('<?= PROOT; ?>' + it.target_url) : '#';
                            return `
                                <li style="border-bottom:1px solid #eef2f7;${bg}">
                                    <a href="${esc(url)}" class="d-block px-3 py-2 text-body text-decoration-none"
                                       onclick="rsNotifMarkRead(${it.id})">
                                        <div style="font-size:.72rem;font-weight:600;">${esc(it.subject)}</div>
                                        <div class="text-muted" style="font-size:.66rem;">${esc(it.body||'')}</div>
                                        <div class="text-muted" style="font-size:.6rem;">${esc(it.created_on)}</div>
                                    </a>
                                </li>`;
                        }).join('') +
                    '</ul>';
                }).catch(() => {});
            }

            window.rsNotifMarkRead = function (id) {
                fetch('<?= PROOT; ?>Notifications/markReadAj', {
                    method: 'POST', headers: {'Content-Type':'application/x-www-form-urlencoded'},
                    body: 'id=' + encodeURIComponent(id)
                });
            };
            window.rsNotifMarkAll = function () {
                fetch('<?= PROOT; ?>Notifications/markAllReadAj', {method:'POST'}).then(() => refresh());
            };

            refresh();
            setInterval(refresh, 60000); // poll every minute; cheap enough
        })();
        </script>

        <!-- User menu -->
        <div class="dropdown">
            <a href="#" class="dropdown-toggle text-decoration-none text-body d-flex align-items-center gap-2" data-bs-toggle="dropdown">
                <div class="text-end" style="line-height:1.05;">
                    <div style="font-size:.76rem;font-weight:600;"><?= htmlspecialchars($fullName); ?></div>
                    <div class="text-muted" style="font-size:.64rem;letter-spacing:.4px;text-transform:uppercase;"><?= htmlspecialchars($roleName); ?></div>
                </div>
                <i class="fas fa-user-circle" style="font-size:1.2rem;color:var(--rs-accent,#6b8fbe);"></i>
            </a>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="<?= PROOT; ?>Dashboard"><i class="fas fa-home me-2"></i>Dashboard</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item" href="<?= PROOT; ?>Logout"><i class="fas fa-sign-out-alt me-2"></i>Sign out</a></li>
            </ul>
        </div>
    </div>
</div>
