<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$loggedIn = isset($_SESSION['user_id']);
$displayName = $loggedIn ? htmlspecialchars($_SESSION['name'] ?? 'Account') : null;
$is_admin = $loggedIn ? intval($_SESSION['is_admin'] ?? 0) : 0;

// Default avatar
$default_avatar = '/Bella/images/default-user.jpg';

// Ensure session profile pic is set
if ($loggedIn && !isset($_SESSION['profile_pic'])) {
    // For pages like profile.php, $profilePic should be fetched before including navbar
    $_SESSION['profile_pic'] = $_SESSION['profile_pic'] ?? $default_avatar;
}

$profile_pic = $loggedIn ? ($_SESSION['profile_pic'] ?? $default_avatar) : null;

// Determine avatar to display
$avatar_path = $default_avatar;
if ($profile_pic && $profile_pic !== '') {
    $full_path = $_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($profile_pic, '/');
    if (file_exists($full_path)) {
        $avatar_path = '/' . ltrim($profile_pic, '/');
    }
}

// Generate initials if no uploaded avatar
$initials_display = '';
if ($avatar_path === $default_avatar && $displayName) {
    foreach (explode(' ', $displayName) as $p) {
        $initials_display .= strtoupper(substr($p, 0, 1));
    }
}
?>

<header>
  <div class="navbar-container">
    <!-- Logo -->
    <div class="logo">
      <a href="<?= $is_admin ? 'admin-dashboard.php' : 'index.php' ?>">
        <img src="images/taji-yetu.png" alt="Logo">
      </a>
    </div>

    <!-- Nav Links -->
    <ul class="nav-links">
      <?php if ($is_admin): ?>
        <li><a href="admin-dashboard.php">Dashboard</a></li>
      <?php else: ?>
        <li><a href="index.php">Home</a></li>
      <?php endif; ?>
      <li><a href="listing.php">Shop</a></li>
      <li><a href="about.php">About</a></li>
      <li><a href="contactus.php">Contact</a></li>
    </ul>

    <!-- Right Icons -->
    <div class="nav-icons">
      <!-- Cart -->
      <div class="cart-wrapper">
        <a href="cart.php" class="cart-icon">
          <i class="fas fa-shopping-cart"></i>
        </a>
        <span id="cart-count">0</span>
      </div>

      <!-- Mini Avatar -->
      <?php if ($loggedIn): ?>
        <div class="mini-avatar">
          <?php if ($avatar_path !== $default_avatar): ?>
            <img src="<?= htmlspecialchars($avatar_path) ?>" alt="Profile">
          <?php elseif ($initials_display): ?>
            <?= htmlspecialchars($initials_display) ?>
          <?php else: ?>
            <img src="<?= htmlspecialchars($default_avatar) ?>" alt="Profile">
          <?php endif; ?>
        </div>
      <?php endif; ?>

      <!-- Profile Dropdown -->
      <div class="account-dropdown">
        <?php if ($loggedIn): ?>
          <button id="account-btn">
            <?php if ($avatar_path !== $default_avatar): ?>
              <img src="<?= htmlspecialchars($avatar_path) ?>" alt="Profile">
            <?php elseif ($initials_display): ?>
              <?= htmlspecialchars($initials_display) ?>
            <?php else: ?>
              <img src="<?= htmlspecialchars($default_avatar) ?>" alt="Profile">
            <?php endif; ?>
            <i class="fas fa-caret-down"></i>
          </button>
          <div id="dropdown-menu" class="dropdown-menu">
            <a href="profile.php">Profile</a>
            <a href="logout.php">Logout</a>
          </div>
        <?php else: ?>
          <a href="login.php" class="login-btn">Login</a>
        <?php endif; ?>
      </div>

      <!-- Hamburger -->
      <button class="hamburger">
        <i class="fas fa-bars"></i>
      </button>
    </div>
  </div>
</header>

<style>
/* Navbar general */
.navbar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #222;
  color: #fff;
  padding: 10px 20px;
  position: fixed;
  top: 0; left: 0; right: 0;
  height: 60px;
  z-index: 1100;
}
.logo img { height: 45px; }

/* Nav links */
.nav-links {
  display: flex;
  list-style: none;
  gap: 20px;
  margin: 0; padding: 0;
}
.nav-links li a {
  color: #fff;
  text-decoration: none;
  font-size: 1rem;
  transition: 0.3s;
}
.nav-links li a:hover { color: #ff3c78; }

/* Right icons */
.nav-icons { display: flex; gap: 15px; align-items: center; }
.cart-wrapper { position: relative; }
.cart-icon { color: #fff; font-size: 1.2rem; }
#cart-count {
  display: none;
  position: absolute;
  top: -6px; right: -10px;
  background: #ff3c78; color: #fff;
  border-radius: 50%;
  padding: 3px 7px;
  font-size: 0.75rem; font-weight: bold;
}

/* Mini avatar */
.mini-avatar {
  width: 32px; height: 32px;
  border-radius: 50%;
  overflow: hidden;
  background: #444;
  display: flex;
  align-items: center; justify-content: center;
  color: #fff;
  font-size: 0.9rem;
}
.mini-avatar img { width: 100%; height: 100%; object-fit: cover; }

/* Profile dropdown */
.account-dropdown { position: relative; }
.account-dropdown button, .login-btn {
  background: #333;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 25px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
}
.dropdown-menu {
  display: none;
  position: absolute;
  right: 0;
  top: 110%;
  background: #111;
  border: 1px solid #333;
  border-radius: 10px;
  overflow: hidden;
  min-width: 160px;
  z-index: 1000;
}
.dropdown-menu a {
  display: block;
  padding: 12px 18px;
  text-decoration: none;
  color: #fff;
  transition: background 0.3s;
}
.dropdown-menu a:hover { background: #333; }

/* Hamburger */
.hamburger { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer; }

/* Responsive mobile */
@media (max-width: 768px) {
  .nav-links { display: none; position: fixed; top: 60px; left: 0; width: 100%; flex-direction: column; background: #111; padding: 10px 0; gap: 0; z-index: 1090; }
  .nav-links li { text-align: center; margin: 5px 0; }
  .hamburger { display: block; }
}
</style>

<script>
// Mobile toggle & dropdown
document.addEventListener('DOMContentLoaded', () => {
  const hamburger = document.querySelector('.hamburger');
  const navLinks = document.querySelector('.nav-links');
  const accountBtn = document.getElementById('account-btn');
  const dropdownMenu = document.getElementById('dropdown-menu');
  const cartCount = document.getElementById('cart-count');

  hamburger.addEventListener('click', () => {
    navLinks.style.display = navLinks.style.display === 'flex' ? 'none' : 'flex';
  });

  if (accountBtn) {
    accountBtn.addEventListener('click', () => {
      dropdownMenu.style.display = dropdownMenu.style.display === 'block' ? 'none' : 'block';
    });
  }

  // Fetch cart count
  function refreshCartCount() {
    fetch('/Bella/get-cart.php')
      .then(res => res.json())
      .then(data => {
        if (data.status === 'success') {
          const count = data.total_items;
          if (count > 0) { cartCount.textContent = count; cartCount.style.display = 'inline-block'; }
          else { cartCount.style.display = 'none'; }
        }
      })
      .catch(err => console.error('Cart fetch error', err));
  }

  refreshCartCount();
  window.refreshCartCount = refreshCartCount;
});
</script>
