<!-- ══════════════════════════════════════════════════════════════════════════
     notification_bell.php  ·  Include this ONCE per page inside your topbar.
     ──────────────────────────────────────────────────────────────────────────
     USAGE — paste inside your .topbar div, just before the .topbar-user div:

       <?php include 'notification_bell.php'; ?>

     Works for every role: superadmin, admin, manager, employee.
     ══════════════════════════════════════════════════════════════════════════ -->

<style>
/* ── Bell wrapper ── */
.notif-bell-wrap {
  position: relative;
  margin-right: 4px;
}
.notif-bell-btn {
  width: 36px; height: 36px; border-radius: 9px;
  border: 1px solid var(--border); background: var(--surface);
  display: flex; align-items: center; justify-content: center;
  cursor: pointer; font-size: 15px; color: var(--ink-2);
  transition: background .15s, color .15s; position: relative;
}
.notif-bell-btn:hover { background: var(--bg); color: var(--ink); }
.notif-bell-btn.has-unread { color: #3b82f6; }

/* Pulse badge */
.bell-badge {
  position: absolute; top: -4px; right: -4px;
  min-width: 18px; height: 18px; border-radius: 20px;
  background: #ef4444; color: #fff;
  font-size: 10px; font-weight: 700; font-family: 'JetBrains Mono', monospace;
  display: flex; align-items: center; justify-content: center; padding: 0 4px;
  border: 2px solid var(--surface);
  animation: bellPop .3s ease;
  display: none; /* hidden until JS sets count */
}
.bell-badge.visible { display: flex; }
@keyframes bellPop { from { transform: scale(0); } to { transform: scale(1); } }

/* Dropdown */
.notif-dropdown {
  position: absolute; top: calc(100% + 10px); right: 0;
  width: 360px; background: var(--surface);
  border: 1px solid var(--border); border-radius: 14px;
  box-shadow: 0 8px 32px rgba(15,23,42,.14);
  z-index: 300; display: none;
  animation: dropFade .18s ease;
  overflow: hidden;
}
.notif-dropdown.open { display: block; }
@keyframes dropFade { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:none; } }

