From 270b4503780d7ae18a519301fb501b759baa520e Mon Sep 17 00:00:00 2001
From: 65160381 <65160381@go.buu.ac.th>
Date: Tue, 25 Mar 2025 02:25:55 +0700
Subject: [PATCH] 8.6

---
 app.js                   |   1 -
 public/checkout.html     | 120 +++++++++++++++++++++++++++++++++++++++
 public/post-product.html |  70 +++++++++++++++++++++++
 public/styles/cart.css   |  21 +++++--
 4 files changed, 206 insertions(+), 6 deletions(-)
 create mode 100644 public/checkout.html
 create mode 100644 public/post-product.html

diff --git a/app.js b/app.js
index 10703b8..e8d9481 100644
--- a/app.js
+++ b/app.js
@@ -210,7 +210,6 @@ app.post('/api/products', (req, res) => {
     });
 });
 
-
 // ดึงสินค้าของผู้ใช้
 app.get('/api/user/products', (req, res) => {
     if (!req.session.user) {
diff --git a/public/checkout.html b/public/checkout.html
new file mode 100644
index 0000000..4818cc3
--- /dev/null
+++ b/public/checkout.html
@@ -0,0 +1,120 @@
+<!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/checkout.css">
+</head>
+<body>
+    <header>
+        <h1>ASA Checkout</h1>
+    </header>
+
+    <div class="cart-items" id="cart-items">
+        <!-- Cart items will be dynamically loaded here -->
+    </div>
+
+    <footer>
+        <p>&copy; 2025 ASA</p>
+        <div class="checkout-button" onclick="processCheckout()">Confirm and Checkout</div>
+    </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>
diff --git a/public/post-product.html b/public/post-product.html
new file mode 100644
index 0000000..d5a4e55
--- /dev/null
+++ b/public/post-product.html
@@ -0,0 +1,70 @@
+<!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>
diff --git a/public/styles/cart.css b/public/styles/cart.css
index 98e3832..a136c56 100644
--- a/public/styles/cart.css
+++ b/public/styles/cart.css
@@ -11,28 +11,30 @@ header {
     background-color: #007bff;
     color: white;
     padding: 20px;
-    text-align: center;
+    display: flex;
+    justify-content: space-between;
+    align-items: center;
 }
 
 header h1 {
     margin: 0;
 }
 
+header .cart-info {
+    font-size: 18px;
+}
+
 footer {
     background-color: #007bff;
     color: white;
     padding: 10px;
     text-align: center;
-    position: fixed;
-    width: 100%;
-    bottom: 0;
 }
 
 footer .checkout {
     background-color: #28a745;
     color: white;
     padding: 10px 20px;
-    text-align: center;
     cursor: pointer;
     border-radius: 5px;
     margin-top: 10px;
@@ -133,4 +135,13 @@ footer .checkout:hover {
     .cart-item div {
         margin-left: 0;
     }
+
+    header {
+        flex-direction: column;
+        text-align: center;
+    }
+
+    header .cart-info {
+        margin-top: 10px;
+    }
 }
-- 
GitLab