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

    <header>
        <div class="logo">
            <h1>ASA</h1>
        </div>
        <div class="search-bar">
            <input type="text" id="search" placeholder="Search for products..." oninput="searchProducts()">
        </div>
        <div class="cart">
            <a href="cart.html">Cart (<span id="cart-item-count">0</span>)</a>
        </div>
        <div class="user-info">
            <span id="welcome-message">Welcome, User</span> <!-- Display User's Name here -->
            <a href="edit-order.html" class="edit-order-btn">Edit Order</a> <!-- ปุ่ม Edit Order -->
        </div>
        <div class="logout">
            <a href="/logout">Logout</a>
        </div>
    </header>

    <div class="products" id="product-list">
        <!-- Products will be dynamically loaded here -->
    </div>

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

    <script>
        // Fetch and display products
        async function fetchProducts(searchQuery = '') {
            try {
                const response = await fetch(`/api/products?search=${searchQuery}`);
                const products = await response.json();
                console.log('Fetched Products:', products);  // เพิ่มการตรวจสอบข้อมูล
                renderProducts(products);
            } catch (error) {
                console.error('Error fetching products:', error);
            }
        }

        function renderProducts(products) {
            const productContainer = document.querySelector('.products');
            productContainer.innerHTML = '';

            products.forEach(product => {
                const productDiv = document.createElement('div');
                productDiv.classList.add('product');
                productDiv.innerHTML = `
                    <img src="${product.product_img}" alt="${product.product_name}">
                    <h3>${product.product_name}</h3>
                    <p>$${product.product_price}</p>
                    <button onclick="addToCart(${product.product_id}, '${product.product_name}', ${product.product_price}, '${product.product_img}')">Add to Cart</button>
                `;
                productContainer.appendChild(productDiv);
            });
        }

        function searchProducts() {
            const searchQuery = document.getElementById('search').value.toLowerCase();
            fetchProducts(searchQuery);
        }

        // Add item to the cart
        function addToCart(productId, productName, productPrice, productImg) {
            let cart = JSON.parse(localStorage.getItem('cart')) || [];
            const existingItem = cart.find(item => item.id === productId);

            if (existingItem) {
                existingItem.quantity++;
            } else {
                cart.push({
                    id: productId,
                    name: productName,
                    price: productPrice,
                    img: productImg,
                    quantity: 1
                });
            }

            localStorage.setItem('cart', JSON.stringify(cart));
            updateCart();
            alert(`${productName} added to cart!`);
        }

        // Update cart item count
        function updateCart() {
            let cart = JSON.parse(localStorage.getItem('cart')) || [];
            const cartItemCount = document.getElementById('cart-item-count');
            const totalQuantity = cart.reduce((sum, item) => sum + item.quantity, 0);
            cartItemCount.textContent = totalQuantity;
        }

        async function displayUsername() {
            try {
                const response = await fetch('/api/getUser');  // Endpoint to get the username
                const user = await response.json();
                document.getElementById('welcome-message').innerText = `Welcome, ${user.fname} ${user.lname}`;
            } catch (error) {
                console.log('Error fetching user info:', error);
            }
        }

        // Initially load products and cart item count
        fetchProducts();  // Fetch all products initially
        updateCart(); // Update cart count when page loads
        displayUsername(); // Display user info when page loads
    </script>
</body>
</html>