<?php
/**
 * Header Template
 * Includes head, shopping cart offcanvas, and navbar
 */

require_once __DIR__ . '/init.php';

$pageTitle = $pageTitle ?? 'Cartzilla | Electronics Store';
$pageDescription = $pageDescription ?? 'Cartzilla - Multipurpose Bootstrap E-Commerce HTML Template';

// Detect if we're on the homepage/index
$currentPage = $_SERVER['REQUEST_URI'] ?? '';
$isHomePage = (strpos($currentPage, '/index.php') !== false || 
               strpos($currentPage, '/') === strlen($currentPage) - 1 || 
               $currentPage === '/' || 
               empty(parse_url($currentPage, PHP_URL_PATH)) || 
               parse_url($currentPage, PHP_URL_PATH) === '/');

// Get cart data
$cart = new Cart();
$userId = $auth->getUserId();
$sessionId = $auth->getSessionId();
$cartData = $cart->getOrCreateCart($userId, $sessionId);
$cartItems = $cart->getCartItems($cartData['id']);
$cartTotal = $cart->getCartTotal($cartData['id'], $userId);
$cartCount = $cart->getCartCount($cartData['id']);

// Get user data
$user = $auth->isLoggedIn() ? $auth->getUser() : null;

// Get free shipping threshold
$freeShippingThreshold = defined('FREE_SHIPPING_THRESHOLD') ? FREE_SHIPPING_THRESHOLD : 200;

