<?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;
$profile_pic = $loggedIn && !empty($_SESSION['profile_pic']) ? $_SESSION['profile_pic'] : null;

$initials = '';
if (!$profile_pic && $displayName) {
    foreach (explode(' ', $displayName) as $p) {
        $initials .= strtoupper(substr($p,0,1));
    }
}

// Cart fallback
$cart_count = 0;
if (isset($_SESSION['cart']) && is_array($_SESSION['cart'])) {
    $cart_count = array_sum(array_column($_SESSION['cart'], 'quantity'));
}

// Try DB
$dbHost = "localhost";
$dbUser = "kkfxoaad";
$dbPass = "Bitok@2025";
$dbName = "kkfxoaad_bella";

$conn = @new mysqli($dbHost, $dbUser, $dbPass, $dbName);
if (!$conn->connect_errno) {
    $conn->set_charset('utf8mb4');
    try {
        $user_id = $loggedIn ? intval($_SESSION['user_id']) : null;
        $session_token = session_id();

        if ($user_id) {
            $stmt = $conn->prepare("
                SELECT COALESCE(SUM(ci.qty),0) AS total
                FROM carts c
                LEFT JOIN cart_items ci ON c.id = ci.cart_id
                WHERE c.user_id = ?
            ");
            $stmt->bind_param("i", $user_id);
        } else {
            $stmt = $conn->prepare("
                SELECT COALESCE(SUM(ci.qty),0) AS total
                FROM carts c
                LEFT JOIN cart_items ci ON c.id = ci.cart_id
                WHERE c.session_token = ?
            ");
            $stmt->bind_param("s", $session_token);
        }

        if ($stmt->execute()) {
            $res = $stmt->get_result();
            $row = $res->fetch_assoc();
            if ($row && isset($row['total'])) {
                $cart_count = intval($row['total']);
            }
        }
        $stmt->close();
    } catch (Throwable $e) {}
    $conn->close();
}
?>

<header style="background:#222;color:white;padding:10px 20px;position:fixed;top:0;left:0;right:0;height:60px;z-index:1100;display:flex;align-items:center;">
  <div class="navbar" style="display:flex;justify-content:space-between;align-items:center;width:100%;">
    
    <!-- Logo -->
    <div class="logo">
      <?php if ($is_admin): ?>
        <a href="admin-dashboard.php">
          <img src="images/taji-yetu.png" alt="Taji Yetu Logo" style="height:45px;width:auto;display:block;">
        </a>
      <?php else: ?>
        <a href="index.php">
          <img src="images/taji-yetu.png" alt="Taji Yetu Logo" style="height:45px;width:auto;display:block;">
        </a>
      <?php endif; ?>
    </div>

    <!-- Nav Links -->
    <ul class="nav-links" style="display:flex;list-style:none;gap:20px;margin:0;padding:0;">
      <?php if ($is_admin): ?>
        <li><a href="admin-dashboard.php" style="color:white;text-decoration:none;font-size:1rem;transition:color 0.3s;">Dashboard</a></li>
      <?php else: ?>
        <li><a href="index.php" style="color:white;text-decoration:none;font-size:1rem;transition:color 0.3s;">Home</a></li>
      <?php endif; ?>
      <li><a href="listing.php" style="color:white;text-decoration:none;font-size:1rem;transition:color 0.3s;">Shop</a></li>
      <li><a href="about.php" style="color:white;text-decoration:none;font-size:1rem;transition:color 0.3s;">About</a></li>
      <li><a href="contactus.php" style="color:white;text-decoration:none;font-size:1rem;transition:color 0.3s;">Contact</a></li>
    </ul>

    <!-- Right Icons -->
    <div class="nav-icons" style="display:flex;gap:15px;align-items:center;">

      <!-- Cart -->
      <div class="cart-wrapper" style="position:relative;">
        <a href="cart.php" style="color:white;font-size:1.2rem;text-decoration:none;">
          <i class="fas fa-shopping-cart"></i>
        </a>
        <?php if ($cart_count > 0): ?>
          <span style="position:absolute;top:-6px;right:-10px;background:#ff3c78;color:#fff;border-radius:50%;padding:3px 7px;font-size:0.75rem;font-weight:bold;">
            <?= intval($cart_count) ?>
          </span>
        <?php endif; ?>
      </div>

      <!-- Profile -->
      <div class="account-dropdown" style="position:relative;">
        <?php if ($loggedIn): ?>
          <button class="account-button" style="background:#333;color:#fff;border:none;padding:8px 16px;border-radius:25px;cursor:pointer;font-size:0.9rem;display:flex;align-items:center;gap:6px;">
            <?php if ($profile_pic): ?>
              <img src="<?= htmlspecialchars($profile_pic) ?>" alt="Profile" style="width:28px;height:28px;border-radius:50%;object-fit:cover;">
            <?php else: ?>
              <?= htmlspecialchars($initials ?: 'U') ?>
            <?php endif; ?>
            <i class="fas fa-caret-down"></i>
          </button>
          <div class="dropdown-menu" style="display:none;position:absolute;right:0;top:110%;background:#111;border:1px solid #333;border-radius:10px;overflow:hidden;min-width:160px;">
            <a href="profile.php" style="display:block;padding:12px 18px;text-decoration:none;color:#fff;transition:background 0.3s;">Profile</a>
            <a href="logout.php" style="display:block;padding:12px 18px;text-decoration:none;color:#fff;transition:background 0.3s;">Logout</a>
          </div>
        <?php else: ?>
          <a href="login.php" style="background:#333;color:#fff;border:none;padding:8px 16px;border-radius:25px;cursor:pointer;font-size:0.9rem;display:flex;align-items:center;gap:6px;text-decoration:none;">Login</a>
        <?php endif; ?>
      </div>
    </div>

    <!-- Hamburger -->
    <button class="hamburger" style="display:none;font-size:1.5rem;background:none;border:none;color:white;cursor:pointer;">
      <i class="fas fa-bars"></i>
    </button>
  </div>
</header>

<script>
// Mobile toggle
document.addEventListener('DOMContentLoaded', () => {
  const hamburger = document.querySelector('.hamburger');
  const navLinks = document.querySelector('.nav-links');
  hamburger.addEventListener('click', () => {
    if(navLinks.style.display === 'flex'){
      navLinks.style.display = 'none';
    } else {
      navLinks.style.display = 'flex';
      navLinks.style.flexDirection = 'column';
      navLinks.style.background = '#111';
      navLinks.style.position = 'absolute';
      navLinks.style.top = '60px';
      navLinks.style.left = '0';
      navLinks.style.width = '100%';
      navLinks.style.padding = '10px 0';
      navLinks.style.zIndex = '1110';
    }
  });
});
</script>
