<!-- Cart Modal -->
<div class="modal fade" id="cartModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header bg-success-subtle text-white">
                <h5 class="modal-title font-weight-bolder text-dark">Your Cart</h5>
                <button type="button" class="btn-close btn-close-dark" data-bs-dismiss="modal"></button>
            </div>

            <form action="index.php" method="POST" id="checkout-form-modal">
                <div class="modal-body">
                    <div class="table-responsive">
                        <table class="table table-stripped table-sm">
                            <thead class="table-info">
                                <tr>
                                    <th>Item</th>
                                    <th>Price</th>
                                    <th>Quantity</th>
                                    <th>Total</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody id="cart-items-modal">
                                <tr>
                                    <td colspan="5" class="text-center py-4">Your cart is empty.</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <h5 class="text-end">Total: ৳ <span id="cart-total-modal">0.00</span></h5>

                    <!-- Hidden inputs for checkout -->
                    <input type="hidden" name="cart_data" id="cart-data-modal">
                    <input type="hidden" name="total_amount" id="total-amount-modal">
                    <input type="hidden" name="checkout" value="1">
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Continue Shopping</button>
                    <button type="submit" class="btn btn-success">Proceed to Checkout</button>
                </div>
            </form>
        </div>
    </div>
</div>




<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/php-email-form/validate.js"></script>
<script src="assets/vendor/aos/aos.js"></script>
<script src="assets/vendor/glightbox/js/glightbox.min.js"></script>
<script src="assets/vendor/purecounter/purecounter_vanilla.js"></script>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>


<!-- Main JS File -->
<script src="assets/js/main.js"></script>
<script src="site-cart-helper/cart-helper.js"></script>

<script>
   document.addEventListener("DOMContentLoaded", () => {
    const cartCountEl = document.getElementById("cart-count");
    const cartItemsModalEl = document.getElementById("cart-items-modal");
    const cartTotalModalEl = document.getElementById("cart-total-modal");
    const checkoutFormModal = document.getElementById("checkout-form-modal");

    // Render cart in modal
    function renderCart() {
        const cart = cartHelper.getCart();
        cartItemsModalEl.innerHTML = "";

        if(cart.length === 0) {
            cartItemsModalEl.innerHTML = '<tr><td colspan="5" class="text-center py-4">Your cart is empty.</td></tr>';
            cartTotalModalEl.textContent = "0.00";
            if(cartCountEl) cartCountEl.textContent = "0";
            updateHiddenInputs();
            return;
        }

        let total = 0;
        cart.forEach(item => {
            const discountedPrice = item.price - (item.discount || 0);
            const itemTotal = discountedPrice * item.quantity;
            total += itemTotal;

            const row = document.createElement("tr");
            row.innerHTML = `
                <td>${item.name}</td>
                <td>${discountedPrice.toFixed(2)}</td>
                <td>
                    <div class="d-flex justify-content-center align-items-center">
                        <button class="btn btn-sm btn-secondary decrease-qty" data-id="${item.id}">-</button>
                        <span class="mx-2 qty-text">${item.quantity}</span>
                        <button class="btn btn-sm btn-secondary increase-qty" data-id="${item.id}">+</button>
                    </div>
                </td>
                <td>${itemTotal.toFixed(2)}</td>
                <td><button class="btn btn-sm btn-danger remove-item" data-id="${item.id}">Remove</button></td>
            `;
            cartItemsModalEl.appendChild(row);
        });

        cartTotalModalEl.textContent = total.toFixed(2);
        if(cartCountEl) cartCountEl.textContent = cart.reduce((sum,i) => sum + i.quantity, 0);

        updateHiddenInputs();
    }

    // Update hidden inputs for checkout
    function updateHiddenInputs() {
        const cart = cartHelper.getCart();
        document.getElementById("cart-data-modal").value = JSON.stringify(cart);
        document.getElementById("total-amount-modal").value = cart.reduce((sum, item) => sum + ((item.price - (item.discount || 0)) * item.quantity), 0).toFixed(2);
    }

    // Initial render
    renderCart();

    // Add to Cart buttons
    document.querySelectorAll(".add-to-cart-btn").forEach(btn => {
        btn.addEventListener("click", e => {
            e.preventDefault();
            const id = parseInt(btn.dataset.id);
            const name = btn.dataset.name;
            const price = parseFloat(btn.dataset.price);

            cartHelper.addItem(id, name, price, 1);
            renderCart();
        });
    });

    // Increase, decrease, remove in modal
    cartItemsModalEl.addEventListener("click", e => {
        const target = e.target;
        const id = parseInt(target.dataset.id);

        if(target.classList.contains("increase-qty")) cartHelper.increaseQuantity(id);
        if(target.classList.contains("decrease-qty")) cartHelper.decreaseQuantity(id);
        if(target.classList.contains("remove-item")) cartHelper.removeItem(id);

        renderCart();
    });

    // Ensure hidden inputs are updated before checkout
checkoutFormModal.addEventListener("submit", async function(e) {
    e.preventDefault(); // Prevent default form submission

    const cart = cartHelper.getCart();
    if(cart.length === 0) {
        alert("Your cart is empty!");
        return false;
    }

    updateHiddenInputs();

    const formData = new FormData(checkoutFormModal);

    try {
        const response = await fetch('checkout.php', {
            method: 'POST',
            body: formData
        });

        const result = await response.text();
        console.log("Server Response:", result);

        if(result.includes("Order Placed")) {
            // Clear cart
            cartHelper.emptyCart();
            renderCart();

            // SweetAlert with page reload after OK
            Swal.fire({
                icon: 'success',
                title: 'Order Placed!',
                text: 'Thank You For Dining With Us!',
                confirmButtonText: 'OK'
            }).then(() => {
                // Reload page after user clicks OK
                location.reload();
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Checkout Failed',
                text: result
            });
        }
    } catch(error) {
        console.error("Checkout error:", error);
        Swal.fire({
            icon: 'error',
            title: 'Checkout Failed',
            text: 'Something went wrong. Please try again.'
        });
    }
});


});

</script>




</body>

</html>