var express = require('express');
var router = express.Router();
var bcrypt = require('bcryptjs');
var { adminonly, renderError, renderAllRecords, renderOneRecord } = require('../util');

// ==================================================
// Route Provide Login Window
// URL: http://localhost:3039/customer/register
// ==================================================
router.get('/register', function(req, res, next) {
    if (typeof req.session.customer_id !== 'undefined' && req.session.customer_id) { //Must logout first
        res.redirect('/');
    } else {
        res.render('customer/addrec');
    }
});

// ==================================================
// Route Provide Login Window
// ==================================================
router.get('/login', function(req, res, next) {
    if (typeof req.session.customer_id !== 'undefined' && req.session.customer_id) { //Must logout first
        res.redirect('/');
    } else {
        res.render('customer/login', {message: "Please Login"});
    }
});

// ==================================================
// Route Check Login Credentials
// ==================================================
router.post('/login', function(req, res, next) {
    let query = "SELECT customer_id, firstname, lastname, password, isadmin FROM customer WHERE username = ?";
    db.all(query, [req.body.username], (err, result) => {
        if (err) {
            renderError(res, err);
        } else {
            if (result[0]) {
                // Username was correct. Check if password is correct
                bcrypt.compare(req.body.password, result[0].password, function(err, result2) {
                    if (err) {
                        renderError(res, err);
                    } else if (result2) {
                        // Password is correct. Set session variables for user.
                        var custid = result[0].customer_id;
                        req.session.customer_id = custid;
                        var custname = result[0].firstname + " " + result[0].lastname;
                        req.session.custname = custname;
                        var isadmin = result[0].isadmin;
                        req.session.isadmin = isadmin;
                        res.redirect('/');
                    } else {
                        // password do not match
                        res.status(401).render('customer/login', {message: "Wrong Password"});
                    }
                });
            } else {
                res.status(401).render('customer/login', {message: "Wrong Username"});
            }
        }
    });
});

// ==================================================
// Route Check Login Credentials
// URL: http://localhost:3039/customer/logout
// ==================================================
router.get('/logout', function(req, res, next) {
    req.session.customer_id = 0;
    req.session.custname = "";
    req.session.cart = [];
    req.session.qty = [];
    req.session.isadmin = 0;
    res.redirect('/');
});    

// ==================================================
// Route to list all records. Display view to list all records
// URL: http://localhost:3039/customer/
// ==================================================
router.get('/', adminonly, function(req, res, next) {
    let query = "SELECT * FROM customer";
    db.all(query, (err, result) => {
        renderAllRecords(res, err, result, "customer/allrecords");
    });
});

// ==================================================
// Route to view one specific record. Notice the view is one record
// URL: http://localhost:3039/customer/1/show
// ==================================================
router.get('/:recordid/show', adminonly, function(req, res, next) {
    let query = "SELECT * FROM customer WHERE customer_id = ?";
    db.all(query, [req.params.recordid], (err, result) => {
        renderOneRecord(res, err, result, "customer/onerec");
    });
});

// ==================================================
// Route to show empty form to obtain input form end-user.
// URLL http://localhost:3039/customer/addrecord
// ==================================================
router.get('/addrecord', adminonly, function(req, res, next) {
    res.render('customer/addrec');
});

// ==================================================
// Route to obtain user input and save in database.
// ==================================================
router.post('/', function(req, res, next) {
    let insertquery = "INSERT INTO customer (firstname, lastname, email, phone, address, city, state, zip, username, password) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    bcrypt.genSalt(10, (err, salt) => {
        if (err) {
            renderError(res, err);
        } else {
            bcrypt.hash(req.body.password, salt, (err, hash) => {
                if (err) {
                    renderError(res, err);
                } else {
                    db.run(insertquery, [req.body.firstname, req.body.lastname, req.body.email, req.body.phone, req.body.address, req.body.city, req.body.state, req.body.zip, req.body.username, hash], (err) => {
                        if (err) {
                            renderError(res, err, 400);
                        } else {
                            if (req.session.isadmin) {
                                res.redirect('/customer');
                            } else {
                                res.redirect('/customer/login'); // Customer must login with created account.
                            }
                        }
                    });
                }
            });
        }
    });
});

// ==================================================
// Route to edit one specific record.
// URL: http://localhost:3039/customer/1/edit
// ==================================================
router.get('/:recordid/edit', adminonly, function(req, res, next) {
    let query = "SELECT * FROM customer WHERE customer_id = ?";
    db.all(query, [req.params.recordid], (err, result) => {
        renderOneRecord(res, err, result, "customer/editrec");
    });
})

// ==================================================
// Route to save edited data in database.
// ==================================================
router.post('/save', adminonly, function(req, res, next) {
    bcrypt.genSalt(10, (err, salt) => {
        if (err) {
            renderError(res, err);
        } else {
            bcrypt.hash(req.body.password, salt, (err, hash) => {
                if (err) {
                    renderError(res, err);
                } else {
                    let updatequery = "UPDATE customer SET firstname = ?, lastname = ?, email = ?, phone = ?, address = ?, city = ?, state = ?, zip = ?, username = ?, password = ? WHERE customer_id = ?";
                    db.run(updatequery, [req.body.firstname, req.body.lastname, req.body.email, req.body.phone, req.body.address, req.body.city, req.body.state, req.body.zip, req.body.username, hash, req.body.customer_id], (err) => {
                        if (err) {
                            renderError(res, err, 400);
                        } else {
                            // If an admin changes a customer's first name and/or last name, the customer must logout and log back in for the change to take effect.
                            res.redirect('/customer');
                        }
                    });
                }
            });
        }
    });
});

// ==================================================
// Route to delete one specific record.
// URL: http://localhost:3039/customer/1/delete
// ==================================================
router.get('/:recordid/delete', adminonly, function(req, res, next) {
    let query = "DELETE FROM customer WHERE customer_id = ?";
    db.run(query, [req.params.recordid], (err) => {
        if (err) {
            renderError(res, err);
        } else {
            res.redirect('/customer');
        }
    });
});

module.exports = router;