<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <!-- Favicon -->
  <link rel="icon" type="image/png" href="<?= base_url('uploads/MSFFLogo.png') ?>">

  <title>Welcome to Multiplex Safe Farms and Fresh</title>

  <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

  <style>
    html { scroll-behavior: smooth; } /* smooth scrolling */
    .fade-out { opacity: 0; transition: opacity 0.4s ease; }
    .fade-in  { opacity: 1; transition: opacity 0.4s ease; }
  </style>
</head>

<body class="bg-gray-100" 
      x-data="{ qty: {}, initQty(id){ this.qty[id] = 1 }, showCart: false, cartItems: [] }">

<!-- HEADER -->
<header class="w-full bg-white shadow sticky top-0 z-50">
  <div class="w-full px-8 flex items-center h-20 gap-10">

    <!-- LEFT SECTION: Logo + Store Title -->
    <div class="flex items-center gap-3 flex-shrink-0">
      <img src="<?= base_url('uploads/MSFFLogo.png') ?>"
           alt="Multiplex Farms Logo"
           class="h-14 w-auto">
      <div>
        <h3 class="text-2xl font-extrabold text-green-600 leading-tight">Multiplex Farms</h3>
        <p class="text-sm text-gray-700 italic leading-none">Safe Farms and Fresh Store</p>
      </div>
    </div>

    <!-- LOCATION + TIME -->
    <div class="hidden lg:flex flex-col leading-tight border-l pl-6">
      <div class="flex items-center gap-2 text-gray-800">
        <i class="fa-solid fa-clock text-green-600 text-xl"></i>
        <span class="text-xl font-semibold italic tracking-wide">12 Minutes</span>
      </div>
      <div class="flex items-center gap-2 text-gray-600 mt-1">
        <span class="text-sm"><?= esc($user_apartName) ?></span>
      </div>
    </div>

    <!-- SEARCH BOX -->
    <div class="flex-1">
      <form action="<?= base_url('search') ?>" method="GET" class="relative">
        <i class="fa-solid fa-magnifying-glass absolute left-3 top-3 text-gray-500"></i>
        <input type="text"
               id="typedSearch"
               name="q"
               class="w-full pl-10 pr-4 py-2 border rounded-xl focus:ring-2 focus:ring-green-500 focus:outline-none"
               placeholder="">
      </form>
    </div>

    <!-- CART + PROFILE -->
    <div class="flex items-center gap-6 flex-shrink-0">
      <a href="<?= base_url('order/cart') ?>" class="relative text-gray-700 hover:text-green-600 transition text-2xl">
        <i class="fa fa-cart-plus"></i>
        <span id="cart-count" class="absolute -top-2 -right-3 bg-red-600 text-xs font-bold px-2 py-0.5 rounded-full text-white"><?= $cart_count ?></span>
      </a>

      <?php if(session()->get('isLoggedIn')): ?>
      <div class="relative" x-data="{ open: false }">
        <button @click="open = !open"
                class="flex items-center bg-gray-100 px-3 py-2 rounded-xl hover:bg-gray-200 transition">
          <i class="fa-solid fa-user text-lg text-gray-700"></i>
        </button>

        <div x-show="open" @click.away="open = false"
             class="absolute right-0 mt-2 w-52 bg-white border rounded-xl shadow-lg py-2 z-50">
          <a href="<?= base_url('order-tracking') ?>" class="flex items-center px-4 py-2 hover:bg-gray-100 text-sm text-gray-700 transition">
            <i class="fa-solid fa-box text-gray-600"></i>
            <span class="ml-2">My Orders</span>
          </a>
          <hr class="my-1">
          <a href="<?= base_url('auth/logout') ?>" class="flex items-center px-4 py-2 hover:bg-gray-100 text-sm text-red-600 transition">
            <i class="fa-solid fa-right-from-bracket"></i>
            <span class="ml-2">Logout</span>
          </a>
        </div>
      </div>
      <?php endif; ?>
    </div>
  </div>

  <!-- NAVIGATION -->
  <nav class="w-full border-t bg-white">
    <ul class="flex justify-center items-center gap-10 px-10 py-4 overflow-x-auto whitespace-nowrap text-base">
      <?php 
      // Define nav items with category keys matching main sections
      $navItems = [
        "All" => "shop",
        "Vegetables" => "vegetables",
        "Leafy Vegetables" => "leafy",
        "Fruits" => "fruits",
        "Dairy Products" => "dairy",
        "Flowers" => "flowers",
        "Home Essentials" => "home"
      ];
      ?>
      <?php foreach($navItems as $label => $sectionId): ?>
      <li class="text-gray-600 hover:text-green-600 cursor-pointer flex flex-col items-center">
        <div class="flex items-center gap-2 text-lg">
          <?php
            $icons = [
              "All" => "fa-shopping-bag",
              "Vegetables" => "fa-carrot",
              "Leafy Vegetables" => "fa-leaf",
              "Fruits" => "fa-apple-whole",
              "Dairy Products" => "fa-cheese",
              "Flowers" => "fa-spa",
              "Home Essentials" => "fa-house"
            ];
          ?>
          <i class="fa-solid <?= $icons[$label] ?>"></i>
          <span><?= $label ?></span>
        </div>
        <div class="h-1.5 w-10 bg-green-600 rounded-full mt-1 hidden nav-underline"></div>
      </li>
      <?php endforeach; ?>
    </ul>
  </nav>