// Load category menu helper
require_once __DIR__ . '/category-menu-helper.php';
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="light" data-pwa="true">
  <head>
    <meta charset="utf-8">

    <!-- Viewport -->
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, viewport-fit=cover">

    <!-- SEO Meta Tags -->
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($pageDescription); ?>">
    <meta name="keywords" content="online shop, e-commerce, online store, market, multipurpose, product landing, cart, checkout, ui kit, light and dark mode, bootstrap, html5, css3, javascript, gallery, slider, mobile, pwa">
    <meta name="author" content="Coderthemes">

    <!-- Webmanifest + Favicon / App icons -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="manifest" href="/manifest.json">
    <link rel="icon" type="image/png" href="/assets/app-icons/icon-32x32.png" sizes="32x32">
    <link rel="apple-touch-icon" href="/assets/app-icons/icon-180x180.png">

    <!-- Theme switcher (color modes) -->
    <script src="/assets/js/theme-switcher.js"></script>

    <!-- Preloaded local web font (Inter) -->
    <link rel="preload" href="/assets/fonts/inter-variable-latin.woff2" as="font" type="font/woff2" crossorigin>

    <!-- Font icons -->
    <link rel="preload" href="/assets/icons/cartzilla-icons.woff2" as="font" type="font/woff2" crossorigin>
    <link rel="stylesheet" href="/assets/icons/cartzilla-icons.min.css">

    <!-- Vendor styles -->
    <link rel="stylesheet" href="/assets/vendor/swiper/swiper-bundle.min.css">

    <!-- Bootstrap + Theme styles -->
    <link rel="preload" href="/assets/css/theme.min.css" as="style">
    <link rel="preload" href="/assets/css/theme.rtl.min.css" as="style">
    <link rel="stylesheet" href="/assets/css/theme.min.css" id="theme-styles">
  </head>


  <!-- Body -->
  <body>

    <!-- Shopping cart offcanvas -->
    <div class="offcanvas offcanvas-end pb-sm-2 px-sm-2" id="shoppingCart" tabindex="-1" aria-labelledby="shoppingCartLabel" style="width: 500px" data-free-shipping-threshold="<?php echo $freeShippingThreshold; ?>">

      <!-- Header -->
      <div class="offcanvas-header flex-column align-items-start py-3 pt-lg-4">
        <div class="d-flex align-items-center justify-content-between w-100 mb-3 mb-lg-4">
          <h4 class="offcanvas-title" id="shoppingCartLabel">Coș de cumpărături</h4>
          <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Închide"></button>
        </div>
        <?php 
        if ($cartTotal > 0): 
            $remainingForFreeShipping = max(0, $freeShippingThreshold - $cartTotal);
            $freeShippingProgress = min(100, ($cartTotal / $freeShippingThreshold) * 100);
        ?>
        <?php if ($remainingForFreeShipping > 0): ?>
        <p class="fs-sm free-shipping-text">Cumpără încă <span class="text-dark-emphasis fw-semibold"><?php echo number_format($remainingForFreeShipping, 2); ?> RON</span> pentru <span class="text-dark-emphasis fw-semibold">Transport Gratuit</span></p>
        <div class="progress w-100 free-shipping-progress" role="progressbar" aria-label="Progres transport gratuit" aria-valuenow="<?php echo round($freeShippingProgress); ?>" aria-valuemin="0" aria-valuemax="100" style="height: 4px">
          <div class="progress-bar bg-warning rounded-pill" style="width: <?php echo $freeShippingProgress; ?>%"></div>
        </div>
        <?php else: ?>
        <p class="fs-sm text-success free-shipping-text"><span class="text-dark-emphasis fw-semibold">Transport Gratuit</span> eligibil!</p>
        <div class="progress w-100 free-shipping-progress" role="progressbar" aria-label="Progres transport gratuit" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="height: 4px">
          <div class="progress-bar bg-success rounded-pill" style="width: 100%"></div>
        </div>
        <?php endif; ?>
        <?php else: ?>
        <p class="fs-sm free-shipping-text">Coșul tău este gol</p>
        <?php endif; ?>
      </div>

      <!-- Items -->
      <div class="offcanvas-body d-flex flex-column gap-4 pt-2" id="cartItemsContainer">
        <?php if (empty($cartItems)): ?>
          <p class="text-center text-body-secondary">Coșul tău este gol</p>
        <?php else: ?>
          <?php foreach ($cartItems as $item): 
            // Normalize image path
            $itemImage = $item['image'] ?? '01.png';
            if (!empty($itemImage)) {
                if (str_starts_with($itemImage, 'http') || str_starts_with($itemImage, '/')) {
                    // Already absolute path or URL
                    $itemImagePath = $itemImage;
                } else {
                    // Relative path - prepend default path
                    $itemImagePath = '/assets/img/shop/electronics/thumbs/' . $itemImage;
                }
            } else {
                $itemImagePath = '/assets/img/shop/electronics/thumbs/01.png';
            }
          ?>
          <div class="d-flex align-items-center" data-cart-item-id="<?php echo $item['id']; ?>">
            <a class="flex-shrink-0" href="/produs/<?php echo htmlspecialchars($item['slug']); ?>">
              <img src="<?php echo htmlspecialchars($itemImagePath); ?>" width="110" alt="<?php echo htmlspecialchars($item['name']); ?>">
            </a>
            <div class="w-100 min-w-0 ps-2 ps-sm-3">
              <h5 class="d-flex animate-underline mb-2">
                <a class="d-block fs-sm fw-medium text-truncate animate-target" href="/produs/<?php echo htmlspecialchars($item['slug']); ?>"><?php echo htmlspecialchars($item['name']); ?></a>
              </h5>
              <div class="h6 pb-1 mb-2" data-item-total data-unit-price="<?php echo $item['price_at_add']; ?>"><?php echo number_format($item['price_at_add'] * $item['quantity'], 2); ?> RON</div>
              <div class="d-flex align-items-center justify-content-between">
                <div class="count-input rounded-2">
                  <button type="button" class="btn btn-icon btn-sm cart-decrement-offcanvas" data-cart-item-id="<?php echo $item['id']; ?>" aria-label="Scade cantitatea">
                    <i class="ci-minus"></i>
                  </button>
                  <input type="number" class="form-control form-control-sm cart-quantity-offcanvas" data-cart-item-id="<?php echo $item['id']; ?>" value="<?php echo $item['quantity']; ?>" readonly>
                  <button type="button" class="btn btn-icon btn-sm cart-increment-offcanvas" data-cart-item-id="<?php echo $item['id']; ?>" aria-label="Crește cantitatea">
                    <i class="ci-plus"></i>
                  </button>
                </div>
                <button type="button" class="btn-close fs-sm cart-remove-offcanvas" data-cart-item-id="<?php echo $item['id']; ?>" data-bs-toggle="tooltip" data-bs-custom-class="tooltip-sm" data-bs-title="Șterge" aria-label="Șterge din coș"></button>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>

      <!-- Footer -->
      <?php if (!empty($cartItems)): ?>
      <div class="offcanvas-header flex-column align-items-start">
        <div class="d-flex align-items-center justify-content-between w-100 mb-3 mb-md-4">
          <span class="text-light-emphasis">Subtotal:</span>
          <span class="h6 mb-0" id="cartSubtotal"><?php echo number_format($cartTotal, 2); ?> RON</span>
        </div>
        <div class="d-flex w-100 gap-3">
          <a class="btn btn-lg btn-secondary w-100" href="/cos">Vezi coșul</a>
          <a class="btn btn-lg btn-primary w-100" href="/checkout/livrare">Finalizează comanda</a>
        </div>
      </div>
      <?php endif; ?>
    </div>


    <!-- Navigation bar (Page header) -->
    <header class="navbar navbar-expand-lg navbar-dark bg-dark d-block z-fixed p-0" data-sticky-navbar='{"offset": 500}'>
      <div class="container d-block py-1 py-lg-3" data-bs-theme="dark">
        <div class="navbar-stuck-hide pt-1"></div>
        <div class="row flex-nowrap align-items-center g-0">
          <div class="col col-lg-3 d-flex align-items-center">

            <!-- Mobile offcanvas menu toggler (Hamburger) -->
            <button type="button" class="navbar-toggler me-4 me-lg-0" data-bs-toggle="offcanvas" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>

            <!-- Navbar brand (Logo) -->
            <a href="/" class="navbar-brand me-0">
              <span class="d-none d-sm-flex flex-shrink-0 text-primary me-2">
                <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36"><path d="M36 18.01c0 8.097-5.355 14.949-12.705 17.2a18.12 18.12 0 0 1-5.315.79C9.622 36 2.608 30.313.573 22.611.257 21.407.059 20.162 0 18.879v-1.758c.02-.395.059-.79.099-1.185.099-.908.277-1.817.514-2.686C2.687 5.628 9.682 0 18 0c5.572 0 10.551 2.528 13.871 6.517 1.502 1.797 2.648 3.91 3.359 6.201.494 1.659.771 3.436.771 5.292z" fill="currentColor"/><g fill="#fff"><path d="M17.466 21.624c-.514 0-.988-.316-1.146-.829-.198-.632.138-1.303.771-1.501l7.666-2.469-1.205-8.254-13.317 4.621a1.19 1.19 0 0 1-1.521-.75 1.19 1.19 0 0 1 .751-1.521l13.89-4.818c.553-.197 1.166-.138 1.64.158a1.82 1.82 0 0 1 .85 1.284l1.344 9.183c.138.987-.494 1.994-1.482 2.33l-7.864 2.528-.375.04zm7.31.138c-.178-.632-.85-1.007-1.482-.81l-5.177 1.58c-2.331.79-3.28.02-3.418-.099l-6.56-8.412a4.25 4.25 0 0 0-4.406-1.758l-3.122.987c-.237.889-.415 1.777-.514 2.686l4.228-1.363a1.84 1.84 0 0 1 1.857.81l6.659 8.551c.751.948 2.015 1.323 3.359 1.323.909 0 1.857-.178 2.687-.474l5.078-1.54c.632-.178 1.008-.829.81-1.481z"/><use href="#czlogo"/><use href="#czlogo" x="8.516" y="-2.172"/></g><defs><path id="czlogo" d="M18.689 28.654a1.94 1.94 0 0 1-1.936 1.935 1.94 1.94 0 0 1-1.936-1.935 1.94 1.94 0 0 1 1.936-1.935 1.94 1.94 0 0 1 1.936 1.935z"/></defs></svg>
              </span>
              Cartzilla
            </a>
          </div>
          <div class="col col-lg-9 d-flex align-items-center justify-content-end">

            <!-- Search visible on screens > 991px wide (lg breakpoint) -->
            <div class="position-relative flex-fill d-none d-lg-block pe-4 pe-xl-5">
              <i class="ci-search position-absolute top-50 translate-middle-y d-flex fs-lg text-white ms-3"></i>
              <input type="search" class="form-control form-control-lg form-icon-start border-white rounded-pill" placeholder="Search the products" id="searchInput">
            </div>

            <!-- Sale link visible on screens > 1200px wide (xl breakpoint) -->
            <a class="d-none d-xl-flex align-items-center text-decoration-none animate-shake navbar-stuck-hide me-3 me-xl-4 me-xxl-5" href="/catalog">
              <div class="btn btn-icon btn-lg fs-lg text-primary bg-body-secondary bg-opacity-75 pe-none rounded-circle">
                <i class="ci-percent animate-target"></i>
              </div>
              <div class="ps-2 text-nowrap">
                <div class="fs-xs text-body">Only this month</div>
                <div class="fw-medium text-white">Super Sale 20%</div>
              </div>
            </a>

            <!-- Button group -->
            <div class="d-flex align-items-center">

              <!-- Navbar stuck nav toggler -->
              <button type="button" class="navbar-toggler d-none navbar-stuck-show me-3" data-bs-toggle="collapse" data-bs-target="#stuckNav" aria-controls="stuckNav" aria-expanded="false" aria-label="Toggle navigation in navbar stuck state">
                <span class="navbar-toggler-icon"></span>
              </button>

              <!-- Theme switcher (light/dark/auto) -->
              <div class="dropdown">
                <button type="button" class="theme-switcher btn btn-icon btn-lg btn-outline-secondary fs-lg border-0 rounded-circle animate-scale" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Toggle theme (light)">
                  <span class="theme-icon-active d-flex animate-target">
                    <i class="ci-sun"></i>
                  </span>
                </button>
                <ul class="dropdown-menu" style="--cz-dropdown-min-width: 9rem">
                  <li>
                    <button type="button" class="dropdown-item active" data-bs-theme-value="light" aria-pressed="true">
                      <span class="theme-icon d-flex fs-base me-2">
                        <i class="ci-sun"></i>
                      </span>
                      <span class="theme-label">Light</span>
                      <i class="item-active-indicator ci-check ms-auto"></i>
                    </button>
                  </li>
                  <li>
                    <button type="button" class="dropdown-item" data-bs-theme-value="dark" aria-pressed="false">
                      <span class="theme-icon d-flex fs-base me-2">
                        <i class="ci-moon"></i>
                      </span>
                      <span class="theme-label">Dark</span>
                      <i class="item-active-indicator ci-check ms-auto"></i>
                    </button>
                  </li>
                  <li>
                    <button type="button" class="dropdown-item" data-bs-theme-value="auto" aria-pressed="false">
                      <span class="theme-icon d-flex fs-base me-2">
                        <i class="ci-auto"></i>
                      </span>
                      <span class="theme-label">Auto</span>
                      <i class="item-active-indicator ci-check ms-auto"></i>
                    </button>
                  </li>
                </ul>
              </div>

              <!-- Search toggle button visible on screens < 992px wide (lg breakpoint) -->
              <button type="button" class="btn btn-icon btn-lg fs-xl btn-outline-secondary border-0 rounded-circle animate-shake d-lg-none" data-bs-toggle="collapse" data-bs-target="#searchBar" aria-controls="searchBar" aria-expanded="false" aria-label="Toggle search bar">
                <i class="ci-search animate-target"></i>
              </button>

              <!-- Account button visible on screens > 768px wide (md breakpoint) -->
              <?php if ($user): ?>
              <div class="dropdown d-none d-md-block">
                <a class="btn btn-icon btn-lg fs-lg btn-outline-secondary border-0 rounded-circle animate-shake" href="#" data-bs-toggle="dropdown" aria-expanded="false">
                  <i class="ci-user animate-target"></i>
                  <span class="visually-hidden">Account</span>
                </a>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li><a class="dropdown-item" href="/cont/info">Contul meu</a></li>
                  <li><a class="dropdown-item" href="/cont/comenzi">Comenzile mele</a></li>
                  <li><a class="dropdown-item" href="/cont/wishlist">Lista de dorințe</a></li>
                  <li><hr class="dropdown-divider"></li>
                  <li><a class="dropdown-item" href="api/auth.php?action=logout">Sign Out</a></li>
                </ul>
              </div>
              <?php else: ?>
              <a class="btn btn-icon btn-lg fs-lg btn-outline-secondary border-0 rounded-circle animate-shake d-none d-md-inline-flex" href="/cont/login">
                <i class="ci-user animate-target"></i>
                <span class="visually-hidden">Account</span>
              </a>
              <?php endif; ?>

              <!-- Wishlist button visible on screens > 768px wide (md breakpoint) -->
              <a class="btn btn-icon btn-lg fs-lg btn-outline-secondary border-0 rounded-circle animate-pulse d-none d-md-inline-flex" href="/cont/wishlist">
                <i class="ci-heart animate-target"></i>
                <span class="visually-hidden">Wishlist</span>
              </a>

              <!-- Cart button -->
              <button type="button" class="btn btn-icon btn-lg btn-secondary position-relative rounded-circle ms-2" data-bs-toggle="offcanvas" data-bs-target="#shoppingCart" aria-controls="shoppingCart" aria-label="Shopping cart">
                <?php if ($cartCount > 0): ?>
                <span class="position-absolute top-0 start-100 mt-n1 ms-n3 badge text-bg-success border border-3 border-dark rounded-pill cart-badge" style="--cz-badge-padding-y: .25em; --cz-badge-padding-x: .42em"><?php echo $cartCount; ?></span>
                <?php endif; ?>
                <span class="position-absolute top-0 start-0 d-flex align-items-center justify-content-center w-100 h-100 rounded-circle animate-slide-end fs-lg">
                  <i class="ci-shopping-cart animate-target ms-n1"></i>
                </span>
              </button>
            </div>
          </div>
        </div>
        <div class="navbar-stuck-hide pb-1"></div>
      </div>

      <!-- Search visible on screens < 992px wide (lg breakpoint). It is hidden inside collapse by default -->
      <div class="collapse position-absolute top-100 z-2 w-100 bg-dark d-lg-none" id="searchBar">
        <div class="container position-relative my-3" data-bs-theme="dark">
          <i class="ci-search position-absolute top-50 translate-middle-y d-flex fs-lg text-white ms-3"></i>
          <input type="search" class="form-control form-icon-start border-white rounded-pill" placeholder="Search the products" data-autofocus="collapse" id="searchInputMobile">
        </div>
      </div>

      <!-- Main navigation that turns into offcanvas on screens < 992px wide (lg breakpoint) -->
      <div class="collapse navbar-stuck-hide" id="stuckNav">
        <nav class="offcanvas offcanvas-start" id="navbarNav" tabindex="-1" aria-labelledby="navbarNavLabel">
          <div class="offcanvas-header py-3">
            <h5 class="offcanvas-title" id="navbarNavLabel">Browse Cartzilla</h5>
            <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
          </div>
          <div class="offcanvas-body py-3 py-lg-0">
            <div class="container px-0 px-lg-3">
              <div class="row">
                <!-- Categories mega menu - will be populated dynamically -->
                <div class="col-lg-3">
                  <div class="navbar-nav">
                    <div class="dropdown w-100">
                      <div class="cursor-pointer d-none d-lg-block" data-bs-toggle="dropdown" data-bs-trigger="hover" data-bs-theme="dark">
                        <a class="position-absolute top-0 start-0 w-100 h-100" href="/categorii">
                          <span class="visually-hidden">Categorii</span>
                        </a>
                        <button type="button" class="btn btn-lg btn-secondary dropdown-toggle w-100 rounded-bottom-0 justify-content-start pe-none">
                          <i class="ci-grid fs-lg"></i>
                          <span class="ms-2 me-auto">Categorii</span>
                        </button>
                      </div>
                      <button type="button" class="btn btn-lg btn-secondary dropdown-toggle w-100 justify-content-start d-lg-none mb-2" data-bs-toggle="dropdown" data-bs-auto-close="outside">
                        <i class="ci-grid fs-lg"></i>
                        <span class="ms-2 me-auto">Categorii</span>
                      </button>
                      <?php echo renderCategoryMegaMenu($isHomePage); ?>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </nav>
      </div>
    </header>

