require('dotenv').config();
var express = require('express');
const axios = require('axios');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const multer = require("multer");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const dbConn = require('./lib/db');

var app = express();
const PORT = 3000;
const SAMEDAYCSVNAME = 'uploadssamedaycsv';

app.use(cors());
app.use(express.json());

/*app.get('/', function (req, res) {
  res.send('Hello World!');
});*/
app.listen(PORT, function () {
  console.log(`Example app listening on port http://localhost:${PORT}/!`);
});

// User Registration
app.post("/register", async (req, res) => {
  const { username, email, password } = req.body;
  const hashedPassword = await bcrypt.hash(password, 10);

  dbConn.query(
    "INSERT INTO admin_users (username, email, password) VALUES (?, ?, ?)",
    [username, email, hashedPassword],
    (err, result) => {
      if (err) return res.status(500).json({ error: err });
      res.json({ message: "User registered successfully!" });
    }
  );
});

app.post("/login", async (req, res) => {
  const { email, password } = req.body;
  if (email == "" && password == "") {
    return res.status(400).json({ success: false, message: "Email and Password Field are required." });
  }
  dbConn.query("SELECT * FROM admin_users WHERE email = ?", [email], async (err, results) => {
    if (err) return res.status(500).json({ error: err });
    if (results.length === 0) return res.status(400).json({success: false, message: "User not found. Please check your credentials." });

    const user = results[0];
    const isValid = await bcrypt.compare(password, user.password);
    if (!isValid) return res.status(400).json({ message: "Invalid credentials. Please check your credentials." });
    const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET ?? 'ozwashroom', { expiresIn: "1h" });
    res.status(200).json({ success: true, token, user: { id: user.id, username: user.username, email: user.email } });
  });
});

// display add user page
app.get('/getfreeship', function(req, res, next) {
    try {
        dbConn.query('SELECT * FROM shipping_data ORDER BY id DESC',function(error,rows)     {
            if (!!error) {
              res.status(500).json({
                  message: error,
                  freeshippingdata: [],
              });
            } else {
              res.status(200).json({
                  freeshippingdata: rows[0],
              });
            }
        });
      } catch (err) {
        res.status(500).json({
          message: err,
          freeshippingdata: [],
        });
      }
});

app.post('/getshipdata', function(req, res) {
    try {
        const path = req.body.path;
        dbConn.query('SELECT * FROM shipping_data WHERE path ="' + path + '" ORDER BY id DESC',function(error,rows)     {
            if (!!error) {
              res.status(500).json({
                  message: error,
                  freeshippingdata: [],
              });
            } else {
              res.status(200).json({
                  freeshippingdata: rows[0],
              });
            }
        });
      } catch (err) {
        res.status(500).json({
          message: err,
          freeshippingdata: [],
        });
      }
});

// add a new user
app.post('/addfreeship', function(req, res) {
      try {
        var form_data;
        const amount = req.body.amount;
        const path = req.body.path;
        if (typeof amount === "undefined") {
          res.status(500).json({
            message: "Please enter Shipping Amount",
          });
        }
        dbConn.query(`INSERT INTO shipping_data (amount, path) VALUES (${amount}, "${path}")`, function(error, result) {
            if (!!error){
              res.status(500).json({
                  message: error,
              });
            } else {
              var freeshippingdata;
              dbConn.query('SELECT * FROM shipping_data WHERE path ="' + path + '" ORDER BY id DESC',function(error,rows)     {
                if (!!error) {

                } else {
                    freeshippingdata = rows[0];
                    res.status(202).json({
                      freeshippingdata: freeshippingdata,
                      message: "Shipping Created",
                    });
                }
              });
            }
        })
      } catch (err) {
        res.status(500).json({
          message: err,
        });
      }
});

