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')
const bcrypt = require("bcryptjs")

/* 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'));

/* configure the Express.js server to receive the form values as JSON */
app.use(express.urlencoded({extended: 'false'}))
app.use(express.json())


app.get("/", (req, res) => { res.render("login") })
app.get("/register", (req, res) => { res.render("register") })
app.get("/index", (req, res) => { res.render("index") })


app.post("/auth/register", (req, res) => {    
    const { gender, name, firstname, dob, title, email, password, password_confirm } = req.body

    // db.query() code goes here
    db.query('SELECT email FROM user WHERE email = ?', [email], async (error, result) => {
        if(error){
            console.log(error)
        }
        if( result.length > 0 ) {
            return res.render('register', {
                error: 'Adresse email déjà utilisée : choisissez-en une autre ou bien cliquez sur le lien ci-dessus pour vous connecter'
            })
        } else if(password !== password_confirm) {
            return res.render('register', { 
                error: 'Vos mots de passe ne correspondent pas'
            })
        }

        let hashedPassword = await bcrypt.hash(password, 8)            
        db.query('INSERT INTO user SET?', {gender : (gender != undefined ? gender : ""), firstname: firstname, name: name, date_of_birth: dob, title: title, email: email, password: hashedPassword}, (err, result) => {
            if(error) {
                console.log(error)
            } else {
                return res.render('index')
            }
        })  
    })
})


app.post("/auth/log-control", (req, res) => {    
    const { email, password } = req.body

    // db.query() code goes here
    db.query('SELECT password FROM user WHERE email = ?', [email], async (error, result) => {
        if(error){
            console.log(error)
        }

        if( result.length == 0 ) {
            return res.render('login', {
                error: 'Utilisateur inconnu : veuillez créer votre compte via le lien ci-dessus'
            })
        }

        bcrypt.compare(password, result[0].password, function(err, result) {
            if(result) {
                return res.render('index')
            }
            else {
                return res.render('login', {
                    error: 'Mot de passe incorrect : corriger votre saisie'
                })
            }
        })
    })
})




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