now please fix the  logic for adding items to cart in the products page:
<!DOCTYPE html>
<html><head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Loveessential - Our Products</title>
  <style>
  :root {
    --primary-color: #800000;
    --secondary-color: #F5E6D3;
    --background-color: #FFF5E6;
    --text-color: #333333;
    --light-text-color: #666666;
  }
  
  body {
    font-family: 'Roboto', sans-serif;
    margin: 0;
    padding: 0;
    background-color: var(--background-color);
    color: var(--text-color);
    line-height: 1.6;
  }
  
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  header {
    background-color: var(--secondary-color);
    padding: 20px 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .logo {
    font-size: 24px;
    font-weight: bold;
    color: var(--primary-color);
    text-decoration: none;
  }
  
  .nav-links {
    display: flex;
    gap: 20px;
  }
  
  .nav-links a {
    color: var(--text-color);
    text-decoration: none;
    transition: color 0.3s ease;
  }
  
  .nav-links a:hover {
    color: var(--primary-color);
  }
  
  .cart-icon {
    position: relative;
    font-size: 24px;
  }
  
  .cart-count {
    position: absolute;
    top: -10px;
    right: -10px;
    background-color: var(--primary-color);
    color: white;
    border-radius: 50%;
    padding: 2px 6px;
    font-size: 12px;
  }
  
  main {
    padding: 40px 0;
  }
  
  h1 {
    text-align: center;
    margin-bottom: 40px;
    color: var(--primary-color);
  }
  
  .product-container {
    display: flex;
    gap: 20px;
  }
  
  .filter-section {
    width: 200px;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  .filter-title {
    font-size: 18px;
    margin-bottom: 15px;
    color: var(--primary-color);
  }
  
  .filter-options {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .filter-option {
    cursor: pointer;
    padding: 5px;
    border-radius: 4px;
    transition: background-color 0.3s ease;
  }
  
  .filter-option:hover {
    background-color: var(--secondary-color);
  }
  
  .filter-option.active {
    background-color: var(--primary-color);
    color: white;
  }
  
  .product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    flex-grow: 1;
  }
  
  .product-card {
    background-color: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    max-width: 190px;
    padding-bottom: 30px;
  }
  
  .product-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
  }
  
  .product-image {
    width: 100%;
    height: 150px;
    object-fit: cover;
  }
  
  .product-info {
    padding: 15px;
  }
  
  .product-title {
    font-size: 16px;
    margin-bottom: 8px;
  }
  
  .product-description {
    font-size: 12px;
    color: var(--light-text-color);
    margin-bottom: 10px;
  }
  
  .product-price {
    font-weight: bold;
    color: var(--primary-color);
    margin-bottom: 10px;
  }
  
  .product-color {
    font-size: 12px;
    color: var(--light-text-color);
    margin-bottom: 10px;
  }
  
  .add-to-cart {
    display: block;
    width: 100%;
    padding: 8px;
    background-color: var(--primary-color);
    color: white;
    text-align: center;
    text-decoration: none;
    border-radius: 4px;
    transition: background-color 0.3s ease;
    cursor: pointer;
    border: none;
    font-size: 14px;
  }
  
  .add-to-cart:hover {
    background-color: #600000;
  }
  
  footer {
    background-color: var(--secondary-color);
    color: var(--text-color);
    padding: 20px 0;
    text-align: center;
  }
  
  .search-container {
    display: flex;
    justify-content: center;
    margin-bottom: 30px;
  }
  
  .search-input {
    width: 300px;
    padding: 10px;
    font-size: 16px;
    border: 1px solid #ccc;
    border-radius: 4px 0 0 4px;
  }
  
  .search-button {
    padding: 10px 20px;
    font-size: 16px;
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 0 4px 4px 0;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }
  
  .search-button:hover {
    background-color: #B71C1C;
  }
  
  .alert {
    position: fixed;
    top: 20px;
    right: 20px;
    background-color: #4CAF50;
    color: white;
    padding: 15px;
    border-radius: 4px;
    display: none;
    z-index: 1000;
  }
  
  .filter-toggle {
    display: none;
    align-items: center;
    cursor: pointer;
    font-size: 16px;
    margin-bottom: 15px;
  }
  
  .filter-toggle-icon {
    margin-left: 5px;
    transition: transform 0.3s ease;
  }
  
  .filter-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }
  
  .filter-overlay-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    width: 80%;
    max-width: 300px;
  }
  
  .filter-overlay-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }
  
  .filter-overlay-title {
    font-size: 18px;
    color: var(--primary-color);
  }
  
  .filter-overlay-close {
    cursor: pointer;
    font-size: 24px;
  }
  
  @media (max-width: 768px) {
    .container {
      padding: 0 15px;
    }
  
    .product-container {
      flex-direction: column;
    }
  
    .filter-section {
      width: 100%;
      display: none;
    }
  
    .filter-toggle {
      display: flex;
    }
  
    .product-grid {
      grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
    }
    
    .search-input {
      width: calc(100% - 80px);
      max-width: none;
    }
  
    .search-button {
      width: 80px;
      padding: 10px;
    }
  
    nav {
      flex-direction: column;
      align-items: center;
    }
  
    .nav-links {
      gap: 10px;
      align-items: center;
      text-align: center;
      margin-top: 10px;
      justify-content: center;
    }
  
    .nav-links a {
      margin: 5px;
    }
  }
  </style>
  </head>
  <body>
    <header>
      <nav class="container">
        <a href="/" class="logo">Loveessential</a>
        <div class="nav-links">
          <a href="/">Home</a>
          <a href="/products">Products</a>
          <a href="/about">About</a>
          <a href="/cart" class="cart-icon">🛒 <span class="cart-count">0</span></a>
        </div>
      </nav>
    </header>
  
    <main class="container">
      <h1>Our Products</h1>
      <div class="search-container">
        <input type="text" id="search-input" class="search-input" placeholder="Search products...">
        <button id="search-button" class="search-button">Search</button>
      </div>
      <div class="filter-toggle">
        Filter <span class="filter-toggle-icon">▼</span>
      </div>
      <div class="product-container">
        <aside class="filter-section">
          <h2 class="filter-title">Categories</h2>
          <div class="filter-options">
            <div class="filter-option" data-category="all">All</div>
            <div class="filter-option" data-category="oral care">Oral Care</div>
            <div class="filter-option" data-category="body care">Body Care</div>
            <div class="filter-option" data-category="skin care">Skin Care</div>
            <div class="filter-option" data-category="hair care">Hair Care</div>
            <div class="filter-option" data-category="stationery">Stationery</div>
            <div class="filter-option" data-category="accessories">Accessories</div>
          </div>
        </aside>
        <div class="product-grid" id="product-grid">
          <!-- Products will be dynamically inserted here -->
        </div>
      </div>
    </main>
  
    <div class="filter-overlay">
      <div class="filter-overlay-content">
        <div class="filter-overlay-header">
          <span class="filter-overlay-title">Filter by Category</span>
          <span class="filter-overlay-close">&times;</span>
        </div>
        <div class="filter-options">
          <div class="filter-option" data-category="all">All</div>
          <div class="filter-option" data-category="oral care">Oral Care</div>
          <div class="filter-option" data-category="body care">Body Care</div>
          <div class="filter-option" data-category="skin care">Skin Care</div>
          <div class="filter-option" data-category="hair care">Hair Care</div>
          <div class="filter-option" data-category="stationery">Stationery</div>
          <div class="filter-option" data-category="accessories">Accessories</div>
        </div>
      </div>
    </div>
  
    <footer>
      <p>&copy; 2024 Loveessential. All rights reserved.</p>
    </footer>
  
    <div id="alert" class="alert"></div>
  
    <script>
     document.addEventListener('DOMContentLoaded', function() {
      const searchInput = document.getElementById('search-input');
      const searchButton = document.getElementById('search-button');
      const productGrid = document.getElementById('product-grid');
      const cartCount = document.querySelector('.cart-count');
      const alertElement = document.getElementById('alert');
      const filterOptions = document.querySelectorAll('.filter-option');
      const filterToggle = document.querySelector('.filter-toggle');
      const filterOverlay = document.querySelector('.filter-overlay');
      const filterOverlayClose = document.querySelector('.filter-overlay-close');
      let quantityInput = 0
  
      let products = [];
      let countcart = 0;
      let currentCategory = 'all';
  
      function fetchProducts() {
          fetch('/fetch_products.php')
              .then(response => {
                  if (!response.ok) {
                      throw new Error('Network response was not ok');
                  }
                  return response.json();
              })
              .then(data => {
                  products = data;
                  displayProducts(products);
              })
              .catch(error => console.error('Error fetching products:', error));
      }
  
      function displayProducts(productsToShow) {
          productGrid.innerHTML = '';
          productsToShow.forEach(product => {
              if (currentCategory === 'all' || product.category.toLowerCase() === currentCategory) {
                  const productCard = document.createElement('div');
                  productCard.className = 'product-card';
  
                  let images;
                  try {
                      images = JSON.parse(product.images);
                  } catch (e) {
                      images = [];
                  }
                  const defaultImagePath = '/static/images/loveessential_ke-08092024-0007.jpeg'; 
                  const imageSrc = (product.images && product.images.length > 0) ? product.images[0] : defaultImagePath;
  
                  productCard.innerHTML = `
                      <img src="${imageSrc}" alt="${product.name.slice(0, 10)}..." onerror="this.onerror=null;this.src='${defaultImagePath}';" class="product-image">
                      <div class="product-info">
                          <h2 class="product-title">${product.name}</h2>
                          <p class="product-price">Ksh ${parseFloat(product.price).toFixed(2)}</p>
                          <button class="add-to-cart" data-id="${product.id}">Add to Cart</button>
                      </div>
                  `;
                  productGrid.appendChild(productCard);
              }
          });
      }
  
      function searchProducts() {
          const searchTerm = searchInput.value.toLowerCase().trim();
          const filteredProducts = products.filter(product => 
              (product.name.toLowerCase().includes(searchTerm) || 
              (product.description && product.description.toLowerCase().includes(searchTerm)) ||
              (product.category && product.category.toLowerCase().includes(searchTerm))) &&
              (currentCategory === 'all' || product.category.toLowerCase() === currentCategory)
          );
          displayProducts(filteredProducts);
      }
  
   // Function to Save Cart to Local Storage
   function saveCart() {
      localStorage.setItem('cart', JSON.stringify(cart));
    }

    // Function to Add Product to Cart
    function addToCart(product) {
      const existingProductIndex = cart.findIndex(item => item.id === product.id);
      if (existingProductIndex >= 0) {
        // If product already in cart, update quantity
        cart[existingProductIndex].quantity += product.quantity;
      } else {
        // Add new product to cart
        cart.push(product);
      }
      saveCart();
      updateCartCount();
      showAlert(`${product.name} has been added to your cart!`, 'success');
    }

    // Function to update cart count in the UI
    function updateCartCount() {
        const cart = JSON.parse(localStorage.getItem('cart')) || [];
        const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
        cartCount.textContent = totalItems;
    }
  
      function showAlert(message) {
          alertElement.textContent = message;
          alertElement.style.display = 'block';
          setTimeout(() => {
              alertElement.style.display = 'none';
          }, 3000);
      }
  
      function filterProducts(category) {
          currentCategory = category.toLowerCase();
          filterOptions.forEach(option => {
              option.classList.toggle('active', option.dataset.category === currentCategory);
          });
          displayProducts(products);
      }
  
      searchButton.addEventListener('click', searchProducts);
      
      searchInput.addEventListener('keyup', function(event) {
          if (event.key === 'Enter') {
              searchProducts();
          }
      });
  
     // Event delegation for 'Add to Cart' button click
     productGrid.addEventListener('click', function(event) {
      const addToCartButton = event.target.closest('.add-to-cart');
        if (addToCartButton) {
            const productId = parseInt(event.target.getAttribute('data-id'), 10);
            event.preventDefault();

        // Fetch product details from the DOM
        let product;
        if (addToCartButton.closest('.product-info')) {
          // Main Product
          const productInfo = addToCartButton.closest('.product-info');
          const productName = productInfo.querySelector('.product-title').textContent.trim();
          const productPriceText = productInfo.querySelector('.product-price').textContent.trim();
          const productPrice = parseFloat(productPriceText.replace(/[^\d.]/g, '')) || 0;
          const productImage = document.getElementsByClassName('product-image').src;
          const quantity = parseInt(quantityInput.value) || 1;

          // Validate quantity
          if (quantity < 1) {
            showAlert('Quantity must be at least 1.', 'error');
            return;
          }

          product = {
            id: productId,
            name: productName || 'Unnamed Product',
            price: productPrice,
            images: productImage,
            quantity: quantity
          };
        }
        if (product) {
          addToCart(product);
        } else {
          showAlert('Unable to add product to cart.', 'error');
        }
    }});
  
      filterOptions.forEach(option => {
          option.addEventListener('click', function() {
              filterProducts(this.dataset.category);
              if (window.innerWidth <= 768) {
                  filterOverlay.style.display = 'none';
              }
          });
      });
  
      filterToggle.addEventListener('click', function() {
          filterOverlay.style.display = 'block';
      });
  
      filterOverlayClose.addEventListener('click', function() {
          filterOverlay.style.display = 'none';
      });
  
      window.addEventListener('resize', function() {
          if (window.innerWidth > 768) {
              filterOverlay.style.display = 'none';
              document.querySelector('.filter-section').style.display = 'block';
          } else {
              document.querySelector('.filter-section').style.display = 'none';
          }
      });
  
      fetchProducts();
      updateCartCount();
  });
    </script>
  </body>
  </html>