const pdfBuilder = require("../../helpers/pdfBuilder");
const Customers = require("../../models/Customers");
const OrderForm = require("../../models/OrderForm");
const OrderFormDetails = require("../../models/OrderFormDetails");
const Product = require("../../models/Products");
const SellersCompany = require("../../models/SellersCompany");

exports.generateDr = async (req, res, next) => {
  try {
    const { orderNumber } = req.query;

    if (!orderNumber)
      return res
        .status(200)
        .json({ success: false, message: "Order number is required." });

    const templatePath =
      __dirname + "/../../helpers/email-templates/delivery-receipt.html";

    const date = new Date();
    const dateOptions = {
      weekday: undefined,
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      hour12: true,
    };
    const formattedDate = date.toLocaleString("en-US", dateOptions);

    const orderForm = await OrderForm.findOne({
      where: {
        reference_no: orderNumber,
      },
      include: [
        {
          model: OrderFormDetails,
          as: "order_form_details",
          include: [
            {
              model: Product,
              as: "product",
            },
          ],
        },
        {
          model: Customers,
          as: "customer_detail",
        },
        {
          model: SellersCompany,
          as: "sellers_company_details"
        }
      ],
    });

    if (!orderForm)
      return res
        .status(200)
        .json({ success: false, message: "Order form not found." });

    if (orderForm && orderForm.order_form_details.length === 0)
      return res
        .status(200)
        .json({ success: false, message: "No order details found." });

    const orderDetails = [];
    for (const order of orderForm.order_form_details) {
      orderDetails.push({
        qty: order.quantity,
        unit: "PC",
        description: order.product.menu,
      });
    }

    let customerName = "";
    let sellerName = "";
    let sellerAddress = "";

    if (orderForm && orderForm.customer_detail) {
      if (
        orderForm.customer_detail &&
        orderForm.customer_detail.hardware_name &&
        orderForm.customer_detail.hardware_name !== ""
      ) {
        customerName = orderForm.customer_detail.hardware_name;
      } else {
        customerName = `${orderForm.customer_detail.first_name} ${orderForm.customer_detail.last_name}`;
      }
    }

    if(orderForm && orderForm.sellers_company_details) {
      if(orderForm && orderForm.sellers_company_details && orderForm.sellers_company_details.company_name) {
        sellerName = orderForm.sellers_company_details.company_name;
      }
      if(orderForm && orderForm.sellers_company_details && orderForm.sellers_company_details.address) {
        sellerAddress = orderForm.sellers_company_details.address;
      }
      if(orderForm && orderForm.sellers_company_details && orderForm.sellers_company_details.isParentCompany !== "Yes") {
        const parentCompanyID = orderForm.sellers_company_details.parent_company;

        const parentCompanyDetails = await SellersCompany.findByPk(parentCompanyID);
        if(parentCompanyDetails) {
          sellerName = parentCompanyDetails.company_name;
          sellerAddress = parentCompanyDetails.address;
        }
      }


    }
    const data = {
      sellerName,
      sellerAddress,
      dateNTime: formattedDate,
      customerName,
      tinNumber: "",
      terms: "",
      address: orderForm.address,
      ordNumber: orderNumber,
      orderDetails: orderDetails,
    };

    const pdfResponse = await pdfBuilder(
      templatePath,
      "delivery-receipt",
      "pdf-files",
      "landscape",
      data
    );
    if (pdfResponse) {
      const urlToRedirect = `/public/pdf-files/${pdfResponse?.file_name}`;
      res.redirect(urlToRedirect);
    }
  } catch (err) {
    next(err);
  }
};
