var express = require("express")
var app = express()
var db = require("./database.js")
var cron = require('node-cron');
var bodyParser = require("body-parser");
const { request, response } = require("express");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

let HTTP_PORT = 8080
const cors = require('cors');
app.use(cors({
	origin: '*'
}));



// Start server
app.listen(HTTP_PORT, () => {
	console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});

app.get("/api/products", (req, res, next) => {
	try {
		var sql = "select * from products"
		var params = []
		db.all(sql, params, (err, rows) => {
			if (err) {
				res.status(400).json({ "error": err.message });
				return;
			}
			res.json({
				"message": "success",
				"data": rows
			})
		});
	} catch (E) {
		res.status(400).send(E);
	}

});

app.get("/api/products/:id", (req, res, next) => {
	try {
		var sql = "select * from products where id = ?"
		var params = [req.params.id]
		db.get(sql, params, (err, row) => {
			if (err) {
				res.status(400).json({ "error": err.message });
				return;
			}
			res.json({
				"message": "success",
				"data": row
			})
		});
	} catch (E) {
		res.status(400).send(E);
	}
});

app.get("/api/products/quantity/:quantity", (req, res, next) => {
	try {
		var row = "[]"
		var sql = "select * from products where quantity > ?"
		var params = [req.params.quantity]
		db.get(sql, params, (err, row) => {
			if (err) {
				res.status(400).json({ "error": err.message });
				return;
			}
			res.json({
				"message": "success",
				"data": row
			})
		});
	} catch (E) {
		res.status(400).send(E);
	}
});

app.get("/api/products/unitPrice/:unitPrice", (req, res, next) => {
	try {
		var row = "[]"
		var sql = "select * from products where unitPrice > ?"
		var params = [req.params.unitPrice]
		db.get(sql, params, (err, row) => {
			if (err) {
				res.status(400).json({ "error": err.message });
				return;
			} else {
				res.json({

					"message": "success",
					"data": row
				})
			}

		});
	} catch (E) {
		res.status(400).send(E);
	}
});

app.post("/api/products/", (req, res, next) => {

	try {
		var errors = []

		if (!req.body) {
			errors.push("An invalid input");
		}

		const { productName,
			description,
			category,
			brand,
			expiredDate,
			manufacturedDate,
			batchNumber,
			unitPrice,
			quantity,
			createdDate
		} = req.body;

		var sql = 'INSERT INTO products (productName, description, category, brand, expiredDate, manufacturedDate, batchNumber, unitPrice, quantity, createdDate) VALUES (?,?,?,?,?,?,?,?,?,?)'
		var params = [productName, description, category, brand, expiredDate, manufacturedDate, batchNumber, unitPrice, quantity, createdDate]
		db.run(sql, params, function (err, result) {

			if (err) {
				res.status(400).json({ "error": err.message })
				return;
			} else {
				res.json({
					"message": "success",
					"data": req.body,
					"id": this.lastID
				})
			}

		});
	} catch (E) {
		res.status(400).send(E);
	}
});


app.put("/api/products/", (req, res, next) => {


	const {
		id,
		productName,
		description,
		category,
		brand,
		expiredDate,
		manufacturedDate,
		batchNumber,
		unitPrice,
		quantity,
		createdDate
	} = req.body;

	db.run(`UPDATE products set productName = ?, description = ?, category = ?, brand = ?,expiredDate=?,manufacturedDate=?,batchNumber=?,unitPrice=?,quantity=?,createdDate=? WHERE id = ?`,
		[productName, description, category, brand, expiredDate, manufacturedDate, batchNumber, unitPrice, quantity, createdDate, id],
		function (err, result) {
			if (err) {
				res.status(400).json({ "error": res.message })
				return;
			}
			res.status(200).json({ updated: this.changes });
		});
});


app.delete("/api/products/delete/:id", (req, res, next) => {
	try {
		db.run(
			'DELETE FROM products WHERE id = ?',
			req.params.id,
			function (err, result) {
				if (err) {
					res.status(400).json({ "error": res.message })
					return;
				}
				res.json({ "message": "deleted", rows: this.changes })
			});
	} catch (E) {
		res.status(400).send(E);
	}
});

