var express = require("express");
var router = express.Router({ mergeParams: true });
var Product = require("../models/product");
var Cart = require("../models/cart");
var Order = require("../models/order");
const sendEmail = require("../tools/sendEmail");


//if you want to use strict signin for checkout just readd the isLoggedIn middleware
//cart checkout, not loggedIn
router.post("/checkout_setup", function (req, res) {
  var ids = [];
  var full_products_cart = [];
  var cart_products = JSON.parse(req.body.cart_products);
  cart_products.forEach(cart_product => {
    ids.push(cart_product._id);
  });
  var total = 0;
  var TTC = 0;
  Product.find({ _id: { $in: ids } }, function (err, products) {
    if (err) { console.log(err); return res.json({ message: "fail" }) }
    var full_product_cart;
    for (var i = 0; i < products.length; i++) {
      for (var j = 0; j < cart_products.length; j++) {
        if (products[i]._id == cart_products[j]._id) {
          total += (products[i].price * cart_products[j].qty);
          TTC += (products[i].TTC * cart_products[j].qty);
          full_product_cart = { product: products[i], qty: cart_products[j].qty }
          full_products_cart.push(full_product_cart);
        }
      }
    }
    res.render("checkout/checkout", { full_products_cart, total, TTC });
  });
});

//signed cart checkout
router.post("/user/checkout_setup", isLoggedIn, function (req, res) {
  if (req.user.confirmed != true) {
    return res.render("user/verification");
  }
  Cart.findOne({ User: req.user }).populate("Product_qty.product").exec(function (err, cart) {
    if (err || !cart) { console.log(err); return res.redirect("/home"); }
    var total = 0;
    var TTC = 0;
    cart.Product_qty.forEach(function (cartPQ) {
      total += cartPQ.product.price * cartPQ.qty;
      TTC += cartPQ.product.TTC * cartPQ.qty;
    });
    if (!cart.Product_qty.length) return res.redirect("/home");
    res.render("checkout/checkout", { full_products_cart: cart.Product_qty, total, TTC });
  });
});

router.get("/order_checkout", function (req, res) {
  try {
    if (req.user?.confirmed != true && req.user) {
      return res.render("user/verification");
    }
    var full_products_cart = [];
    var total = 0;
    var TTC = 0;
    Product.find({ _id: req.query.product_id }, function (err, products) {
      if (err) { console.log(err); return res.json({ message: "fail" }) }
      full_product_cart = { product: products[0], qty: req.query.qty }
      full_products_cart.push(full_product_cart);
      total = products[0].price * req.query.qty;
      TTC = products[0].TTC * req.query.qty;
      res.render("checkout/checkout", { full_products_cart, total, TTC });
    })
  } catch (error) {
    console.log(error);
    res.redirect("/home");
  }
})

//send email of quote
router.post("/send/devis", async function (req, res) {
  var mailOptions = {
    from: 'FutureTech',
    to: req.body.client_email,
    subject: 'Your Quote from FutureTech',
    html: req.body.mailBody //fixed the body with inline style instead of style tag
  };
  await sendEmail(mailOptions);
  res.json({ message: "success", desc: "Quote was sent" });
});

//send email of order
router.post("/send/order_purchase", async function (req, res) {
  var mailOptions = {
    from: 'FutureTech',
    to: req.body.client_email,
    subject: 'Your Purchase Order from FutureTech',
    html: req.body.mailBody //TODO: the body is not compatible, fix it
  };
  await sendEmail(mailOptions);
  res.json({ message: "success", desc: "order purchase was sent" });

});

//generate quote
router.get("/generate/quote", function (req, res) {
  var client_infos = req.query;

  if (typeof req.query.products.product == "string") {
    req.query.products.product = [req.query.products.product];
    req.query.products.qty = [req.query.products.qty];
  }

  Product.find({ _id: { $in: req.query.products.product[0] } }, function (err, products) {
    if (err || !products) { console.log(err); return res.redirect("/home"); }
    var total = 0;
    var TTC = 0;
    let product_qty = [];
    products.forEach(function (curProd, i, arr) {
      for (let index = 0; index < req.query.products.product.length; index++) {
        req.query.products.product[index] = curProd;
        const curQueryProd = req.query.products;
        if (curQueryProd.product[index]._id == curProd._id) {
          product_qty.push({ product: curProd, qty: curQueryProd.qty[index] });
          total += curProd.price * curQueryProd.qty[index];
          TTC += curProd.TTC * curQueryProd.qty[index];
        }
      }
      if (i == arr.length - 1)
        res.render("checkout/quote", { full_products_cart: product_qty, total, TTC, client_infos, shipping: req.query.shipping });

    });
  });

});

//quote submitted, redirect to thank you page
router.get("/quote/submitted", function (req, res) {
  if (req.query.bl) return res.render("checkout/thank_you", { download: true, fileType: "bl" });
  res.render("checkout/thank_you");
});

//download bl
router.get("/download/bl", isLoggedIn, function (req, res) {
  Order.findOne({ User: req.user._id }, {}, { sort: { '_id': -1 } }).populate("Product_qty.product").exec(function (err, order) {
    if (err) { console.log(err); return res.redirect("/home"); }
    res.render("checkout/b_l", { full_products_cart: order.Product_qty, order, download: true });
  });
})

//confirm order
router.post("/checkout", function (req, res) {

  var client_infos = req.body;

  req.body.products = { product: req.body["products[product]"], qty: req.body['products[qty]'] };

  if (typeof req.body.products.product == "string") {
    req.body.products.product = [req.body.products.product];
    req.body.products.qty = [req.body.products.qty];
  }

  Product.find({ _id: { $in: req.body.products.product[0] } }, function (err, products) {
    if (err || !products) { console.log(err); return res.redirect("/home"); }
    var total = 0;
    var TTC = 0;
    let product_qty = [];
    products.forEach(function (curProd, i, arr) {
      for (let index = 0; index < req.body.products.product.length; index++) {
        req.body.products.product[index] = curProd;
        const curQueryProd = req.body.products;
        if (curQueryProd.product[index]._id == curProd._id) {
          product_qty.push({ product: curProd, qty: curQueryProd.qty[index] });
          total += curProd.price * curQueryProd.qty[index];
          TTC += curProd.TTC * curQueryProd.qty[index];
        }
      }
      if (i == arr.length - 1) {
        Order.create({ User: req.user?._id, Product_qty: product_qty, client_infos: client_infos, total, TTC, shipping: req.body.shipping }, function (err, order) {
          if (err) { console.log(err); return res.redirect("/home"); }
          //res.render("checkout/thank_you", {download: true, fileType:"bl"});
          res.render("checkout/b_l", { full_products_cart: product_qty, order });
        });
      }

    });
  });

});


function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  else {
    res.redirect("/login");
  }
}
module.exports = router;
