const express = require('express');
const router = express.Router();
const db = require('../database/db');
const bcrypt = require('bcrypt');


router.post('/register', (req, res) => {

    const {name, password, email} = req.body;

    //check values are null
    if (!name || !password || !email) {
        return res.status(400).send('Please fill all fields');
    }

    //hash password
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password, salt);

    const query = 'INSERT INTO admin (name, email, password, pass_on) VALUES (?,?,?,?)';
    const values = [name, email, hash, password];

    db.query(query, values, (err, results) => {
        if (err) {
            console.error('Error saving data:', err);
            return res.status(500).send('Server error');
        }

        res.status(201).send('Data saved successfully');
    });


});


//login
router.post('/login', (req, res) => {

    const {email, password} = req.body;

    //check values are null
    if (!email || !password) {
        return res.status(400).send('Please fill all fields');
    }

    const query = 'SELECT * FROM admin WHERE email = ?';
    db.query(query, email, (err, results) => {
        if (err) {
            console.error('Error getting data:', err);
            return res.status(500).send('Server error');
        }

        if (results.length === 0) {
            return res.status(401).send('Invalid');
        }

        const user = results[0];
        const hash = user.password;

        if (!bcrypt.compareSync(password, hash)) {
            return res.status(401).send('Invalid');
        }

        res.status(200).send(user);
    });

});


module.exports = router;

