const jwt = require("jsonwebtoken");
const Orders = require("../models/ordersModel");
const User = require("../models/userModel");
const Campaign = require("../models/campaignsModel");
const moment = require("moment/moment");

const verification = async (token) => {
  try {
    // if (token.startsWith("Bearer ")) {
    //   TokenArray = token.split(" ");
    //   const decoded = jwt.verify(TokenArray[1], process.env.JWT_SECRET);
    //   const user = await User.findOne({ _id: decoded.id });
    //   if (user !== null && decoded.exp > Date.now() / 1000) {
    //     return true;
    //   } else {
    //     return false;
    //   }
    // } else {
    //   return false;
    // }
    return true;
  } catch (error) {
    return false;
  }
};

exports.getOrders = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const orders = await Orders.find({ IsDelete: false });
    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: orders,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.Get_Order_By_UserID = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const CustomerId = req.params.id;
    const orders = await Orders.find({ customerId: CustomerId });
    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: orders,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.saveOrder = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    let isExpired = false;
    let expiredPRoducts = "";

    body.Items.map(async (product) => {
      const res = await Campaign.findById(product.campaignId);
      if (res.drawDateTime < moment.now()) {
        isExpired = true;
        expiredPRoducts = expiredPRoducts + ", " + res.name;
      }
    });

    if (isExpired === false) {
      const data = {
        orderNumber: moment().format("YYYY-MMM-DDThh:mm:ss") + "_" + body.User,
        orderDateTime: moment().format("YYYY-MMM-DD hh:mm:ss"),
        customerId: body.customerId,
        customerName: body.customerName,
        Items: body.Items,
        Amount: body.Amount,
        Tickets: body.Tickets,
        address: body.address,
        country: body.country,
        city: body.city,
        phone: body.phone,
        paymentType: body.paymentType,
        IsActive: true,
        IsDelete: false,
        CreatedBy: body.customerId,
        CreatedOn: moment().format("YYYY-MMM-DD"),
      };
      const newOrder = await Orders.create(data);
      res.json({
        message: "New Order created successfully.",
        IsSuccess: true,
        Status_Code: 200,
        Data: newOrder,
      });
    } else {
      res.json({
        message: expiredPRoducts + " has been expired.",
        IsSuccess: false,
        Status_Code: 400,
        Data: null,
      });
    }
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.editOrder = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const updateOrder = await Orders.updateOne(
      { _id: body._id },
      {
        $set: {
          orderNumber: body.orderNumber,
          orderDateTime: body.orderDateTime,
          customerName: body.customerName,
          paymentType: body.paymentType,
          IsActive: body.IsActive,
          ModifiedBy: body.User,
          ModifiedOn: moment().format("YYYY-MMM-DD"),
        },
      }
    );
    const updatedOrder = await Orders.findById(body._id);
    res.json({
      message: "Order updated successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedOrder,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.deleteOrder = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const updateOrder = await Orders.updateOne(
      { _id: body._id },
      {
        $set: {
          IsActive: body.IsActive,
          IsDelete: body.IsDelete,
          ModifiedBy: body.User,
          ModifiedOn: moment().format("YYYY-MMM-DD"),
        },
      }
    );
    const updatedOrder = await Orders.findOne({
      _id: body._id,
    });
    res.json({
      message: "Order deleted successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedOrder,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};
