const express = require('express');
const router = express.Router();
const pool = require('../config/database');

// Middleware ตรวจสอบการ Login
function isAuthenticated(req, res, next) {
    if (req.session && req.session.user) {
        return next(); // ถ้า Login แล้วให้ไปต่อ
    } else {
        res.redirect('/login'); // ถ้ายังไม่ได้ Login ให้ Redirect ไปที่หน้า Login
    }
}

// แสดงประวัติออเดอร์ (เฉพาะผู้ที่ Login)
router.get('/history', isAuthenticated, async (req, res) => {
    try {
        const [orders] = await pool.query(
            `SELECT 
                orders.id,
                orders.total_amount,
                orders.status,
                orders.shipping_address,
                orders.created_at,
                GROUP_CONCAT(
                    CONCAT(
                        products.name, ' x ', order_items.quantity, ' (฿', order_items.price, ')'
                    ) SEPARATOR ', '
                ) as items_detail
            FROM orders
            JOIN order_items ON orders.id = order_items.order_id
            JOIN products ON order_items.product_id = products.id
            WHERE orders.session_id = ?
            GROUP BY orders.id
            ORDER BY orders.created_at DESC`,
            [req.session.id]
        );

        res.render('order-history', { orders });
    } catch (error) {
        console.error(error);
        res.status(500).send('Error fetching order history');
    }
});

// อัปเดตที่อยู่จัดส่งของคำสั่งซื้อ
router.get('/update/:orderId', async (req, res) => {
    try {
        const { orderId } = req.params;
        const { shipping_address } = req.body;

        console.log("Updating Shipping Address...");
        console.log("Session ID:", req.session.id);
        console.log("Order ID:", orderId);
        console.log("New Address:", shipping_address);

        if (!shipping_address) {
            return res.status(400).json({ message: "กรุณากรอกที่อยู่จัดส่ง" });
        }

        // อัปเดตที่อยู่เฉพาะของคำสั่งซื้อที่เป็นของ session นั้นๆ
        const [result] = await pool.query(
            "UPDATE orders SET shipping_address = ? WHERE id = ? AND session_id = ?",
            [shipping_address, orderId, req.session.id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({ message: "ไม่พบคำสั่งซื้อนี้ หรือไม่มีสิทธิ์แก้ไข" });
        }

        res.json({ message: "อัปเดตที่อยู่สำเร็จ!" });
    } catch (error) {
        console.error("ERROR:", error);
        res.status(500).json({ message: "เกิดข้อผิดพลาด", error: error.message });
    }
});


// ป้องกันไม่ให้เข้า Checkout ถ้าไม่ได้ Login
router.get('/checkout', isAuthenticated, async (req, res) => {
    try {
        const [cartItems] = await pool.query(
            `SELECT cart_items.*, products.name, products.price 
             FROM cart_items 
             JOIN products ON cart_items.product_id = products.id 
             WHERE cart_items.session_id = ?`,  
            [req.session.id] 
        );

        const total = cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);

        // ต้องส่ง user ไปที่ checkout.ejs
        res.render('checkout', { user: req.session.user, cartItems, total });
    } catch (error) {
        console.error(error);
        res.status(500).send('Error loading checkout');
    }
});

// บันทึกออเดอร์
router.post('/create', isAuthenticated, async (req, res) => {
    const { address } = req.body;
    const conn = await pool.getConnection();
    try {
        await conn.beginTransaction();

        const [cartItems] = await conn.query(
            `SELECT cart_items.*, products.price 
             FROM cart_items 
             JOIN products ON cart_items.product_id = products.id 
             WHERE cart_items.session_id = ?`,
            [req.session.id]
        );

        if (cartItems.length === 0) {
            return res.status(400).send('Cart is empty');
        }

        const total = cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);

        const [order] = await conn.query(
            'INSERT INTO orders (session_id, total_amount, status, shipping_address) VALUES (?, ?, ?, ?)',
            [req.session.id, total, 'pending', address]
        );

        for (const item of cartItems) {
            await conn.query(
                'INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)',
                [order.insertId, item.product_id, item.quantity, item.price]
            );
            await conn.query(
                'UPDATE products SET stock = stock - ? WHERE id = ?',
                [item.quantity, item.product_id]
            );
        }

        await conn.query('DELETE FROM cart_items WHERE session_id = ?', [req.session.id]);

        await conn.commit();
        res.redirect('/order/confirmation');
    } catch (error) {
        await conn.rollback();
        console.error(error);
        res.status(500).send('Error creating order');
    } finally {
        conn.release();
    }
});

router.get('/confirmation', (req, res) => {
    res.render('confirmation');
});

module.exports = router;