<%@ page import="java.util.List" %>
<%@ page import="com.nisum.model.CartItem" %>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false"%>


<%
    List<CartItem> cartItems = (List<CartItem>) request.getAttribute("cartItems");
    double cartTotal = (double) request.getAttribute("cartTotal");
    int userId = (int) request.getAttribute("userId");
    int cartId = (int) request.getAttribute("cartId");

%>

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

    </head>
    <body>
        <div class="cart-container">
            <h1>Your Shopping Cart</h1>

            <% for (CartItem item : cartItems) { %>
            <div class="cart-item" id="row_<%= item.getCartItemId() %>" data-price="<%= item.getFinalPrice() / item.getQuantity() %>">
                <div class="product-image">
                   <img src="<%= item.getImageurl() %>" alt="<%= item.getProductName() %>" />
                </div>
                <div class="product-info">
                    <h2><%= item.getProductName() %></h2>
                    <p class="brand">by FashionHub</p>
                    <div class="details">
                        <span>Color: <%= item.getColor() %></span>
                        <span>Status: <span id="status_<%= item.getCartItemId() %>" class="status <%= item.getStockStatus().equals("In Stock") ? "in-stock" : "out-of-stock" %>">
                        <%= item.getStockStatus() %></span></span>
                </div>
                <div class="details">
                    <span>Quantity:
                        <select class="quantity" id="qty_<%= item.getCartItemId() %>"
                                onchange="updateQuantity(<%= item.getCartItemId() %>, this)"

                            <% for (int i = 0; i <= 10; i++) { %>
                                <option value="<%= i %>" <%= i == item.getQuantity() ? "selected" : "" %>><%= i %></option>
                            <% } %>
                        </select>
                    </span>
                </div>
                <label><input type="checkbox"/> This will be a gift</label>
                <div class="actions">
                    <button onclick="deleteCartItem(<%= item.getCartItemId() %>)">Delete</button>
                    <button disabled>Save for Later</button>
                    <button disabled>See more like this</button>
                </div>
            </div>
            <div class="product-price">
                <p class="price">Rs<%= item.getFinalPrice() %>
                    <span class="original">Rs<%= item.getUnitPrice() * item.getQuantity() %></span>
                </p>
                <p class="discount">(<%= item.getDiscountPercent() %>% OFF)</p>
            </div>
        </div>
    <% } %>

            <div class="cart-total">
                <p id="total">Total Cart Subtotal: Rs. <%= cartTotal %></p>
            </div>
            <div class="cart-actions" style="text-align: right; margin-top: 20px;">
                <button id="placeOrderBtn" disabled>Place Order</button>
            </div>
        </div>

        <script>

                console.log("hello");
                document.getElementById("placeOrderBtn").addEventListener("click", function () {
                    if (!this.disabled) {
                            var contextPath = '<%= request.getContextPath() %>';
                             var userId = <%= request.getAttribute("userId") %>;
                            var cartId = <%= request.getAttribute("cartId") %>;
                            window.location.href = contextPath + '/address?userId=' + userId + '&cartId=' + cartId;
                        }
                });

            function updateQuantity(cartItemId, selectElement) {
                const newQuantity = selectElement.value;

                fetch("update-quantity", {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: "cartItemId=" + encodeURIComponent(cartItemId)+"&newQuantity="+encodeURIComponent(newQuantity)
                })
                .then(res => res.text())
                .then(result => {
                    const statusEl = document.getElementById("status_" + cartItemId);
                    if (result.trim() === "out_of_stock") {
                        statusEl.innerText = "Out of Stock";
                        statusEl.classList.remove("in-stock");
                        statusEl.classList.add("out-of-stock");
                    } else {
                        statusEl.innerText = "In Stock";
                        statusEl.classList.remove("out-of-stock");
                        statusEl.classList.add("in-stock");
                    }

                    checkAllInStock();
                    location.reload();
                })
                .catch(error => {
                    console.error("Error:", error);
                    alert("Error updating quantity.");
                });
            }

            const contextPath = '<%= request.getContextPath() %>';
            console.log('hello');

            function deleteCartItem(cartItemId) {
                console.log("Deleting cartItemId:", cartItemId);
                fetch(contextPath + "/delete-item", {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: "cartItemId=" + encodeURIComponent(cartItemId)
                })
                .then(res => res.text())
                .then(result => {
                    if (result.trim() === "deleted") {
                        const row = document.getElementById("row_" + cartItemId);
                        if (row) row.remove();
                        checkAllInStock();
                        location.reload(); // update totals
                    } else {
                        alert("Failed to delete item.");
                    }
                })
                .catch(err => {
                    console.error("Error:", err);
                    alert("Error deleting item.");
                });
            }


            function checkAllInStock() {
                const statusElements = document.querySelectorAll(".status");
                const placeOrderBtn = document.getElementById("placeOrderBtn");
                let allInStock = true;

                statusElements.forEach(status => {
                    if (status.innerText.trim().toLowerCase() === "out of stock") {
                        allInStock = false;
                    }
                });

                placeOrderBtn.disabled = !allInStock;
            }

            checkAllInStock();
        </script>
    </body>
</html>