const bcrypt = require('bcrypt');
const pool = require('../db');

module.exports = {
    showLoginPage: (req, res) => {
        res.render('login', { message: req.flash('message') });
    },

    loginUser: async (req, res) => {
        const { email, rpassword } = req.body;
        try {
            const [rows] = await pool.execute('SELECT * FROM users WHERE email = ?', [email]);
            if (rows.length === 0) {
                req.flash('message', 'Email not found');
                return res.redirect('/login');
            }

            const user = rows[0];
            const match = await bcrypt.compare(rpassword, user.password);
            if (match) {
                req.session.userId = user.user_id; // ใช้ user_id แทน id
                res.redirect('/');
            } else {
                req.flash('message', 'Password incorrect');
                return res.redirect('/login');
            }
        } catch (err) {
            console.error(err);
            res.status(500).send('Server error');
        }
    }
};
