<%- include('partials/header') %>
<div class="container">
    <div class="cart">
        <h2>Shopping Cart</h2>
        <% if (cartItems.length === 0) { %>
            <div class="info-section">
                <p>Your cart is empty</p>
                <a href="/" class="continue-shopping">Continue Shopping</a>
            </div>
        <% } else { %>
            <div class="cart-items">
                <% cartItems.forEach(item => { %>
                    <div class="cart-item">
                        <div class="item-info">
                            <h3><%= item.name %></h3>
                            <p>Price: ฿<%= item.price.toLocaleString() %></p>
                            <p class="price">
                                Total: ฿<%= (item.price * item.quantity).toLocaleString() %>
                            </p>
                            <% if (item.stock < 5) { %>
                                <p style="color: var(--primary);">Only <%= item.stock %> items left!</p>
                            <% } %>
                        </div>

                        <form method="POST" action="/cart/update" style="display: flex; gap: 0.8rem; align-items: center;">
                            <input type="hidden" name="cartItemId" value="<%= item.id %>">
                            <input type="number" 
                                   name="quantity" 
                                   value="<%= item.quantity %>" 
                                   min="1" 
                                   max="<%= item.stock %>"
                                   style="width: 70px;">
                            <button type="button" class="update-btn" style="margin: 0; padding: 0.5rem 1rem;">
                                Update
                            </button>
                        </form>

                        <form action="/cart/remove" method="POST" style="text-align: right;">
                            <input type="hidden" name="cartItemId" value="<%= item.id %>">
                            <button type="submit" class="back-btn" style="margin: 0; padding: 0.5rem 1rem; background-color: red;">
                                Remove
                            </button>
                        </form>
                    </div>
                <% }); %>
            </div>

            <div class="cart-summary">
                <div class="total">
                    <h3 id="total-price">Total Amount: ฿<%= total.toLocaleString() %></h3>
                </div>
                <div class="order-actions">
                    <a href="/" class="back-btn">Continue Shopping</a>
                    <a href="/order/checkout" class="checkout-button">Proceed to Checkout</a>
                </div>
            </div>

            <script>
                document.querySelectorAll('.update-btn').forEach(button => {
                    button.addEventListener('click', async (event) => {
                        event.preventDefault();
                        const form = button.closest('form');
                        const cartItemId = form.querySelector('[name="cartItemId"]').value;
                        const quantity = form.querySelector('[name="quantity"]').value;

                        try {
                            const response = await fetch('/cart/update', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ cartItemId, quantity })
                            });

                            if (response.ok) {
                                const data = await response.json();
                                // อัปเดตราคารวมในหน้าเว็บ
                                document.getElementById('total-price').innerText = `Total Amount: ฿${data.total.toFixed(2)}`;
                            } else {
                                const error = await response.text();
                                alert(error);
                            }
                        } catch (error) {
                            console.error('Error updating cart:', error);
                        }
                    });
                });
            </script>
        <% } %>
    </div>
</div>
<%- include('partials/footer') %>