</header>

<!-- BANNER -->
<div class="relative bg-green-500 rounded-lg overflow-hidden max-w-6xl mx-auto my-6">
  <img src="https://images.unsplash.com/photo-1504674900247-0877df9cc836?auto=format&fit=crop&w=1200&q=80"
       alt="Banner" class="w-full h-56 object-cover opacity-90">
  <div class="absolute inset-0 bg-green-800 bg-opacity-40"></div>
  <div class="absolute inset-0 flex flex-col items-start justify-center px-6 text-white">
    <h2 class="text-2xl font-bold mb-2">Fruits & Vegetables</h2>
    <p class="text-sm mb-4">Your favourite Online Shop is now Online</p>
    <a href="#shop" class="bg-white text-green-600 px-3 py-1.5 rounded-md font-medium text-sm hover:bg-gray-100">Shop Now</a>
  </div>
</div>

<!-- Mini Category Banners -->
<div class="max-w-6xl mx-auto px-4 mb-8 grid grid-cols-1 md:grid-cols-3 gap-4">
  <div id="vegetables" class="bg-green-200 rounded-xl p-5 flex items-center justify-between">
    <div>
      <h3 class="text-lg font-bold text-green-900">Fresh Vegetables</h3>
      <p class="text-sm text-green-800">Farm fresh, daily supply</p>
      <a href="#vegetables" class="mt-2 inline-block bg-green-600 text-white text-xs px-3 py-1.5 rounded">Shop Now</a>
    </div>
    <img src="https://cdn-icons-png.flaticon.com/512/765/765519.png" alt="Vegetables" class="w-16 h-16">
  </div>
  <div id="fruits" class="bg-yellow-200 rounded-xl p-5 flex items-center justify-between">
    <div>
      <h3 class="text-lg font-bold text-yellow-900">Fresh Fruits</h3>
      <p class="text-sm text-yellow-800">Pure & fresh Fruits</p>
      <a href="#fruits" class="mt-2 inline-block bg-yellow-600 text-white text-xs px-3 py-1.5 rounded">Shop Now</a>
    </div>
    <img src="https://cdn-icons-png.flaticon.com/512/2909/2909761.png" alt="Fruits" class="w-16 h-16">
  </div>
  <div id="leafy" class="bg-green-300 rounded-xl p-5 flex items-center justify-between">
    <div>
      <h3 class="text-lg font-bold text-green-900">Leafy Vegetables</h3>
      <p class="text-sm text-green-800">Healthy & organic</p>
      <a href="#leafy" class="mt-2 inline-block bg-green-700 text-white text-xs px-3 py-1.5 rounded">Shop Now</a>
    </div>
    <img src="https://cdn-icons-png.flaticon.com/512/766/766116.png" alt="Leafy" class="w-16 h-16">
  </div>
