const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const flash = require('connect-flash');

const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const flash = require('connect-flash');

global.loggedIn = null
const app = express();
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
    secret: 'secretkey',
    resave: true,
    saveUninitialized: true
}));
app.use(flash());
app.set('view engine', 'ejs');
app.use('*', (req, res, next) => {
  loggedIn = req.session.userId
  next()
});

// การนำเข้า controller
const indexController = require('./controllers/indexController');
const loginController = require('./controllers/loginController');
const registerController = require('./controllers/registerController');
const logoutController = require('./controllers/logoutController');

// การตั้งค่า route สำหรับการสมัครและเข้าสู่ระบบ
app.get('/', indexController.getProducts);
app.get('/login', loginController.showLoginPage);
app.post('/user/login', loginController.loginUser);
app.get('/register', registerController.showRegisterPage);
app.post('/user/register', registerController.registerUser);
app.get('/logout', logoutController);

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});
