const express = require('express')
const bodyParser=require('body-parser')
const cors = require('cors')
const app = express()
const mysql = require('mysql')
const bcrypt = require('bcrypt')
const cookieParser = require('cookie-parser')
const session = require('express-session')
const saltRounds = 10


const db = mysql.createPool({
    host:'62.171.189.81',
    user:'sagatec',
    password:'SagaTeC@2016',
    database:'Helper',
});



app.use(cors({
    origin : ["http://dashboard.mcsystem.net"],
    methods: ["GET" , "POST"],
    credentials: true
}));


app.use(cookieParser())
app.use(session({
    key:"userID", 
    secret: "SagaTec" ,
    resave: false,
    saveUninitialized: false,
    cookie :{
        expires: 60*60*24,
    },
}))

app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));







app.get("/login" , (req, res)=>{
    if (req.session.user) {
        res.send({loggedIn : true, user: req.session.user})
    }else{
        res.send({loggedIn : false})
    }
})


app.post('/api/Magasins' , (req, res)=>{
    const IDclient= req.body.IDclient;
    db.query("SELECT * FROM Magasin WHERE IDclient =? " , IDclient , (err, result) =>{
        res.send(result);
        
    } )
});
app.post('/api/chart' , (req, res)=>{
    const GatChart= req.body.GatChart;
    db.query( GatChart , (err, result) =>{
        res.send(result);
        
    } )
});


app.post('/api/chartAnnee' , (req, res)=>{
    const GetChartAnnee= req.body.GetChartAnnee;
    db.query( GetChartAnnee , (err, result) =>{
        res.send(result);
        
    } )
});

app.post('/api/chartMois' , (req, res)=>{
    const GetChartMois= req.body.GetChartMois;
    db.query( GetChartMois , (err, result) =>{
        res.send(result);
        
    } )
});


app.post('/api/Mois' , (req, res)=>{
    const IDclient= req.body.IDclient;
    db.query( IDclient , (err, result) =>{
        res.send(result);
        
    } )
});

app.post('/api/Annee' , (req, res)=>{
    const GetAnnee= req.body.GetAnnee;
    db.query( GetAnnee , (err, result) =>{
        res.send(result);
        
    } )
});
app.post('/api/get' , (req, res)=>{
    const GetData= req.body.GetData;
    db.query(GetData , (err, result) =>{
        res.send(result);
        
    } )
});


app.post('/api/getArticles' , (req, res)=>{
    const GetData= req.body.GetData;
    db.query(GetData , (err, result) =>{
        res.send(result);
        
    } )
});
app.post('/api/getCategorie' , (req, res)=>{
    const GetCategorie= req.body.GetCategorie;
    db.query(GetCategorie , (err, result) =>{
        res.send(result);
        
    } )
});
app.post('/Update/mdp' , async (req, res)=>{
    const Newpassword= req.body.Newpassword;
    const IDmagasin = req.body.IDmagasin;
    const hach = await bcrypt.hash(Newpassword,10);
    
    const queryMDP = `UPDATE Clients SET PASSWORD = '${hach}' where IDclient = (SELECT IDclient FROM Magasin WHERE IDmagasin='${IDmagasin}')`;
    db.query(queryMDP , (err, result) =>{
        res.send(result);
        console.log(hach);
    } )

});




app.get("/",(req, res)=>{
    res.send("hello me");
});

app.post('/login', (req, res)=> {
    const username = req.body.username;
    const password = req.body.password;

    db.query(
        "SELECT * FROM Clients where Login = ?",
        username , (err,result) =>{
            if (err) {
                res.send(err);
            }
            if (result.length > 0) {
                db.query(
                    "SELECT * FROM Clients where Login = ? AND STR_TO_DATE(DateFin ,  '%d/%m/%Y') > CURDATE()",
        username , (err,result2) =>{
            if (result2.length > 0) {
                bcrypt.compare(password, result2[0].PASSWORD , (err , resp)=>{
                    if (resp) {
                        req.session.user = result2;
                        res.send(result2);
                    }else{
                        
                        res.send(result2);
                    }
                });
            }else{
                res.send(true);
            }
            }
                )
                
            }else{
                res.send(false);
            }
        }
    )
});





app.post('/Update', (req, res)=> {
    const IDmagasin = req.body.IDmagasin;
    const password = req.body.password;

    db.query(
        "SELECT * FROM Clients where IDclient = (SELECT IDclient FROM Magasin WHERE IDmagasin=?)",
        IDmagasin , (err,result) =>{
            if (err) {
                res.send(err);
            }

            if (result.length > 0) {
                bcrypt.compare(password, result[0].PASSWORD , (err , resp)=>{
                    if (resp) {
                        req.session.user = result;
                        res.send(result);
                    }else{
                        
                        res.send(false);
                    }
                });
            }else{
                res.send(false);
            }
        }
    )
});





app.listen(8080 ,()=>{
console.log("the API is running");   
});