<header class="main-header">
  <!-- Logo -->
  <a href="#" class="logo">
    <span class="logo-mini"><b><img src="<?= base_url('assets/images/company_logo.jpg') ?>"></b></span>
    <span class="logo-lg"><b>MotorBike</b></span>
  </a>

  <!-- Header Navbar -->
  <nav class="navbar navbar-static-top" style="position: relative; height: 50px; background: #3c8dbc;">
    <!-- Sidebar toggle button -->
    <a href="#" class="sidebar-toggle" onclick="toggleSidebar()">
      <span class="sr-only">Toggle navigation</span>
    </a>

    <!-- Notifications -->
    <ul class="navbar-nav" style="position: absolute; right: 15px; top: 50%; transform: translateY(-50%); margin: 0; padding: 0; list-style: none;">
      <li class="nav-item dropdown" style="position: relative;">
        <i class="fa fa-bell" id="notificationIcon" style="font-size: 20px; cursor: pointer; color:white;" data-toggle="dropdown"></i>
        <span id="notificationCount" class="badge badge-warning navbar-badge"></span>
        <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right" 
             style="width: 400px; padding: 5%; max-height: 500px; overflow: auto; margin-right: 5px;">
          <div style="display: flex; justify-content: space-between; align-items: center; padding: 0 10px;">
            <span class="dropdown-header" id="notificationHeader" style="padding: 0;">0 Notifications</span>
            <button id="markAllAsReadBtn" class="btn btn-sm btn-primary" style="font-size: 12px; padding: 4px 10px;">
              <i class="fa fa-check"></i> Marquer tout comme lu
            </button>
          </div>
          <div class="dropdown-divider"></div>
          <div id="notificationList"></div>
          <div class="dropdown-divider"></div>
        </div>
      </li>
    </ul>
  </nav>
</header>

<!-- Styles -->
<style>
  /* Notifications non lues */
  .notification_item.unread {
    font-weight: bold;
    background-color: #f0f8ff; /* bleu clair */
  }

  /* Icône bleue pour notifications non lues */
  .icon-unread {
    color: #007bff; /* bleu */
  }

  /* Style du bouton */
  #markAllAsReadBtn {
    white-space: nowrap;
  }

  #markAllAsReadBtn:hover {
    background-color: #0056b3;
  }
</style>

<script>
function fetchNotifications() {
  $.ajax({
    url: '/notifications', // route NotificationController::getNotification
    type: 'GET',
    dataType: 'json',
    success: function(data) {
      let notificationCount = 0;
      let notificationHTML = '';

      data.forEach(notif => {
        // Compter les notifications non lues
        if (notif.is_read == 0) {
          notificationCount++;
        }

        const href = '/' + notif.link.replace(/^\/+/, '');
        const notifClass = notif.is_read == 0 ? "notification_item unread" : "notification_item";

        // Icône uniquement pour non lu
        const iconHTML = notif.is_read == 0 ? '<i class="fa fa-exclamation-circle icon-unread mr-9"></i>' : '';

        notificationHTML += `
          <a href="${href}"
             class="${notifClass}"
             data-id="${notif.id}"
             style="font-size: 15px; display: flex; align-items: center; justify-content: space-between;">
            <span style="display: flex; align-items: center; gap:10px;">
              ${iconHTML} ${notif.message}
            </span>
            <span class="float-right text-muted text-sm">${notif.created_at}</span>
          </a>
          <div class="dropdown-divider"></div>
        `;
      });

      // Injecter les notifications
      $('#notificationList').html(notificationHTML);
      $('#notificationHeader').text(data.length + ' Notifications');

      // Badge pour non lues
      if (notificationCount > 0) {
        $('#notificationCount').text(notificationCount).show();
        $('#markAllAsReadBtn').show();
      } else {
        $('#notificationCount').hide();
        $('#markAllAsReadBtn').hide();
      }

      // Ajouter l'événement clic pour marquer comme lu
      const items = document.querySelectorAll('.notification_item');
      items.forEach(item => {
        item.addEventListener('click', () => {
          const notifId = item.dataset.id;
          fetch("<?= base_url('notifications/markAsRead') ?>/" + notifId, {
            method: "POST",
            headers: { "Content-Type": "application/json" }
          })
          .then(response => response.json())
          .then(data => {
            console.log("Notification marked as read:", data);
            // l'icône disparaîtra au prochain fetch
          })
          .catch(error => console.error("Error:", error));
        });
      });

    },
    error: function(err) {
      console.error('Error fetching notifications:', err);
    }
  });
}

// Fonction pour marquer toutes les notifications comme lues
function markAllAsRead() {
  fetch("<?= base_url('notifications/markAllAsRead') ?>", {
    method: "POST",
    headers: { "Content-Type": "application/json" }
  })
  .then(response => response.json())
  .then(data => {
    console.log("All notifications marked as read:", data);
    // Rafraîchir les notifications immédiatement
    fetchNotifications();
  })
  .catch(error => console.error("Error:", error));
}

// Attacher l'événement au bouton
$(document).on('click', '#markAllAsReadBtn', function(e) {
  e.preventDefault();
  e.stopPropagation();
  markAllAsRead();
});

// Rafraîchir toutes les 10 secondes
setInterval(fetchNotifications, 10000);
// Premier chargement
fetchNotifications();
</script>