// update user data
app.post('/updatefreeship', function(req, res, next) {
    try {
        let id = req.body.id;
        let amount = req.body.amount;
        if (typeof amount === "undefined") {
          res.status(500).json({
            message: "Please enter Shipping Amount",
          });
        }
        if (req.body.zone != null) {
          let zone = req.body.zone;
          zone = zone.replace(/ /g, '');
          var form_data = {
              id: id,
              amount: amount,
              zone: zone
          }
        } else {
          var form_data = {
              id: id,
              amount: amount
          }
        }

        // update query
        dbConn.query('UPDATE shipping_data SET ? WHERE id = ' + id, form_data, function(error, result) {
            if (!!error){
              res.status(500).json({
                  message: error,
              });
            } else {
              res.status(202).json({
                freeshippingdata: form_data,
                message: "Free Shipping Data Added",
              });
            }
        });
    } catch (err) {
        res.status(500).json({
          message: err,
        });
    }
});

// delete user
app.get('/deletefreeship/(:id)', function(req, res, next) {

    let id = req.params.id;

    dbConn.query('DELETE FROM shipping_data WHERE id = ' + id, function(err, result) {
        //if(err) throw err
        if (err) {
            // set flash message
            req.flash('error', err)
            // redirect to user page
            res.redirect('/')
        } else {
            // set flash message
            req.flash('success', 'Freeshipping data successfully deleted! ID = ' + id)
            // redirect to user page
            res.redirect('/')
        }
    })
});

app.get('/getsameday', function(req, res, next) {
    try {
        const path = req.body.path;
        dbConn.query('SELECT * FROM shipping_data WHERE path ="' + path + '" ORDER BY id DESC',function(error,rows)     {
            if (!!error) {
              res.status(500).json({
                  message: error,
                  freeshippingdata: [],
              });
            } else {
              res.status(200).json({
                  freeshippingdata: rows[0],
              });
            }
        });
      } catch (err) {
        res.status(500).json({
          message: err,
          freeshippingdata: [],
        });
      }
});

app.post('/addsameday', function(req, res) {
      try {
        var form_data;
        const amount = req.body.amount;
        const path = req.body.path;
        if (typeof amount === "undefined") {
          res.status(500).json({
            message: "Please enter Shipping Amount",
          });
        }
        dbConn.query(`INSERT INTO shipping_data (amount, path) VALUES (${amount}, "${path}")`, function(error, result) {
            if (!!error){
              res.status(500).json({
                  message: error,
              });
            } else {
              var freeshippingdata;
              dbConn.query('SELECT * FROM shipping_data WHERE path ="' + path + '" ORDER BY id DESC',function(error,rows)     {
                if (!!error) {

                } else {
                    freeshippingdata = rows[0];
                }
            });
              res.status(202).json({
                freeshippingdata: freeshippingdata,
                message: "Sameday Shipping Data Created",
              });
            }
        })
      } catch (err) {
        res.status(500).json({
          message: err,
        });
      }
});


// update user data
app.post('/updatesameday', function(req, res, next) {
    try {
        let id = req.body.id;
        let amount = req.body.amount;
        if (typeof amount === "undefined") {
          res.status(500).json({
            message: "Please enter Sameday Amount",
          });
        }
        if (req.body.zone != null) {
          let zone = req.body.zone;
          zone = zone.replace(/ /g, '');
          var form_data = {
              id: id,
              amount: amount,
              zone: zone
          }
        } else {
          var form_data = {
              id: id,
              amount: amount
          }
        }

        // update query
        dbConn.query('UPDATE shipping_data SET ? WHERE id = ' + id, form_data, function(error, result) {
            if (!!error){
              res.status(500).json({
                  message: error,
              });
            } else {
              res.status(202).json({
                freeshippingdata: form_data,
                message: "Sameday Amount Added",
              });
            }
        });
    } catch (err) {
        res.status(500).json({
          message: err,
        });
    }
});

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = path.join(__dirname, SAMEDAYCSVNAME);

    // Check if the "uploads" folder exists
    if (!fs.existsSync(uploadDir)) {
        // Create the "uploads" folder if it doesn't exist
        fs.mkdirSync(uploadDir);
        console.log('Uploads folder created.');
    } else {
        console.log('Uploads folder already exists.');
    }

    const uploadPath = path.join(__dirname, SAMEDAYCSVNAME); // Adjust the folder location as needed
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  },
});

