please fix my code:
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Loveessential - Quality Essentials for Your Daily Life</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="apple-touch-icon" sizes="76x76" href="/static/favicon/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon/favicon-16x16.png">
  <link rel="manifest" href="/static/favicon/site.webmanifest">
  <link rel="mask-icon" href="/static/favicon/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#da532c">
  <meta name="theme-color" content="#ffffff">
  <link rel="stylesheet" href="/static/css/cart.css">
</head>
<body>
  
  <header>
    <nav class="container">
      <a href="/" class="logo">Loveessential</a>
      <div class="nav-links">
        <a href="/">Home</a>
        <a href="/about">About Us</a>
        <a href="/all">Products</a>
        <a href="/cart" id="cartIcon" class="cart-icon">
         🛒
          <span class="cart-count">0</span>
        </a>
      </div>
          </nav>
  </header>

  <main class="container">
    <h1>Your Cart</h1>
    <div class="cart-container">
      <div class="cart-items">
        <!-- Cart items will be dynamically inserted here -->
      </div>
      <div class="cart-summary">
        <div class="summary-row">
          <span>Subtotal:</span>
          <span id="subtotal">0.00 Ksh</span>
        </div>
        <div class="summary-row">
          <span>Shipping:</span>
          <p><span id="shipping-fee">0.00</span>Ksh</p>
        </div>
        <div class="summary-row total">
          <span>Total:</span>
          <span id="total">$0.00</span>
        </div>
        <form id="shipping-form">
          <div class="form-group">
            <label for="customer-name">Your Name:</label>
            <input type="text" id="customer-name" name="customer-name" required>
          </div>
          <div class="form-group">
            <label for="customer-email">Email:</label>
            <input type="email" id="customer-email" name="customer-email" required>
          </div>
          <div class="form-group">
            <label for="customer-phone">Phone Number:</label>
            <input type="tel" id="customer-phone" name="customer-phone" required>
          </div>
          <div class="form-group">
            <label for="variant-selector">Select product variant:</label>
            <div class="product-images">
              <!-- Product images will be dynamically inserted here -->
            </div>
          </div>
          <div class="form-group delivery-options">
            <label>Delivery Option:</label>
            <div class="delivery-option">
              <input type="radio" id="pick-in-shop" name="delivery-option" value="pick in shop">
              <label for="pick-in-shop">Pick in Shop (Lake Turkana Business Center, shop F4)</label>
            </div>
            <div class="delivery-option">
              <input type="radio" id="pickup-mtaani" name="delivery-option" value="pickup mtaani">
              <label for="pickup-mtaani">Pickup Mtaani</label>
            </div>
            <div class="delivery-option">
              <input type="radio" id="doorstep-delivery" name="delivery-option" value="doorstep">
              <label for="doorstep-delivery">Doorstep Delivery</label>
            </div>
            <div class="delivery-option">
              <input type="radio" id="bus-delivery" name="delivery-option" value="by bus">
              <label for="bus-delivery">Bus Delivery</label>
            </div>
          </div>
          <div id="county-area-selection" class="hidden">
            <div class="form-group">
              <label for="county-select">Select County:</label>
              <select id="county-select" class="county-select" >
                <option value="">Select a county</option>
                <!-- Counties will be populated dynamically -->
              </select>
            </div>
            <div class="form-group">
              <label for="area-select">Select Area:</label>
              <select id="area-select" class="area-select">
                <option value="">Select an area</option>
                <!-- Areas will be populated dynamically -->
              </select>
            </div>
            <div class="form-group">
              <label for="estate-name">Estate Name:</label>
              <input type="text" id="estate-name" name="estate-name" >
            </div>
          </div>
          <div id="delivery-address" class="hidden">
            <div class="form-group">
              <label for="address-details">Delivery Address:</label>
              <textarea id="address-details" name="address-details" rows="1" placeholder="Enter bus station or pickup point"></textarea>
            </div>
          </div>
        </form>
        <div class="payment-instructions">
          <h4>How to pay with Lipa na M-PESA:</h4>
          <ol>
            <li>Go to M-PESA menu</li>
            <li>Select Lipa na M-PESA</li>
            <li>Select Buy Goods & Enter </li>
            <li>Enter 9174061 as Till Number</li>
            <li>Enter amount & follow prompts to complete</li>
            <li>Confirm payment to "Jean Imodia</li>
          </ol>
        </div>
        <div class="form-group">
          <label for="mpesa-code">M-PESA Transaction Code:</label>
          <input type="text" id="mpesa-code" name="mpesa-code" required placeholder="eg..SIU5F3I9U5">
        </div>
        <button class="checkout-btn">Proceed to Checkout</button>
      </div>
    </div>
  </main>

  <footer>
    <div class="container footer-content">
      <div class="footer-section">
        <h3>Quick Links</h3>
        <ul>
          <li><a href="/">All Products</a></li>
          <li><a href="/about">About Us</a></li>
          <li><a href="/products">Products</a></li>
          
        </ul>
      </div>
      <!--<div class="footer-section">-->
      <!--  <h3>Customer Service</h3>-->
      <!--  <ul>-->
      <!--    <li><a href="/shipping">Shipping Information</a></li>-->
      <!--    <li><a href="/returns">Returns & Exchanges</a></li>-->
      <!--    <li><a href="/privacy">Privacy Policy</a></li>-->
      <!--    <li><a href="/terms">Terms of Service</a></li>-->
      <!--  </ul>-->
      <!--</div>-->
      <div class="footer-section">
        <h3>Connect With Us</h3>
        <ul>
          
          <li><a href="https://instagram.com/Loveessential">Instagram</a></li>
         
        </ul>
      </div>
     
    </div>
  </footer>
