From 5b8d0ac45785d0b07d487f7fe3d27df33528d2fa Mon Sep 17 00:00:00 2001
From: 65160381 <65160381@go.buu.ac.th>
Date: Mon, 24 Mar 2025 15:49:21 +0000
Subject: [PATCH] Update 2 files

- /controllers/productController.js
- /controllers/registerController.js
---
 controllers/productController.js  | 128 ++++++++++++++++++++++++++++++
 controllers/registerController.js |  10 ++-
 2 files changed, 137 insertions(+), 1 deletion(-)
 create mode 100644 controllers/productController.js

diff --git a/controllers/productController.js b/controllers/productController.js
new file mode 100644
index 0000000..72b4436
--- /dev/null
+++ b/controllers/productController.js
@@ -0,0 +1,128 @@
+const pool = require('../db');
+
+exports.showAddProductForm = (req, res) => {
+   if (!req.session.userIdEmail) {
+       return res.redirect('/login');
+   }
+   res.render('addProduct');
+};
+
+exports.createProduct = async (req, res) => {
+    const { product_name, price, image, description } = req.body;
+    const owner = req.session.userIdEmail;
+    try {
+       const sql = 'INSERT INTO products (product_name, price, image, description, owner) VALUES (?, ?, ?, ?, ?)';
+       await pool.query(sql, [product_name, price, image, description, owner]);
+       res.redirect('/');
+    } catch (err) {
+       res.status(500).send('เกิดข้อผิดพลาดในการเพิ่มสินค้า: ' + err.message);
+    }
+};
+
+exports.showUpdateProductForm = async (req, res) => {
+    const productId = req.params.id;
+    if (!req.session.userIdEmail) {
+        return res.redirect('/login');
+    }
+    try {
+        const [rows] = await pool.query('SELECT * FROM products WHERE product_id = ?', [productId]);
+        if (rows.length === 0) {
+            return res.status(404).send('ไม่พบสินค้านี้');
+        }
+        res.render('editProduct', { product: rows[0] });
+    } catch (err) {
+        res.status(500).send('เกิดข้อผิดพลาดในการโหลดข้อมูลสินค้า: ' + err.message);
+    }
+};
+
+exports.updateProduct = async (req, res) => {
+    const productId = req.params.id;
+    const { product_name, price, image, description } = req.body;
+    const currentUserEmail = req.session.userIdEmail;
+
+    try {
+        const [rows] = await pool.query('SELECT * FROM products WHERE product_id = ?', [productId]);
+        if (rows.length === 0) {
+            return res.status(404).send('ไม่พบสินค้านี้');
+        }
+        const product = rows[0];
+        if (product.owner !== currentUserEmail) {
+            return res.status(403).send('คุณไม่มีสิทธิ์แก้ไขสินค้านี้');
+        }
+
+        const sql = 'UPDATE products SET product_name = ?, price = ?, image = ?, description = ? WHERE product_id = ?';
+        await pool.query(sql, [product_name, price, image, description, productId]);
+        
+        res.redirect('/');
+    } catch (err) {
+        res.status(500).send('เกิดข้อผิดพลาดในการอัปเดตสินค้า: ' + err.message);
+    }
+};
+
+exports.deleteProduct = async (req, res) => {
+    const productId = req.params.id;
+    const currentUserEmail = req.session.userIdEmail;
+    try {
+      const [rows] = await pool.query('SELECT * FROM products WHERE product_id = ?', [productId]);
+      if (rows.length === 0) {
+        return res.status(404).send('ไม่พบสินค้านี้');
+      }
+      const product = rows[0];
+      if (product.owner !== currentUserEmail) {
+        return res.status(403).send('คุณไม่มีสิทธิ์ลบสินค้านี้');
+      }
+
+      await pool.query('DELETE FROM products WHERE product_id = ?', [productId]);
+      res.redirect('/');
+    } catch (err) {
+      res.status(500).send('เกิดข้อผิดพลาดในการลบสินค้า: ' + err.message);
+    }
+};
+
+exports.searchProducts = async (req, res) => {
+    const searchQuery = req.query.q;
+    try {
+        const sql = 'SELECT * FROM products WHERE product_name LIKE ?';
+        const [rows] = await pool.query(sql, [`%${searchQuery}%`]);
+
+        res.render('searchResults', { products: rows, searchQuery });
+    } catch (err) {
+        res.status(500).send('เกิดข้อผิดพลาดในการค้นหา: ' + err.message);
+    }
+};
+
+exports.orderHistory = async (req, res) => {
+    if (!req.session.userIdEmail) {
+        return res.redirect('/login');
+    }
+
+    try {
+        const userEmail = req.session.userIdEmail;
+
+        const [user] = await pool.query('SELECT id FROM users WHERE email = ?', [userEmail]);
+        if (user.length === 0) {
+            return res.status(404).send('ไม่พบผู้ใช้งาน');
+        }
+        const userId = user[0].id;
+
+        const [orders] = await pool.query(
+            'SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC',
+            [userId]
+        );
+
+        for (let order of orders) {
+            const [items] = await pool.query(
+                `SELECT oi.*, p.product_name, p.image 
+                 FROM order_items oi 
+                 JOIN products p ON oi.product_id = p.product_id 
+                 WHERE oi.order_id = ?`,
+                [order.order_id]
+            );
+            order.items = items;
+        }
+
+        res.render('orderHistory', { orders });
+    } catch (err) {
+        res.status(500).send('เกิดข้อผิดพลาดในการดึงประวัติการสั่งซื้อ: ' + err.message);
+    }
+};
diff --git a/controllers/registerController.js b/controllers/registerController.js
index 26be4c9..eb32f04 100644
--- a/controllers/registerController.js
+++ b/controllers/registerController.js
@@ -15,6 +15,12 @@ module.exports = {
             return res.redirect('/register');
         }
 
+        // ตรวจสอบว่าอีเมลและชื่อผู้ใช้มีข้อมูลหรือไม่
+        if (!email || !username || !fname || !lname || !rpassword || !confirm_password) {
+            req.flash('message', 'Please fill in all fields!');
+            return res.redirect('/register');
+        }
+
         try {
             // ตรวจสอบว่าอีเมลมีอยู่ในระบบหรือไม่
             const [existingUser] = await pool.execute('SELECT * FROM users WHERE email = ?', [email]);
@@ -38,10 +44,12 @@ module.exports = {
             await pool.execute(query, [email, username, hashedPassword, fname, lname]);
 
             // ส่งข้อความแจ้งเตือนและเปลี่ยนเส้นทางไปที่หน้า login
+            req.flash('message', 'Registration successful! Please log in.');
             res.redirect('/login');
         } catch (err) {
             console.error('Error inserting user:', err);
-            res.status(500).send('Error occurred');
+            req.flash('message', 'Error occurred during registration. Please try again later.');
+            res.redirect('/register');
         }
     }
 };
-- 
GitLab