const express = require('express')
const mysql = require("mysql")
const dotenv = require('dotenv')
const app = express()
const path = require("path")
const publicDir = path.join(__dirname, './public')

/* Connexion à la BDD MySQL */
dotenv.config({ path: './.env'})
const db = mysql.createConnection({
    host: process.env.DATABASE_HOST,
    port: process.env.DATABASE_PORT,
    user: process.env.DATABASE_USER,
    password: process.env.DATABASE_PASSWORD,
    database: process.env.DATABASE
})
db.connect((error) => {
    if(error) {
        console.log(error)
    } else {
        console.log("MySQL connected!")
    }
})

app.set('view engine', 'hbs');
app.use(express.static(publicDir));
/* Pour utiliser le bootstrap local */
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css'));
app.use(express.json());

app.get("/", (req, res) => { 
    db.query('SELECT c.id, c.libelle, c.prix, c.photo, c.lien, p.prenom as "acheteur", p2.prenom as "responsable" FROM cadeau c LEFT OUTER JOIN participations pc on pc.cadeau = c.id LEFT OUTER JOIN participant p on p.id = pc.personne LEFT OUTER JOIN participant p2 on p2.id = pc.responsable', async (error, resultCadeaux) => {
        let message;

        if(error){
            console.log(error);
        }
        if (resultCadeaux.length == 0) {
            console.log("Aucun cadeau");
            message = "Aucun cadeau pour l'instant";
        }
        res.render('index', { message: message, cadeaux: resultCadeaux })
    })
 });


app.get("/reserve", (req, res) => { 
    db.query('SELECT libelle, prix, photo, lien FROM cadeau WHERE id = ?', [req.query.id], async (error, result) => {
        if(error){
            console.log(error);
        }
        if (result.length > 0) {
            res.render('reservation', { retour: result } );
        }
    })
});


app.listen(5006, ()=> {
    console.log("server started on port 5006")
});
