<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" %>
<jsp:useBean id="product" scope="request" type="com.nisum.model.Product" />

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>FashionHub</title>
  <link rel="icon" href="./images/NISUM.jpeg" type="image/x-icon">
  <link rel="stylesheet" href="./CSS/productInfo.css">

</head>
<body>

<div class="product-container">
  <div class="product-image">
    <img src=${product.imageurl} alt="${product.name}">
  </div>
  <div class="product-details">
    <h2>${product.name}</h2>
    <p>by <strong>FashionHub</strong></p>
    <p class="price">
      ₹${product.sellingPrice}
      <span class="original-price">₹${product.mrp}</span>
      <span class="discount">(${product.discountPercent}% OFF)</span>
    </p>

    <div class="offers">
      <strong>Available Offers:</strong>
      <p>• Get 10% off with HDFC Bank Cards</p>
      <p>• Free shipping on orders above ₹499</p>
      <p>• Flat ₹100 cashback on Paytm UPI</p>
    </div>

    <div class="selectors">
      <label for="size">Size:</label>
      <select id="size">
        <option>M</option>
        <option>L</option>
        <option>XL</option>
      </select>

      <label for="quantity">Quantity:</label>
      <select id="quantity">
        <option value=1 selected>1</option>
        <option value=2>2</option>
        <option value=3 >3</option>
        <option value=4 >4</option>
      </select>
    </div>

    <p class="stock">Only 5 items left in stock!</p>

    <div class="buttons">
      <button class="add-cart" onclick="addToCart()">Add to Cart</button>
      <button class="go-cart" onclick="goToCart()">Go to Shopping Cart</button>
    </div>
  </div>
</div>

<!-- Popup -->
<div id="popup">Item added to cart!</div>

<script>

  function UserId(){
    return 1;
  }
function addToCart() {
    console.log("add to cart called");
    const userId = UserId();
    const productId = parseInt('${product.id}');
    const quantity = parseInt(document.getElementById("quantity").value.trim());

    if (!quantity || quantity <= 0) {
        showPopup("Please enter a valid quantity.");
        return;
    }
    console.log(userId + productId + quantity)
    // Use URLSearchParams to properly encode data
    const formData = new URLSearchParams();
    formData.append("userId", userId);
    formData.append("productId", productId);
    formData.append("quantity", quantity);

    fetch('${pageContext.request.contextPath}/add-to-cart', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData.toString()
    })
    .then(response => {
        if (response.ok) {
            showPopup("Item added to cart!");
        } else {
            response.text().then(msg => {
                showPopup("Error: " + msg);
                console.log("Error: " + msg);
            });
        }
    })
    .catch(error => {
        console.error("Error:", error);
        showPopup("An error occurred.");
    });
}

  function showPopup(message) {
    const popup = document.getElementById('popup');
    popup.textContent = message;
    popup.style.display = 'block';
    setTimeout(() => popup.style.display = 'none', 2000);
  }

  function goToCart() {
    const userId = UserId();
    const contextPath = '${pageContext.request.contextPath}';
    window.location.href = contextPath + '/cart?userId=' + userId;
  }
</script>

</body>
</html>
