<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>

    <!-- Navbar Right Menu -->
    <ul class="navbar-nav" style="position: absolute; right: 15px; top: 50%; transform: translateY(-50%); margin: 0; padding: 0; list-style: none; display: flex; align-items: center; gap: 20px;">
      
      <!-- Notifications -->
      <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>

      <!-- User Info (sans dropdown) -->
      <li class="nav-item" style="position: relative;">
        <div style="color: white; display: flex; align-items: center; gap: 10px; padding: 5px 10px; background: rgba(255,255,255,0.1); border-radius: 20px;">
          <i class="fa fa-user-circle" style="font-size: 24px;"></i>
          <div style="display: flex; flex-direction: column; line-height: 1.2;">
            <span style="font-size: 13px; font-weight: 600;">
              <?php 
                $username = session()->get('username');
                echo $username ? esc($username) : 'Utilisateur'; 
              ?>
            </span>
            <span style="font-size: 11px; opacity: 0.8;">
              <?php 
                $role = session()->get('role');
                echo $role ? esc($role) : 'Aucun groupe'; 
              ?>
            </span>
          </div>
        </div>
      </li>
    </ul>
  </nav>
</header>

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

  .icon-unread {
    color: #007bff;
  }

  #markAllAsReadBtn {
    white-space: nowrap;
  }

  #markAllAsReadBtn:hover {
    background-color: #0056b3;
  }

  /* Style pour le dropdown utilisateur */
  .dropdown-item {
    transition: background-color 0.2s;
  }

  .dropdown-item:hover {
    background-color: #f5f5f5;
    text-decoration: none;
  }

  .navbar-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    padding: 3px 6px;
    border-radius: 10px;
    background: #f39c12;
    color: white;
    font-size: 10px;
  }
</style>

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

      data.forEach(notif => {
        if (notif.is_read == 0) {
          notificationCount++;
        }

        const href = '/' + notif.link.replace(/^\/+/, '');
        const notifClass = notif.is_read == 0 ? "notification_item unread" : "notification_item";
        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>
        `;
      });

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

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

      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);
          })
          .catch(error => console.error("Error:", error));
        });
      });

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

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);
    fetchNotifications();
  })
  .catch(error => console.error("Error:", error));
}

$(document).on('click', '#markAllAsReadBtn', function(e) {
  e.preventDefault();
  e.stopPropagation();
  markAllAsRead();
});

setInterval(fetchNotifications, 10000);
fetchNotifications();
</script>