var form;

function openPopup(menuType, itemName, itemPrice) {
  form = document.createElement("form");
  form.classList.add("popup");

  var itemNameDisplay = document.createElement("p");
  itemNameDisplay.innerText = "Item: " + itemName + " (Menu Type: " + menuType + ")";
  form.appendChild(itemNameDisplay);

  var quantityInput = document.createElement("input");
  quantityInput.setAttribute("type", "number");
  quantityInput.setAttribute("placeholder", "Enter quantity");
  form.appendChild(quantityInput);

  var submitButton = document.createElement("button");
  submitButton.innerText = "Proceed";
  submitButton.setAttribute("type", "button");

  submitButton.addEventListener("click", function () {
    var quantity = parseInt(quantityInput.value) || 0;
    var totalPrice = quantity * itemPrice;

    addToCart(menuType, itemName, quantity, totalPrice);

    var cartData = JSON.parse(sessionStorage.getItem("cartData")) || [];
    cartData.push({
      menuType: menuType,
      itemName: itemName,
      quantity: quantity,
      totalPrice: totalPrice
    });

    saveCartData(cartData);

    document.body.removeChild(form); // Remove the form from the DOM
  });

  form.appendChild(submitButton);
  document.body.appendChild(form);
}

function addToCart(menuType, itemName, quantity, totalPrice) {
  var cartData = JSON.parse(sessionStorage.getItem("cartData")) || [];
  cartData.push({
    menuType: menuType,
    itemName: itemName,
    quantity: quantity,
    totalPrice: totalPrice
  });
  saveCartData(cartData);

  var cartItemLi = document.createElement("li");
  cartItemLi.setAttribute("data-total-price", totalPrice.toFixed(2));

  // Construct the cart item string
  var cartItemString = "Menu: " + menuType + ", Item: " + itemName + ", Quantity: " + quantity + ", Total Price: $" + totalPrice.toFixed(2);
  cartItemLi.innerText = cartItemString;

  var deleteButton = document.createElement("button");
  deleteButton.innerText = "Delete";
  deleteButton.style.backgroundColor = "#076339";
  deleteButton.style.padding = "4px 10px";
  deleteButton.style.borderRadius = "5px";
  deleteButton.style.marginLeft = "15px";
  deleteButton.style.color = "white";
  deleteButton.addEventListener("click", function () {
    removeFromCart(cartItemLi);
  });

  cartItemLi.appendChild(deleteButton);

  document.getElementById("cart-items").appendChild(cartItemLi);

  updateCartTotal();
}

function updateCartTotal() {
  var totalElement = document.getElementById("total");
  var total = calculateTotal();  // Assuming this function calculates the total correctly
  totalElement.innerText = "" + total;
}

function calculateTotal() {
  var cartItemsList = document.getElementById("cart-items").getElementsByTagName("li");
  var total = 0;

  for (var i = 0; i < cartItemsList.length; i++) {
    var totalPrice = parseFloat(cartItemsList[i].getAttribute("data-total-price"));
    console.log("Item " + i + " - Total Price: " + totalPrice);
    total += totalPrice;
  }

  console.log("Grand Total: " + total);
  return total.toFixed(2);
}

function closePopup() {
  var popup = document.getElementById("popup");
  popup.style.display = "none";
}

function removeFromCart(cartItem) {
  cartItem.parentNode.removeChild(cartItem);
  updateCartTotal();
}

function updateCartDisplay(cartData) {
  // You can implement this function if needed
}

function saveCartData(cartData) {
  sessionStorage.setItem("cartData", JSON.stringify(cartData));
  updateCartDisplay(cartData);
}

document.addEventListener("DOMContentLoaded", function () {
  updateCartTotal();
});

function addToCartFromPopup() {
  console.log("addToCartFromPopup function is being called.");
  var adults = document.getElementById("adults-popup").value;
  var kids = document.getElementById("kids-popup").value;

  var cartSummary = "Name: " + document.getElementById("fullNames").value + "\n";
  cartSummary += "Email: " + document.getElementById("email").value + "\n";
  cartSummary += "Room Number: " + document.getElementById("roomNumber").value + "\n\n";

  var cartItemsList = document.getElementById("cart-items").getElementsByTagName("li");
  var cartItemsArray = [];
  var total = 0; // Declare the total variable

  // Check if there are cart items before adding to cartSummary
  if (cartItemsList.length > 0) {
    cartSummary += "Booking Details:\n";
    for (var i = 0; i < cartItemsList.length; i++) {
      // Access the text content of the cart item directly
      var cartItemText = cartItemsList[i].innerText.trim();
      cartItemsArray.push(cartItemText);
      cartSummary += cartItemText + "\n";

      // Update the total based on each item's price
      total += parseFloat(cartItemsList[i].getAttribute("data-total-price"));
    }
  } else {
    cartSummary += "No items in the cart\n";
  }

  console.log("Cart Items List:", cartItemsArray);
  console.log("Calculated Total:", total);

  // Set the value of hidden input fields in the form
  document.getElementById("cartItems").value = JSON.stringify(cartItemsArray);

  // Check the actual type of the "total" element and update accordingly
  var totalElement = document.getElementById("total");
  if (totalElement.tagName.toLowerCase() === "input") {
    totalElement.value = total.toFixed(2);
  } else {
    totalElement.innerText = total.toFixed(2);
  }

  // Display the cart summary in the email form
  document.getElementById("emailContent").value = cartSummary;

  console.log("Sending email with cart summary:", cartSummary);

  // Update the total and close the popup
  updateCartTotal();
  closePopup();

  // Send email logic
  sendEmail(cartSummary);
  console.log("Cart items list:", cartItemsList);
  console.log("Cart summary:", cartSummary);
}
