is my code ok esp the part about selcting images :
<!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">
   <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <style>
    /* Add some basic styles for better visibility */
    .product-image.selected {
      border: 2px solid #000;
    }
    .hidden {
      display: none;
    }
    .cart-item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
    .product-images img {
      width: 50px;
      height: 50px;
      margin-right: 10px;
      cursor: pointer;
    }
    .cart-count {
      background-color: red;
      color: white;
      border-radius: 50%;
      padding: 2px 6px;
      position: relative;
      top: -10px;
      right: 10px;
    }
  </style>
</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 Ksh</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>
          <p>Stay updated on our latest products and exclusive offers!</p>
          <div class="social-icons">
           
            <a href="https://www.instagram.com/loveessential_ke/" target="_blank" aria-label="Instagram"><i class="fab fa-instagram"></i></a>
            
          </div>
        </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;
          }
        });
      }

      // 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" data-index="${index}">
                  <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 currentCartItem = cartItems.querySelector(`.cart-item[data-index="${index}"]`);
              const imageContainer = currentCartItem.querySelector('.product-images');

              item.images.forEach((image, imgIndex) => {
                const img = document.createElement('img');
                img.src = image;
                img.alt = `${item.name} - Variant ${imgIndex + 1}`;
                img.className = 'product-image';
                img.dataset.image = image;
                if (imgIndex === 0) img.classList.add('selected'); // Select first image by default
                imageContainer.appendChild(img);
              });

              if (item.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');
                  }
                });
              }
            });
          }

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

      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));
          });
        });
      }

      function attachQuantityListeners() {
        const decreaseButtons = document.querySelectorAll('.quantity-btn.decrease');
        const increaseButtons = document.querySelectorAll('.quantity-btn.increase');
        const quantityInputs = document.querySelectorAll('.quantity-input');

        decreaseButtons.forEach(button => {
          button.addEventListener('click', (e) => {
            const index = e.target.getAttribute('data-index');
            if (cart[index].quantity > 1) {
              cart[index].quantity -= 1;
              saveCart();
              updateCartDisplay();
            }
          });
        });

        increaseButtons.forEach(button => {
          button.addEventListener('click', (e) => {
            const index = e.target.getAttribute('data-index');
            if (cart[index].quantity < 10) {
              cart[index].quantity += 1;
              saveCart();
              updateCartDisplay();
            }
          });
        });

        quantityInputs.forEach(input => {
          input.addEventListener('change', (e) => {
            const index = e.target.getAttribute('data-index');
            let value = parseInt(e.target.value);
            if (isNaN(value) || value < 1) {
              value = 1;
            } else if (value > 10) {
              value = 10;
            }
            cart[index].quantity = value;
            saveCart();
            updateCartDisplay();
          });
        });
      }

      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');
              // Reset shipping fee, will be set based on area selection
              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');
              // Set a fixed shipping fee or calculate based on logic
              shippingFee = 50.00; // Example fixed fee
              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>';
        }
        // Reset shipping fee when county changes
        shippingFeeElement.textContent = '0.00';
        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', (e) => {
        e.preventDefault(); // Prevent form submission

        const selectedDeliveryOptionElement = document.querySelector('input[name="delivery-option"]:checked');
        if (!selectedDeliveryOptionElement) {
          alert('Please select a delivery option.');
          return;
        }
        const selectedDeliveryOption = selectedDeliveryOptionElement.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.trim();

          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.trim();
          const email = document.getElementById('customer-email').value.trim();
          const phone = document.getElementById('customer-phone').value.trim();
          const mpesaCode = document.getElementById('mpesa-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 areaText = document.getElementById('area-select').options[document.getElementById('area-select').selectedIndex].text;
              const estate = document.getElementById('estate-name').value.trim();
              deliveryDetails = `County: ${county}\nArea: ${areaText}\nEstate: ${estate}`;
              break;
            case 'pickup mtaani':
              deliveryDetails = 'Pickup Mtaani';
              break;
            case 'by bus':
              const busArea = document.getElementById('address-details').value.trim();
              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 orderDetailsFormatted = `Email: ${email}\nPhone: ${phone}\nDelivery: ${selectedDeliveryOption}\n${deliveryDetails}\n\nOrder Details:\n${orderDetails}\n\nTotal: ${total}\nM-PESA Code: ${mpesaCode}`;
          whatsappMessage += orderDetailsFormatted;

          const encodedMessage = encodeURIComponent(whatsappMessage);
          const whatsappURL = `https://api.whatsapp.com/send?phone=254768919146&text=${encodedMessage}`;
          window.open(whatsappURL, '_blank');
          let orderimg = cart.map(item => getSelectedImage(item.id));
          console.log(orderimg)

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

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

          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 getSelectedImage(productId) {
        const imageContainer = document.querySelector(`.product-images[data-product-id="${productId}"]`);
        const selectedImage = imageContainer.querySelector('.product-image.selected');
        return selectedImage ? selectedImage.getAttribute('src') : '';
      }

      function sendEmail(to, subject, message, image) {
        fetch('/email', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            to,
            subject,
            image,
            message: message,
            isHtml: true
          })
        })
        .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>