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

// ดูรายละเอียดออเดอร์ (เฉพาะผู้ที่ Login)
router.get('/detail/:orderId', isAuthenticated, async (req, res) => {
    try {
        const sessionId = req.session.id;

        const [orders] = await pool.query(
            `SELECT * FROM orders WHERE id = ? AND session_id = ?`,
            [req.params.orderId, sessionId]
        );

        if (orders.length === 0) {
            return res.status(404).send('Order not found');
        }

        const order = orders[0];

        const [items] = await pool.query(
            `SELECT order_items.*, products.name, products.image_url
             FROM order_items
             JOIN products ON order_items.product_id = products.id
             WHERE order_items.order_id = ?`,
            [req.params.orderId]
        );

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

// ป้องกันไม่ให้เข้า 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.put('/update-address/:orderId', isAuthenticated, async (req, res) => {
    const { shipping_address } = req.body;
    const orderId = req.params.orderId;

    try {
        // ตรวจสอบว่าออเดอร์เป็นของผู้ใช้ปัจจุบัน
        const [order] = await pool.query(
            'SELECT * FROM orders WHERE id = ? AND session_id = ?',
            [orderId, req.session.id]
        );

        if (order.length === 0) {
            return res.status(404).json({ success: false, message: 'Order not found or unauthorized' });
        }

        // อัปเดตที่อยู่จัดส่ง
        await pool.query(
            'UPDATE orders SET shipping_address = ? WHERE id = ?',
            [shipping_address, orderId]
        );

        res.json({ success: true, message: 'Shipping address updated successfully' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ success: false, message: 'Error updating shipping address' });
    }
});

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

module.exports = router;