<?php
$page_title = 'Wellness Store | Herbal Wellness Care';
$page_description = 'Premium herbal products and wellness essentials';
$page_content = function () { ?>

<div class="min-h-screen bg-hero py-8">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <!-- Header -->
    <div class="text-center mb-12">
      <h1 class="font-display text-4xl md:text-5xl font-bold text-neutral-900 mb-4">
        Wellness <span class="text-primary">Store</span>
      </h1>
      <p class="text-xl text-neutral-600 max-w-3xl mx-auto">
        Discover premium herbal products, wellness essentials, and natural remedies curated by our expert practitioners.
      </p>
    </div>

    <!-- Filters -->
    <div class="card p-6 mb-8">
      <div class="flex flex-wrap gap-4 items-center justify-between">
        <div class="flex flex-wrap gap-4">
          <select id="category-filter" class="form-input">
            <option value="">All Categories</option>
            <option value="herbs">Herbs & Tinctures</option>
            <option value="supplements">Supplements</option>
            <option value="teas">Herbal Teas</option>
            <option value="oils">Essential Oils</option>
          </select>
          <select id="price-filter" class="form-input">
            <option value="">Any Price</option>
            <option value="0-25">Under $25</option>
            <option value="25-50">$25 - $50</option>
            <option value="50-100">$50 - $100</option>
            <option value="100+">$100+</option>
          </select>
        </div>
        <div class="flex gap-4">
          <div class="relative">
            <input type="text" id="search-input" placeholder="Search products..." class="form-input pl-10">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <i class="fas fa-search text-neutral-400"></i>
            </div>
          </div>
          <button onclick="toggleCart()" class="btn btn-secondary">
            <i class="fas fa-shopping-cart mr-2"></i>
            Cart (<span id="cart-count">0</span>)
          </button>
        </div>
      </div>
    </div>

    <!-- Products Grid -->
    <div id="products-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
      <!-- Products will be loaded here -->
    </div>

    <!-- Loading State -->
    <div id="loading" class="text-center py-12">
      <i class="fas fa-spinner animate-spin text-3xl text-primary-500 mb-4"></i>
      <p class="text-neutral-600">Loading products...</p>
    </div>

    <!-- Load More -->
    <div class="text-center mt-8">
      <button id="load-more" onclick="loadMoreProducts()" class="btn btn-ghost" style="display:none">
        Load More Products
      </button>
    </div>
  </div>
</div>

<!-- Shopping Cart Modal -->
<div id="cart-modal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
  <div class="card max-w-md w-full mx-4 max-h-[80vh] overflow-y-auto">
    <div class="p-6">
      <div class="flex justify-between items-center mb-6">
        <h3 class="text-xl font-bold text-neutral-900">Shopping Cart</h3>
        <button onclick="toggleCart()" class="text-neutral-400 hover:text-neutral-600 text-2xl">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <div id="cart-items" class="space-y-4 mb-6">
        <p class="text-neutral-500 text-center py-8">Your cart is empty</p>
      </div>
      
      <div id="cart-total" class="border-t border-neutral-200 pt-6 hidden">
        <div class="flex justify-between items-center mb-6">
          <span class="text-lg font-bold text-neutral-900">
            Total: $<span id="total-amount">0.00</span>
          </span>
        </div>
        <button onclick="checkout()" class="btn btn-primary w-full">
          <i class="fas fa-credit-card mr-2"></i>
          Proceed to Checkout
        </button>
      </div>
    </div>
  </div>
</div>

<script>
let products = [];
let cart = JSON.parse(localStorage.getItem('hw_cart') || '[]');
let currentOffset = 0;
const limit = 12;

async function loadProducts(reset = true) {
  if (reset) {
    currentOffset = 0;
    products = [];
  }
  
  const category = document.getElementById('category-filter').value;
  const search = document.getElementById('search-input').value;
  
  try {
    const params = new URLSearchParams({
      limit: limit.toString(),
      offset: currentOffset.toString()
    });
    if (category) params.append('category', category);
    if (search) params.append('search', search);
    
    const response = await fetch(`/atasteofafricanmarketplace/api/store/products.php?${params}`);
    const data = await response.json();
    
    if (data.success) {
      if (reset) {
        products = data.products;
      } else {
        products.push(...data.products);
      }
      
      renderProducts();
      
      const loadMoreBtn = document.getElementById('load-more');
      loadMoreBtn.style.display = data.pagination?.has_more ? 'block' : 'none';
      currentOffset += limit;
    }
  } catch (error) {
    console.error('Error loading products:', error);
  } finally {
    document.getElementById('loading').style.display = 'none';
  }
}

function renderProducts() {
  const grid = document.getElementById('products-grid');
  
  if (products.length === 0) {
    grid.innerHTML = '<div class="col-span-full text-center py-12"><p class="text-neutral-600">No products found</p></div>';
    return;
  }
  
  grid.innerHTML = products.map(product => `
    <div class="card group cursor-pointer" onclick="viewProduct(${product.id})">
      <div class="aspect-w-1 aspect-h-1 w-full overflow-hidden rounded-t-xl bg-neutral-200">
        <img src="${product.image_url || 'https://via.placeholder.com/400x400?text=Product+Image'}" 
             alt="${escapeHtml(product.name)}" 
             onerror="this.src='https://via.placeholder.com/400x400?text=Image+Not+Available'"
             class="w-full h-48 object-cover group-hover:scale-105 transition-transform duration-300"
             loading="lazy">
      </div>
      <div class="p-6">
        <div class="flex items-center justify-between mb-2">
          <span class="badge badge-primary text-xs">${product.category_name || 'Wellness'}</span>
          <span class="text-xs text-neutral-500">${product.stock_quantity || 0} in stock</span>
        </div>
        <h3 class="text-lg font-semibold text-neutral-900 mb-2 group-hover:text-primary-600 transition-colors">
          ${escapeHtml(product.name)}
        </h3>
        <p class="text-neutral-600 text-sm mb-4 line-clamp-2">
          ${escapeHtml(product.description || 'Premium wellness product')}
        </p>
        <div class="flex items-center justify-between">
          <span class="text-2xl font-bold text-primary-600">$${parseFloat(product.price).toFixed(2)}</span>
          <button onclick="event.stopPropagation(); addToCart(${product.id})" 
                  class="btn btn-primary btn-sm">
            <i class="fas fa-cart-plus mr-1"></i>
            Add to Cart
          </button>
        </div>
        ${product.coach_name ? `<div class="text-xs text-neutral-500 mt-2">by ${escapeHtml(product.coach_name)}</div>` : ''}
      </div>
    </div>
  `).join('');
}

function escapeHtml(text) {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return String(text || '').replace(/[&<>"']/g, m => map[m]);
}

function addToCart(productId) {
  const product = products.find(p => p.id == productId);
  if (!product) return;
  
  const existingItem = cart.find(item => item.product_id == productId);
  if (existingItem) {
    existingItem.quantity += 1;
  } else {
    cart.push({
      product_id: productId,
      name: product.name,
      price: product.price,
      quantity: 1
    });
  }
  
  saveCart();
  updateCartDisplay();
  
  // Show feedback
  const button = event.target.closest('button');
  const originalHTML = button.innerHTML;
  button.innerHTML = '<i class="fas fa-check mr-1"></i>Added!';
  button.disabled = true;
  setTimeout(() => {
    button.innerHTML = originalHTML;
    button.disabled = false;
  }, 1000);
}

function removeFromCart(productId) {
  cart = cart.filter(item => item.product_id != productId);
  saveCart();
  updateCartDisplay();
}

function updateQuantity(productId, quantity) {
  const item = cart.find(item => item.product_id == productId);
  if (item) {
    if (quantity <= 0) {
      removeFromCart(productId);
    } else {
      item.quantity = quantity;
      saveCart();
      updateCartDisplay();
    }
  }
}

function saveCart() {
  localStorage.setItem('hw_cart', JSON.stringify(cart));
}

function updateCartDisplay() {
  document.getElementById('cart-count').textContent = cart.reduce((sum, item) => sum + item.quantity, 0);
  
  const cartItems = document.getElementById('cart-items');
  const cartTotal = document.getElementById('cart-total');
  
  if (cart.length === 0) {
    cartItems.innerHTML = '<p class="text-neutral-500 text-center py-8">Your cart is empty</p>';
    cartTotal.classList.add('hidden');
    return;
  }
  
  cartItems.innerHTML = cart.map(item => `
    <div class="flex justify-between items-center p-4 bg-neutral-50 rounded-lg">
      <div class="flex-1">
        <div class="font-semibold text-neutral-900">${item.name}</div>
        <div class="text-sm text-neutral-600">$${item.price} each</div>
      </div>
      <div class="flex items-center gap-3">
        <button onclick="updateQuantity(${item.product_id}, ${item.quantity - 1})" 
                class="w-8 h-8 bg-neutral-200 hover:bg-neutral-300 rounded-full flex items-center justify-center">
          <i class="fas fa-minus text-xs"></i>
        </button>
        <span class="w-8 text-center font-medium">${item.quantity}</span>
        <button onclick="updateQuantity(${item.product_id}, ${item.quantity + 1})" 
                class="w-8 h-8 bg-neutral-200 hover:bg-neutral-300 rounded-full flex items-center justify-center">
          <i class="fas fa-plus text-xs"></i>
        </button>
        <button onclick="removeFromCart(${item.product_id})" 
                class="text-red-500 hover:text-red-700 ml-2">
          <i class="fas fa-trash"></i>
        </button>
      </div>
    </div>
  `).join('');
  
  const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
  document.getElementById('total-amount').textContent = total.toFixed(2);
  cartTotal.classList.remove('hidden');
}

function toggleCart() {
  const modal = document.getElementById('cart-modal');
  modal.classList.toggle('hidden');
  modal.classList.toggle('flex');
}

function viewProduct(productId) {
  console.log('View product:', productId);
}

async function checkout() {
  if (cart.length === 0) return;
  
  const total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
  
  try {
    const response = await fetch('/atasteofafricanmarketplace/api/store/checkout.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({
        items: cart.map(item => ({
          product_id: item.product_id,
          quantity: item.quantity
        })),
        payment_method: 'demo'
      })
    });
    
    const data = await response.json();
    
    if (data.success) {
      alert(`Order placed successfully! Order ID: ${data.order_id}`);
      cart = [];
      saveCart();
      updateCartDisplay();
      toggleCart();
      loadProducts();
    } else {
      alert(data.message || 'Order creation failed');
    }
  } catch (error) {
    alert('Network error. Please try again.');
  }
}

function loadMoreProducts() {
  loadProducts(false);
}

// Initialize
updateCartDisplay();
loadProducts();

// Search functionality
document.getElementById('search-input').addEventListener('keypress', function(e) {
  if (e.key === 'Enter') {
    loadProducts();
  }
});

document.getElementById('category-filter').addEventListener('change', function() {
  loadProducts();
});

document.getElementById('price-filter').addEventListener('change', function() {
  loadProducts();
});
</script>

<?php };
include __DIR__ . '/partials/layout.php';
?>