<script>
  document.addEventListener('DOMContentLoaded', () => {
  const cartItems = document.querySelector('.cart-items');
  const cartSummary = document.querySelector('.cart-summary');
  const cartCountElement = document.querySelector('.cart-count');
  const shippingForm = document.getElementById('shipping-form');
  const deliveryOptions = document.querySelectorAll('input[name="delivery-option"]');
  const countyAreaSelection = document.getElementById('county-area-selection');
  const deliveryAddress = document.getElementById('delivery-address');
  const countySelect = document.getElementById('county-select');
  const areaSelect = document.getElementById('area-select');
  const shippingFeeElement = document.getElementById('shipping-fee');

  let cart = JSON.parse(localStorage.getItem('cart')) || [];
  let shippingData = [];

  // Initialize cart items with quantity if not present
  if (cart.length !== 0) {
    cart.forEach(item => {
      if (!item.hasOwnProperty('quantity')) {
        item.quantity = 1;
      }
    });
  }
//insert clickable images for each product in cart to act as product variants in the product-images div and add the selected value to the final message to the seller as image path. 
//lets remember a product can have multiple images  and all images must have a clickable box unless the product only has one image(only one variant so we dont need to chose a variant) 
//and images are stored as json and we need to have an onclick listener to make the box border bold 
 




  // Fetch shipping data from the server
  fetch('/php/fetch_delivery.php')
    .then(response => response.json())
    .then(data => {
      shippingData = data;
      console.log(shippingData);
      populateCounties();
    })
    .catch(error => console.error('Error fetching shipping data:', error));

  function populateCounties() {
    const counties = [...new Set(shippingData.map(item => item.county))];
    countySelect.innerHTML = '<option value="">Select a county</option>';
    counties.forEach(county => {
      const option = document.createElement('option');
      option.value = county;
      option.textContent = county;
      countySelect.appendChild(option);
    });
  }

  function populateAreas(county) {
    let areas = shippingData.filter(item => item.county === county && item.category === 'doorstep');
    areaSelect.innerHTML = '<option value="">Select an area</option>';
    areas.forEach(area => {
      const option = document.createElement('option');
      option.value = area.id;
      option.textContent = `${area.area} (${area.price} KSH)`;
      areaSelect.appendChild(option);
    });
  }

  function updateCartDisplay() {
    if (cartItems) {
      cartItems.innerHTML = '';
      let subtotal = 0;

      if (cart.length === 0) {
        cartItems.innerHTML = `
          <div class="empty-cart">
            <p>Your cart is empty.</p>
            <a href="/" class="continue-shopping">Continue Shopping</a>
          </div>
        `;
        if (cartSummary) cartSummary.style.display = 'none';
      } else {
        if (cartSummary) cartSummary.style.display = 'block';

        cart.forEach((item, index) => {
          const itemTotal = parseFloat(item.price) * item.quantity;
          subtotal += itemTotal;
          cartItems.innerHTML += `
            <div class="cart-item">
              // <img src="${item.images[0]}" alt="${item.name}" class="item-image" width="80" height="80">
               <div class="product-images" data-product-id="${item.id}"></div>
              <div class="item-details">
                <div class="item-name">${item.name}</div>
                <div class="item-price">${parseFloat(item.price).toFixed(2)} Ksh</div>
                <div class="item-quantity">
                  <button class="quantity-btn decrease" data-index="${index}">-</button>
                  <input type="number" class="quantity-input" value="${item.quantity}" min="1" max="10" data-index="${index}">
                  <button class="quantity-btn increase" data-index="${index}">+</button>
                </div>
              </div>
              <div class="item-actions">
                <button class="remove-item" data-index="${index}">Remove</button>
              </div>
            </div>
          `;
          const imageContainer = cartItems.querySelector('.product-images');
    item.images.forEach((image, index) => {
      const img = document.createElement('img');
      img.src = image;
      img.alt = `${item.name} - Variant ${index + 1}`;
      img.className = 'product-image';
      img.dataset.image = image;
      imageContainer.appendChild(img);
    });

    if (product.images.length > 1) {
      imageContainer.addEventListener('click', (e) => {
        if (e.target.classList.contains('product-image')) {
          imageContainer.querySelectorAll('.product-image').forEach(img => img.classList.remove('selected'));
          e.target.classList.add('selected');
        }
      });
    } else {
      imageContainer.querySelector('.product-image').classList.add('selected');
    }
        });
      }

      updateCartTotal();
      updateCartCount();
      attachRemoveListeners();
    }
  }

  function updateCartTotal() {
    let subtotal = cart.reduce((total, item) => total + (parseFloat(item.price) * item.quantity), 0);
    const shippingFee = parseFloat(shippingFeeElement.textContent) || 0;
    const total = subtotal + shippingFee;

    document.getElementById('subtotal').textContent = `${subtotal.toFixed(2)} Ksh`;
    document.getElementById('total').textContent = `${total.toFixed(2)} Ksh`;
  }

  function updateCartCount() {
    if (cartCountElement) cartCountElement.textContent = cart.reduce((total, item) => total + item.quantity, 0);
  }

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

  function removeFromCart(index) {
    cart.splice(index, 1);
    saveCart();
    updateCartDisplay();
  }

  function attachRemoveListeners() {
    const removeButtons = document.querySelectorAll('.remove-item');
    removeButtons.forEach(button => {
      button.addEventListener('click', (e) => {
        const index = e.target.getAttribute('data-index');
        removeFromCart(parseInt(index));
      });
    });
  }

  deliveryOptions.forEach(option => {
    option.addEventListener('change', () => {
      const selectedOption = option.value;
      countyAreaSelection.classList.add('hidden');
      deliveryAddress.classList.add('hidden');
      let shippingFee = 0;

      switch (selectedOption) {
        case 'doorstep':
          countyAreaSelection.classList.remove('hidden');
          break;
        case 'pickup mtaani':
          const pickupMtaani = shippingData.find(item => item.category === 'pickup mtaani');
          shippingFee = pickupMtaani ? parseFloat(pickupMtaani.price) : 0;
          break;
        case 'by bus':
          deliveryAddress.classList.remove('hidden');
          break;
        case 'pick in shop':
          // No additional UI elements needed, shipping fee is 0
          break;
      }

      shippingFeeElement.textContent = shippingFee.toFixed(2);
      updateCartTotal();
    });
  });

  countySelect.addEventListener('change', () => {
    const selectedCounty = countySelect.value;
    if (selectedCounty) {
      populateAreas(selectedCounty);
    } else {
      areaSelect.innerHTML = '<option value="">Select an area</option>';
    }
    updateCartTotal();
  });

  areaSelect.addEventListener('change', () => {
    const selectedAreaId = areaSelect.value;
    const selectedArea = shippingData.find(item => item.id.toString() === selectedAreaId);
    const shippingFee = selectedArea ? parseFloat(selectedArea.price) : 0;
    shippingFeeElement.textContent = shippingFee.toFixed(2);
    updateCartTotal();
  });

  document.querySelector('.checkout-btn').addEventListener('click', () => {
    const selectedDeliveryOption = document.querySelector('input[name="delivery-option"]:checked').value;

    let isValid = true;

    // Only validate county and area for "doorstep" option
    if (selectedDeliveryOption === 'doorstep') {
      const county = document.getElementById('county-select').value;
      const area = document.getElementById('area-select').value;

      if (!county || !area) {
        alert('Please select a county and area for doorstep delivery.');
        isValid = false;
      }
    }

    // Only validate the bus delivery address for "by bus" option
    if (selectedDeliveryOption === 'by bus') {
      const busArea = document.getElementById('address-details').value;

      if (!busArea) {
        alert('Please enter a bus delivery area.');
        isValid = false;
      }
    }

    // If valid, proceed with order processing
    if (isValid && shippingForm.checkValidity()) {
      const name = document.getElementById('customer-name').value;
      const email = document.getElementById('customer-email').value;
      const phone = document.getElementById('customer-phone').value;
      const mpesaCode = document.getElementById('mpesa-code').value;
      const color = document.getElementById('voucher-code').value.trim();

      let orderDetails = cart.map(item => `${item.name} - ${item.price} Ksh x ${item.quantity}`).join('\n');
      const total = document.getElementById('total').textContent;

      let deliveryDetails = '';
      
      // Handle delivery details based on option
      switch (selectedDeliveryOption) {
        case 'doorstep':
          const county = document.getElementById('county-select').value;
          const area = document.getElementById('area-select').options[document.getElementById('area-select').selectedIndex].text;
          const estate = document.getElementById('estate-name').value;
          deliveryDetails = `County: ${county}\nArea: ${area}\nEstate: ${estate}`;
          break;
        case 'pickup mtaani':
          deliveryDetails = 'Pickup Mtaani';
          break;
        case 'by bus':
          const busArea = document.getElementById('address-details').value;
          deliveryDetails = `Bus Delivery Area: ${busArea}`;
          break;
        case 'pick in shop':
          deliveryDetails = 'Pick in Shop';
          break;
      }

      // Process the order and send email/WhatsApp notifications
      let whatsappMessage = `New order from ${name}:\n\n`;
      let order = `Email: ${email}\n`;
      order += `Phone: ${phone}\n`;
      order += `Delivery: ${selectedDeliveryOption}\n`;
      order += `${deliveryDetails}\n`;
      order += `\nOrder Details:\n${orderDetails}`;
      order += `\nColor: ${color}\n`;
      order += `\nTotal: ${total}`;
      order += `\nM-PESA Code: ${mpesaCode}`;
      whatsappMessage += order;

      const encodedMessage = encodeURIComponent(whatsappMessage);
      const whatsappURL = `https://api.whatsapp.com/send?phone=254768919146&text=${encodedMessage}`;
      window.open(whatsappURL, '_blank');

      const buyerSubject = 'Thank you for your order!';
      const buyerMessage = `
        Dear ${name},<br><br>
        Thank you for your order from Loveessential.<br><br>
        Order Details:<br>--------------
        ${orderDetails.replace(/\n/g, '<br>')}<br><br>
        Delivery Information:<br>---------------------
        ${deliveryDetails.replace(/\n/g, '<br>')}<br><br>
        Total: ${total}<br>
        M-PESA Code: ${mpesaCode}<br><br>
        Best regards,<br>
        The Loveessential Team
      `;

      const sellerSubject = 'New order received!';
      const sellerMessage = `Dear Seller,<br><br>A new order has been received from ${name}.<br><br>${whatsappMessage.replace(/\n/g, '<br>')}`;
      let ordtails = cart.map(item => {
        const selectedVariant = document.querySelector(`.product-images[data-product-id="${item.id}"] .product-image.selected`);
        const variantInfo = selectedVariant ? ` (Variant: ${selectedVariant.alt})` : '';
        return `${variantInfo} - ${item.price} Ksh x ${item.quantity}`;
      }).join('\n');

      sellerMessage+=ordtails
      sendEmail(email, buyerSubject, buyerMessage);
      sendEmail('info@loveessential.co.ke', sellerSubject, sellerMessage);

      alert(`Thank you, ${name}! We've notified the seller.`);
      
      // Clear the cart and update display
      cart = [];
      saveCart();
      updateCartDisplay();
    } else {
      alert('Please fill out all required fields.');
    }
  });

  function sendEmail(to, subject, message) {
    fetch('/email', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        to,
        subject,
        message: message.replace(/\n/g, '<br>'), // Replace newlines with <br> tags
        isHtml: true // Ensure email is sent as HTML
      })
    })
    .then(response => {
      if (response.ok) {
        console.log('Email sent successfully');
      } else {
        console.error('Failed to send email');
      }
    })
    .catch(error => {
      console.error('Error sending email:', error);
    });
  }

  updateCartDisplay();
});
</script>
</body>
</html>