const upload = multer({ storage });

// Handle file upload
app.post("/uploadsamedaycsv", upload.single("file"), (req, res) => {
  if (!req.file) {
    return res.status(400).send({ message: "No file uploaded" });
  }
  res.send({ message: "File uploaded successfully" });
});

app.post('/addpickup', function(req, res) {
      try {
        var form_data;
        const amount = req.body.amount;
        const path = req.body.path;
        if (typeof amount === "undefined") {
          res.status(500).json({
            message: "Please enter Amount",
          });
        }
        dbConn.query(`INSERT INTO shipping_data (amount, path) VALUES (${amount}, "${path}")`, function(error, result) {
            if (!!error){
              res.status(500).json({
                  message: error,
              });
            } else {
              var freeshippingdata;
              dbConn.query('SELECT * FROM shipping_data WHERE path ="' + path + '" ORDER BY id DESC',function(error,rows)     {
                if (!!error) {

                } else {
                    freeshippingdata = rows[0];
                }
            });
              res.status(202).json({
                freeshippingdata: freeshippingdata,
                message: "Pickup Shipping Data Created",
              });
            }
        })
      } catch (err) {
        res.status(500).json({
          message: err,
        });
      }
});


// update user data
app.post('/updatepickup', function(req, res, next) {
    try {
        let id = req.body.id;
        let amount = req.body.amount;
        if (typeof amount === "undefined") {
          res.status(500).json({
            message: "Please enter Amount",
          });
        }
        if (req.body.zone != null) {
          let zone = req.body.zone;
          zone = zone.replace(/ /g, '');
          var form_data = {
              id: id,
              amount: amount,
              zone: zone
          }
        } else {
          var form_data = {
              id: id,
              amount: amount
          }
        }

        // update query
        dbConn.query('UPDATE shipping_data SET ? WHERE id = ' + id, form_data, function(error, result) {
            if (!!error){
              res.status(500).json({
                  message: error,
              });
            } else {
              res.status(202).json({
                freeshippingdata: form_data,
                message: "Pickup Minimum Amount Added",
              });
            }
        });
    } catch (err) {
        res.status(500).json({
          message: err,
        });
    }
});

app.post('/addactivestat', function(req, res) {
      try {
        var form_data;
        const amount = req.body.amount;
        const path = req.body.path;
        if (typeof amount === "undefined") {
          res.status(500).json({
            message: "Please select checkbox",
          });
        }
        dbConn.query(`INSERT INTO shipping_data (amount, path) VALUES (${amount}, "${path}")`, function(error, result) {
            if (!!error){
              res.status(500).json({
                  message: error,
              });
            } else {
              var freeshippingdata;
              dbConn.query('SELECT * FROM shipping_data WHERE path ="' + path + '" ORDER BY id DESC',function(error,rows)     {
                if (!!error) {

                } else {
                    freeshippingdata = rows[0];
                }
            });
              res.status(202).json({
                freeshippingdata: freeshippingdata,
                message: "Status entry created",
              });
            }
        })
      } catch (err) {
        res.status(500).json({
          message: err,
        });
      }
});


// update user data
app.post('/updateactivestat', function(req, res, next) {
    try {
        let id = req.body.id;
        let amount = req.body.amount;
        if (typeof amount === "undefined") {
          res.status(500).json({
            message: "Please select checkbox",
          });
        }
        if (req.body.zone != null) {
          let zone = req.body.zone;
          zone = zone.replace(/ /g, '');
          var form_data = {
              id: id,
              amount: amount,
              zone: zone
          }
        } else {
          var form_data = {
              id: id,
              amount: amount
          }
        }

        // update query
        dbConn.query('UPDATE shipping_data SET ? WHERE id = ' + id, form_data, function(error, result) {
            if (!!error){
              res.status(500).json({
                  message: error,
              });
            } else {
              res.status(202).json({
                freeshippingdata: form_data,
                message: "Status entry updated",
              });
            }
        });
    } catch (err) {
        res.status(500).json({
          message: err,
        });
    }
});