app.delete("/api/products/deleteAll/:id", (req, res, next) => {
	try {
		db.run(
			'DELETE FROM products WHERE id > ?',
			req.params.id,
			function (err, result) {
				if (err) {
					res.status(400).json({ "error": res.message })
					return;
				}
				res.json({ "message": "deleted", rows: this.changes })
			});
	} catch (E) {
		res.status(400).send(E);
	}
});


app.get("/api/suppliers/", (req, res, next) => {
	try {
		var sql = "select * from suppliers"
		var params = []
		db.all(sql, params, (err, rows) => {
			if (err) {
				res.status(400).json({ "error": err.message });
				return;
			}
			res.json({
				"message": "success",
				"data": rows
			})
		});
	} catch (E) {
		res.status(400).send(E);
	}

});


app.post("/api/suppliers/", (req, res, next) => {

	try {
		var errors = []

		if (!req.body) {
			errors.push("An invalid input");
		}

		const { supplierName,
			address,
			joinedDate,
			mobileNo
		} = req.body;

		var sql = 'INSERT INTO suppliers (supplierName, address, joinedDate, mobileNo) VALUES (?,?,?,?)'
		var params = [supplierName, address, joinedDate, mobileNo]
		db.run(sql, params, function (err, result) {

			if (err) {
				res.status(400).json({ "error": err.message })
				return;
			} else {
				res.json({
					"message": "success",
					"data": req.body,
					"id": this.lastID
				})
			}

		});
	} catch (E) {
		res.status(400).send(E);
	}
});

app.delete("/api/suppliers/deleteAll/:id", (req, res, next) => {
	try {
		db.run(
			'DELETE FROM suppliers WHERE id > ?',
			req.params.id,
			function (err, result) {
				if (err) {
					res.status(400).json({ "error": res.message })
					return;
				}
				res.json({ "message": "deleted", rows: this.changes })
			});
	} catch (E) {
		res.status(400).send(E);
	}
});

function validateEmail(email) {
	const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
	return emailRegex.test(email);
}

// Function to validate credit card number (12 digits)
function validateCreditCardNumber(cardNumber) {
    // Check if the cardNumber is a string of exactly 12 characters
    const cardNumberRegex = /^.{12}$/;

    return cardNumberRegex.test(cardNumber);
}

app.post("/api/customers/", (req, res, next) => {
	try {
		var errors = [];

		if (!req.body) {
			errors.push("Invalid input");
			res.status(400).json({ "error": errors });
			return;
		}

		const {
			firstName,
			lastName,
			email,
			phone,
			address,
			createdDate
		} = req.body;

		// Validation
		if (!validateEmail(email)) {
			errors.push("Invalid email address");
		}

		if (!validateCreditCardNumber(phone)) {
			errors.push("Invalid credit card number (12 digits)");
		}

		if (errors.length > 0) {
			res.status(400).json({ "error": errors });
			return;
		}

		var sql = 'INSERT INTO customer (firstName, lastName, email, phone, address, createdDate) VALUES (?,?,?,?,?,?)';
		var params = [firstName, lastName, email, phone, address, createdDate];

		db.run(sql, params, function (err, result) {
			if (err) {
				res.status(400).json({ "error": err.message });
				return;
			} else {
				console.log('Customer registered');
				res.status(201).json({
					"message": `Customer ${firstName + lastName} registered successfully`,
					"data": req.body,
					"id": this.lastID
				});
			}
		});
	} catch (E) {
		console.log(E);
		res.status(400).send(E);
	}
});

// Root path
app.get("/", (req, res, next) => {
	res.json({ "message": "University of Moratuwa" })
});

{
    "error": [
        "Invalid credit card number (12 digits)"
    ]
}

this is the parsed in data.

{
  "name": "W.l. Induranga kaushalya",
  "address": "Undisclosed",
  "email": "rangakaushal36@gmail.com",
  "dateOfBirth": "2005/7/12",
  "gender": "male",
  "age": "18",
  "cardHolderName": "W.l. Induranga kaushalya.",
  "cardNumber": "102445217895",
  "expiryDate": "12/2022",
  "cvv": "246",
  "timeStamp": "2022-12-31 23:59:59"
}