<header class="main-header">
  <!-- Logo -->
  <a href="#" class="logo">
    <!-- mini logo for sidebar mini 50x50 pixels -->
    <span class="logo-mini"><b><img src="<?= base_url('assets/images/company_logo.jpg') ?>"></b></span>
    <!-- logo for regular state and mobile devices -->
    <span class="logo-lg"><b>MotorBike</b></span>
  </a>
  <!-- Header Navbar: style can be found in header.less -->
  <nav class="navbar navbar-static-top">
    <div style="display: flex;align-items: center;justify-content: space-between;">
      <!-- Sidebar toggle button-->
      <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
        <span class="sr-only">Toggle navigation</span>
      </a>
      <li class="nav-item dropdown" style="padding-right: 15px;position: relative;list-style: none;">
        <i class="fa fa-bell" id="notificationIcon" style="font-size: 15px;cursor: pointer;color:white;" data-toggle="dropdown"></i>
        <!-- <span id="notificationCount" style="position: absolute;top: -10px;background-color: red;border-radius: 100px;width: 18px;height: 18px;text-align: center;left: 10px;display: none;"></span> -->
        <span id="notificationCount" class="badge badge-warning navbar-badge">15</span>
        <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right" style="width: 400px;padding: 5%;max-height: 500px;overflow: auto;margin-right: 5px;">
          <span class="dropdown-header" id="notificationHeader">0 Notifications</span>
          <div class="dropdown-divider"></div>
          <div id="notificationList"></div>
          <div class="dropdown-divider"></div>
        </div>
      </li>
    </div>
  </nav>
</header>
<script>
  $(document).ready(function() {
    const checkElement = setInterval(() => {
      const notificationList = document.getElementById('notificationList');
      if (notificationList && notificationList.innerHTML) {
        clearInterval(checkElement); // Stop checking

        const elementother = document.querySelectorAll('.notification_item');

        elementother.forEach((notif) => {
          notif.addEventListener('click', () => {
            let notifId = notif.dataset.id;

            // AJAX request to mark the notification as read
            fetch("<?= base_url('notifications/markAsRead') ?>/" + notifId, {
                method: "POST",
                headers: {
                  "Content-Type": "application/json"
                }
              })
              .then(response => response.json()) // Parse JSON response
              .then(data => {
                console.log("Notification marked as read:", data);
                location.reload(); // Refresh to update notification count
              })
              .catch(error => console.error("Error:", error));
          });
        });
      }
    }, 100); // Check every 100ms
  })

  function fetchNotifications() {
    $.ajax({
      url: '/notifications', // Change this URL to your actual PHP script
      type: 'GET',
      dataType: 'json',
      success: function(data) {

        let notificationCount = data.length;
$('#notificationHeader').text(notificationCount + ' Notifications');

if (notificationCount > 0) {
  $('#notificationCount').text(notificationCount).show();
} else {
  $('#notificationCount').hide();
}

let notificationHTML = `
  
`;

data.forEach(notif => {
  // On enlève d’éventuels slashs au début puis on préfixe d’un slash
  const href = '/' + notif.link.replace(/^\/+/, '');

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


notificationHTML += `
  
`;

$('#notificationList').html(notificationHTML);


        const elementother = document.querySelectorAll('.notification_item');

        elementother.forEach((notif) => {
          notif.addEventListener('click', () => {
            let notifId = notif.dataset.id;

            // AJAX request to mark the notification as read
            fetch("<?= base_url('notifications/markAsRead') ?>/" + notifId, {
                method: "POST",
                headers: {
                  "Content-Type": "application/json"
                }
              })
              .then(response => response.json()) // Parse JSON response
              .then(data => {
                console.log("Notification marked as read:", data);
                // location.reload(); // Refresh to update notification count
              })
              .catch(error => console.error("Error:", error));
          });
        });

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

  // Fetch notifications every 10 seconds
  setInterval(fetchNotifications, 10000);

  // Initial fetch when the page loads
  fetchNotifications();
</script>

<!-- Left side column. contains the logo and sidebar -->