var express = require('express');
var router = express.Router();
var VariableController = require('../controllers/variableController');
const { body } = require('express-validator');
const authentification = require('../middlewares/authentification');
const DB = require('../models/index');


router.post(
    '/variable/save',
    authentification,[
        body('variable').notEmpty().withMessage('Le champ "variable" est requis.'),
        body('value').notEmpty().withMessage('Le champ "value" est requis.'),
    ],
    VariableController.save);

router.get( '/', authentification,( req, res, next ) => {
    res.render('home', { req })
})

router.get('/new', authentification,( req, res ) => {
    let errors = null;
    res.render('pages/setting/variable.ejs', { errors, req });
})

router.get('/holidays', authentification, async (req, res) => {
    let holidays = await DB.holiday.findAll({
        order: [['date', 'DESC']]
    });
    console.log(holidays);
    res.render('pages/admin/holiday.ejs', { req, holidays });
})

router.post('/holidays', authentification, async (req, res) => {    
    await DB.holiday.create(req.body);
    res.redirect('/setting/holidays');
})

router.get('/holiday/delete/:id(\\d+)', authentification, async (req, res) => {
    const ID = req.params.id;
    if (ID == '') {
        return res.redirect('/setting/holidays');
    }

    let holiday = await DB.holiday.findByPk(ID);
    if (!holiday) {
        return res.redirect('/setting/holidays');
    }

    await holiday.destroy();
    
    res.redirect('/setting/holidays');
})

module.exports = router;

  