<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Post a Product</title>
    <link rel="stylesheet" href="styles.css"> <!-- คุณสามารถเพิ่ม CSS ตามที่คุณต้องการ -->
</head>
<body>
    <header>
        <h1>Post a New Product</h1>
    </header>

    <div class="form-container">
        <form id="post-product-form">
            <label for="product_name">Product Name:</label>
            <input type="text" id="product_name" name="product_name" required>

            <label for="product_price">Product Price:</label>
            <input type="number" id="product_price" name="product_price" required>

            <label for="product_img">Product Image URL:</label>
            <input type="url" id="product_img" name="product_img" required>

            <button type="submit">Post Product</button>
        </form>
    </div>

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

    <script>
        // Handle form submission
        document.getElementById('post-product-form').addEventListener('submit', async (e) => {
            e.preventDefault();

            const productName = document.getElementById('product_name').value;
            const productPrice = document.getElementById('product_price').value;
            const productImg = document.getElementById('product_img').value;

            try {
                const response = await fetch('/api/products', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        product_name: productName,
                        product_price: productPrice,
                        product_img: productImg
                    }),
                    credentials: 'same-origin', // ส่ง cookie ไปกับ request
                });

                if (response.ok) {
                    alert('Product posted successfully');
                    window.location.href = '/';  // เปลี่ยนเส้นทางไปหน้าหลัก
                } else {
                    const errorMessage = await response.text();
                    alert('Error posting product: ' + errorMessage);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('Error posting product');
            }
        });
    </script>
</body>
</html>