</div>

<!-- CATEGORIES + PRODUCTS -->
<main id="shop" class="max-w-6xl mx-auto px-4 py-6">
  <?php foreach($categories as $catName => $products): ?>
    <section id="<?= strtolower(str_replace(' ', '', $catName)) ?>">
      <h2 class="text-2xl font-bold text-green-700 mb-4"><?= esc($catName) ?></h2>
      <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-5 mb-10">
        <?php foreach($products as $product): ?>
          <div class="bg-white border rounded-xl shadow hover:shadow-2xl transition p-4 flex flex-col relative">

            <?php if(!empty($product['variants'])): ?>
            <span class="absolute top-2 left-2 px-2 py-1 rounded-full text-xs font-semibold <?= $product['variants'][0]['quantity'] > 0 ? 'bg-green-600 text-white' : 'bg-red-600 text-white' ?>" 
                  id="stock-label-<?= $product['info']['id'] ?>">
              <?= $product['variants'][0]['quantity'] > 0 ? 'In Stock' : 'Out of Stock' ?>
            </span>
            <?php endif; ?>

            <a href="<?= base_url('productDetails/' . $product['info']['id']) ?>" class="block group">
              <div class="h-40 flex items-center justify-center mb-3 bg-white rounded-lg shadow-sm hover:shadow-md transition">
                <?php if (!empty($product['info']['image'])): ?>
                  <img src="<?= base_url('uploads/' . $product['info']['image']) ?>" 
                       alt="<?= esc($product['info']['name']) ?>" 
                       class="max-h-36 object-contain mx-auto transition-transform group-hover:scale-105">
                <?php else: ?>
                  <img src="<?= base_url('uploads/no-image.png') ?>" alt="No Image Available" class="max-h-36 object-contain mx-auto">
                <?php endif; ?>
              </div>
              <h4 class="text-lg font-semibold text-gray-800 mb-1 line-clamp-2 hover:text-green-600 transition">
                <?= esc($product['info']['name']) ?>
              </h4>
            </a>

            <?php if(!empty($product['variants'])): ?>
            <ul class="space-y-2">
              <li class="flex flex-col border p-3 rounded-lg bg-gray-50">
                <select class="border rounded px-2 py-1 text-sm variant-sku-dropdown mb-2">
                  <?php foreach($product['variants'] as $variant): ?>
                  <option value="<?= $variant['variant_id'] ?>" 
                          data-price="<?= $variant['offer_price'] ?>" 
                          data-stock="<?= $variant['quantity'] ?>" 
                          data-product-id="<?= $product['info']['id'] ?>">
                    <?= esc($variant['unit']) ?> - ₹<?= esc($variant['offer_price']) ?>
                  </option>
                  <?php endforeach; ?>
                </select>

                <div class="flex justify-between items-center mt-1">
                  <div class="flex items-center space-x-1">
                    <button type="button" class="qty-btn bg-gray-200 px-2 py-1 rounded text-sm">-</button>
                    <input type="text" name="quantity" value="1" class="w-10 text-center border rounded text-sm qty-input">
                    <button type="button" class="qty-btn bg-gray-200 px-2 py-1 rounded text-sm">+</button>
                  </div>

                  <form class="add-to-cart-form" method="post">
                    <input type="hidden" name="product_id" value="<?= $product['info']['id'] ?>">
                    <input type="hidden" name="variant_id" value="<?= $product['variants'][0]['variant_id'] ?>">
                    <input type="hidden" name="quantity" value="1" class="form-quantity"> 
                    <button type="submit" class="ml-2 bg-green-600 text-white text-xs px-3 py-1 rounded hover:bg-green-700">Add to Cart</button>
                  </form>
                </div>
              </li>
            </ul>
            <?php else: ?>
              <p class="text-gray-500 text-sm mt-2">No variants available</p>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    </section>
  <?php endforeach; ?>
