<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout ASA</title>
    <link rel="stylesheet" href="styles/home.css">
</head>
<body>
    <header>
        <h1>ASA Checkout</h1>
    </header>

    <div class="cart-items" id="cart-items">
        <!-- Cart items will be dynamically loaded here -->
    </div>

    <button>
        <div class="checkout-button" onclick="processCheckout()">Confirm and Checkout</div>
    </button>

    <footer>
        <p>&copy; 2025 ASA</p>
        
    </footer>

    <script>
        // Load cart items from localStorage
        function loadCart() {
            const cart = JSON.parse(localStorage.getItem('cart')) || [];
            const cartItemsContainer = document.getElementById('cart-items');
            cartItemsContainer.innerHTML = '';

            if (cart.length === 0) {
                cartItemsContainer.innerHTML = '<p>Your cart is empty!</p>';
            }

            cart.forEach(item => {
                const itemDiv = document.createElement('div');
                itemDiv.classList.add('cart-item');
                itemDiv.innerHTML = `
                    <img src="${item.img}" alt="${item.name}">
                    <div>
                        <h3>${item.name}</h3>
                        <p>$${item.price}</p>
                        <p>Quantity: ${item.quantity}</p>
                    </div>
                `;
                cartItemsContainer.appendChild(itemDiv);
            });

            console.log("Cart loaded: ", cart);  // Log the cart details
        }

        async function processCheckout() {
            const cart = JSON.parse(localStorage.getItem('cart')) || [];
            const user = await getUserInfo();  // Get user info from session

            // If the user is not logged in
            if (!user) {
                alert("Please log in first.");
                return;
            }

            // Log the checkout details for debugging
            console.log("Proceeding with checkout...");
            console.log("User ID: ", user.user_id);
            console.log("Cart Details: ", cart);

            try {
                const response = await fetch('/api/checkout', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        user_id: user.user_id,  // Use the user_id from session
                        cart: cart
                    }),
                    credentials: 'same-origin', // This ensures that the cookie is sent along with the request
                });

                if (response.ok) {
                    console.log("Checkout successful!");
                    alert("Checkout successful!");
                    localStorage.removeItem('cart');  // Remove cart after checkout
                    window.location.href = "/";  // Redirect to home page
                } else {
                    const errorMessage = await response.text();
                    console.error("Checkout failed: ", errorMessage);
                    alert("Error during checkout: " + errorMessage);
                }
            } catch (error) {
                console.error('Error during checkout process:', error);
                alert('Error during checkout');
            }
        }

        // Get user info from session
        async function getUserInfo() {
            try {
                const response = await fetch('/api/getUser');
                if (response.ok) {
                    const data = await response.json();
                    console.log("User Info: ", data);  // Log the user information
                    return data;
                } else {
                    console.log('User is not logged in');
                    alert('Please log in first.');
                    window.location.href = '/login';
                    return null;
                }
            } catch (error) {
                console.error('Error fetching user info:', error);
                alert('Error fetching user info');
                return null;
            }
        }

        // Load cart items and user info when page loads
        loadCart();  // Load the cart items when page loads
    </script>
</body>
</html>