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);
    }
};