</main>

<!-- JS -->
<script>
$(document).ready(function(){

  // Smooth nav scroll
  $("nav ul li").click(function(){
    let index = $(this).index();
    let sectionId = Object.values(<?= json_encode($navItems) ?>)[index];
    if(sectionId) {
      $('html, body').animate({ scrollTop: $('#' + sectionId).offset().top - 80 }, 600);
      $("nav ul li .nav-underline").addClass('hidden');
      $(this).find(".nav-underline").removeClass('hidden');
    }
  });

  // SKU change
  $(".variant-sku-dropdown").change(function(){
    let container = $(this).closest("li");
    let selected = $(this).find(":selected");
    let stock = selected.data("stock");
    let productId = selected.data("product-id");

    container.find("input[name='variant_id']").val(selected.val());
    let badge = $("#stock-label-" + productId);
    if(stock > 0){
      badge.text("In Stock").removeClass("bg-red-600").addClass("bg-green-600");
    } else {
      badge.text("Out of Stock").removeClass("bg-green-600").addClass("bg-red-600");
    }

    let qtyInput = container.find(".qty-input");
    if(parseInt(qtyInput.val()) > stock) qtyInput.val(stock);
    qtyInput.data('max', stock);
    container.find(".form-quantity").val(qtyInput.val());
  });

  // Quantity buttons
  $(".qty-btn").click(function(){
    let container = $(this).closest("li");
    let input = container.find(".qty-input");
    let formQty = container.find(".form-quantity");
    let selected = container.find(".variant-sku-dropdown :selected");
    let stock = parseInt(selected.data("stock")) || 1;
    let val = parseInt(input.val()) || 1;

    if($(this).text() === '+') val = (val < stock) ? val+1 : stock;
    else if($(this).text() === '-') val = val > 1 ? val-1 : 1;

    input.val(val);
    formQty.val(val);
  });

  // Qty input
  $(".qty-input").on('input', function(){
    let val = parseInt($(this).val()) || 1;
    let stock = parseInt($(this).closest("li").find(".variant-sku-dropdown :selected").data("stock")) || 1;
    if(val > stock) val = stock;
    if(val < 1) val = 1;
    $(this).val(val);
    $(this).closest("li").find(".form-quantity").val(val);
  });

  // Add to cart AJAX
  $(".add-to-cart-form").submit(function(e){
    e.preventDefault();
    let form = $(this);
    $.ajax({
      url: "<?= base_url('order/addToCart') ?>",
      type: "POST",
      data: form.serialize(),
      dataType: "json",
      success: function(response){
        if(response.success) $("#cart-count").text(response.cart_count);
        else alert(response.error || "Error adding to cart!");
      }
    });
  });

  // Placeholder typing effect
  const phrases = ['Search for "Vegetables"', 'Search for "Fruits"', 'Search for "Groceries"', 'Search for "Organic Items"'];
  let phraseIndex = 0, charIndex = 0, isDeleting = false;
  const searchInput = document.getElementById("typedSearch");

  function typeEffect() {
    let currentPhrase = phrases[phraseIndex];
    if (!isDeleting) {
      searchInput.placeholder = currentPhrase.substring(0, charIndex + 1);
      charIndex++;
      if (charIndex === currentPhrase.length) setTimeout(()=>{isDeleting=true}, 1000);
    } else {
      searchInput.placeholder = currentPhrase.substring(0, charIndex - 1);
      charIndex--;
      if (charIndex === 0) { isDeleting = false; phraseIndex = (phraseIndex + 1) % phrases.length; }
    }
    setTimeout(typeEffect, isDeleting ? 50 : 100);
  }
  typeEffect();
});
</script>

</body>
</html>