.notif-drop-head {
  padding: 14px 16px; border-bottom: 1px solid var(--border);
  display: flex; align-items: center; justify-content: space-between;
}
.notif-drop-title { font-size: 14px; font-weight: 700; color: var(--ink); display: flex; align-items: center; gap: 6px; }
.notif-drop-title .drop-count { background: #ef4444; color: #fff; border-radius: 20px; padding: 1px 7px; font-size: 11px; }
.notif-mark-all-btn {
  font-size: 11px; font-weight: 600; color: #3b82f6;
  border: none; background: none; cursor: pointer; font-family: 'Sora',sans-serif;
  padding: 0; transition: color .15s;
}
.notif-mark-all-btn:hover { color: #1d4ed8; }

.notif-drop-list { max-height: 380px; overflow-y: auto; scrollbar-width: thin; }
.notif-drop-list::-webkit-scrollbar { width: 4px; }
.notif-drop-list::-webkit-scrollbar-track { background: transparent; }
.notif-drop-list::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }

.drop-item {
  padding: 12px 16px; border-bottom: 1px solid var(--border);
  display: grid; grid-template-columns: 36px 1fr;
  gap: 10px; cursor: pointer; transition: background .15s;
  text-decoration: none;
}
.drop-item:last-child { border-bottom: none; }
.drop-item:hover { background: #f8fafc; }
.drop-item.unread { background: #f0f9ff; }
.drop-item.unread:hover { background: #e0f2fe; }

.drop-item-icon {
  width: 36px; height: 36px; border-radius: 9px;
  display: flex; align-items: center; justify-content: center; font-size: 14px; flex-shrink: 0;
}
.drop-item-icon.general      { background: #d1fae5; color: #059669; }
.drop-item-icon.announcement { background: #dbeafe; color: #1d4ed8; }
.drop-item-icon.alert        { background: #ffedd5; color: #c2410c; }
.drop-item-icon.reminder     { background: #ede9fe; color: #7c3aed; }
.drop-item-icon.urgent       { background: #fee2e2; color: #dc2626; }

.drop-item-content { min-width: 0; }
.drop-item-title   { font-size: 13px; font-weight: 700; color: var(--ink); margin-bottom: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.drop-item.unread .drop-item-title::before { content: '●'; color: #3b82f6; font-size: 7px; margin-right: 5px; vertical-align: middle; }
.drop-item-msg     { font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.drop-item-time    { font-size: 10px; color: var(--muted); margin-top: 3px; }

.drop-footer {
  padding: 11px 16px; border-top: 1px solid var(--border); text-align: center;
}
.drop-footer a {
  font-size: 12px; font-weight: 700; color: #3b82f6; text-decoration: none;
  display: flex; align-items: center; justify-content: center; gap: 5px;
  transition: color .15s;
}
.drop-footer a:hover { color: #1d4ed8; }

.drop-empty { text-align: center; padding: 36px 20px; color: var(--muted); }
.drop-empty i { font-size: 28px; opacity: .25; display: block; margin-bottom: 10px; }
.drop-empty p { font-size: 13px; }
</style>

<!-- Bell button (insert where the notification bell should appear in topbar) -->
<div class="notif-bell-wrap" id="bellWrap">
  <button class="notif-bell-btn" id="bellBtn" title="Notifications" onclick="toggleBellDrop(event)">
    <i class="fas fa-bell"></i>
    <span class="bell-badge" id="bellBadge"></span>
  </button>
  <div class="notif-dropdown" id="bellDrop">
    <div class="notif-drop-head">
      <div class="notif-drop-title">
        Notifications <span class="drop-count" id="dropCount" style="display:none"></span>
      </div>
      <button class="notif-mark-all-btn" id="markAllBtn" style="display:none" onclick="markAllRead()">
        ✓ Mark all read
      </button>
    </div>
    <div class="notif-drop-list" id="dropList">
      <div class="drop-empty"><i class="fas fa-bell-slash"></i><p>Loading…</p></div>
    </div>
    <div class="drop-footer">
      <a href="view_notifications.php"><i class="fas fa-list"></i> View all notifications</a>
    </div>
  </div>
</div>

<script>
(function() {
  /* Type icon map */
  const ICONS = {
    general:      'fa-info-circle',
    announcement: 'fa-bullhorn',
    alert:        'fa-triangle-exclamation',
    reminder:     'fa-clock',
    urgent:       'fa-circle-exclamation',
  };

  let _loaded = false;

  /* ── Fetch unread count on load & every 60s ── */
  function fetchCount() {
    fetch('notification_api.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'count' })
    })
    .then(r => r.json())
    .then(data => updateBadge(data.unread || 0))
    .catch(() => {});
  }
  fetchCount();
  setInterval(fetchCount, 60000);

  function updateBadge(n) {
    const badge = document.getElementById('bellBadge');
    const btn   = document.getElementById('bellBtn');
    if (n > 0) {
      badge.textContent = n > 99 ? '99+' : n;
      badge.classList.add('visible');
      btn.classList.add('has-unread');
    } else {
      badge.classList.remove('visible');
      btn.classList.remove('has-unread');
    }
  }

  /* ── Toggle dropdown ── */
  window.toggleBellDrop = function(e) {
    e.stopPropagation();
    const drop = document.getElementById('bellDrop');
    const open = drop.classList.toggle('open');
    if (open && !_loaded) { loadRecent(); _loaded = true; }
  };

  /* Close on outside click */
  document.addEventListener('click', function(e) {
    const wrap = document.getElementById('bellWrap');
    if (wrap && !wrap.contains(e.target)) {
      document.getElementById('bellDrop').classList.remove('open');
    }
  });

  /* ── Load recent ── */
  function loadRecent() {
    fetch('notification_api.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'recent' })
    })
    .then(r => r.json())
    .then(data => renderDrop(data))
    .catch(() => {
      document.getElementById('dropList').innerHTML =
        '<div class="drop-empty"><i class="fas fa-wifi-slash"></i><p>Could not load notifications.</p></div>';
    });
  }

  function renderDrop(data) {
    const list = document.getElementById('dropList');
    const cnt  = document.getElementById('dropCount');
    const markBtn = document.getElementById('markAllBtn');

    updateBadge(data.unread || 0);

    if (data.unread > 0) {
      cnt.textContent = data.unread;
      cnt.style.display = 'inline-flex';
      markBtn.style.display = 'inline-block';
    } else {
      cnt.style.display = 'none';
      markBtn.style.display = 'none';
    }

    if (!data.items || data.items.length === 0) {
      list.innerHTML = '<div class="drop-empty"><i class="fas fa-bell-slash"></i><p>No notifications yet.</p></div>';
      return;
    }

    list.innerHTML = data.items.map(n => `
      <a class="drop-item${n.is_read ? '' : ' unread'}"
         href="view_notifications.php"
         onclick="markOneRead(${n.id}, event)">
        <div class="drop-item-icon ${n.type}">
          <i class="fas ${ICONS[n.type] || 'fa-bell'}"></i>
        </div>
        <div class="drop-item-content">
          <div class="drop-item-title">${escHtml(n.title)}</div>
          <div class="drop-item-msg">${escHtml(n.message)}</div>
          <div class="drop-item-time">${escHtml(n.time_ago)}</div>
        </div>
      </a>
    `).join('');
  }

  /* ── Mark one read ── */
  window.markOneRead = function(id, e) {
    fetch('notification_api.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'mark_read', notification_id: id })
    })
    .then(() => { fetchCount(); _loaded = false; })
    .catch(() => {});
    /* let navigation happen */
  };

  /* ── Mark all read ── */
  window.markAllRead = function() {
    fetch('notification_api.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'mark_all_read' })
    })
    .then(() => { _loaded = false; loadRecent(); fetchCount(); })
    .catch(() => {});
  };

  function escHtml(s) {
    return (s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }
})();
</script>