const emailBuilder = require("../../helpers/transporter");
const { adminOrderVerification, buildCreditMailTemplate } = require("../../helpers/email-templates/html-bodys");
const {
  adminVerifiedOrder,
  adminDeniedOrder,
  orderDeliveredTemplate,
  orderPickedUpTemplate,
} = require("./../../helpers/email-templates/html-bodys-new");
const OrderForm = require("../../models/OrderForm");
const OrderFormDetails = require("../../models/OrderFormDetails");
const Product = require("../../models/Products");
const Voucher = require("../../models/Vouchers");
const SellersCompany = require("../../models/SellersCompany");
const Customers = require("../../models/Customers");
const { filterAndFormatPhones } = require("../../helpers/common");
const smsTemplates = require("../../helpers/sms-no-templates/sms-no-templates");
const whispir = require("../../helpers/whispir");

exports.sendEmailOrderVerification = async (req, res, next) => {
  const { receiver_email, seller_email, order_reference_no } = req.body;
  try {
    const receivers = [receiver_email];
    const ccs = [seller_email];
    const emailSubj = `Buildhub - Confirmed Order #: ${order_reference_no}`;

    const orderDetail = await OrderForm.findOne({
      where: {
        reference_no: order_reference_no,
      },
      attributes: ["name"],
    });

    if (receivers.length > 0) {
      const emailResponse = await emailBuilder(
        receivers,
        ccs,
        emailSubj,
        true,
        adminVerifiedOrder(orderDetail.name, order_reference_no),
        []
      );
      res.status(200).json({ success: true, msg: "Email sent", emailResponse });
    } else {
      res.status(200).json({ success: false, msg: "No receivers found." });
    }
  } catch (err) {
    next(err);
  }
};

exports.sendBuildCreditEmail = async (req, res, next) => {
  const {
    company_email,
    contact_person,
    customer_id,
    company_name,
    credit_limit,
    credit_term,
    application_status,
    old_application_status,
  } = req.body;
  if (application_status && old_application_status) {
    if (application_status === old_application_status) return res.status(200).json({ success: true });
  }
  try {
    const customerDetail = await Customers.findByPk(customer_id);
    const customerPhone = customerDetail?.phone;

    const formattedPhone = filterAndFormatPhones([customerPhone, customerDetail.phone_2, customerDetail.phone_3]);
    const smsTemplate =
      application_status === "Approved"
        ? smsTemplates.buildCreditApproved(`${customerDetail.first_name} ${customerDetail.last_name}`, company_name)
        : // : application_status === "Case to case"
        // ? smsTemplates.buildCreditCaseToCase(`${customerDetail.first_name} ${customerDetail.last_name}`, company_name)
        application_status === "Declined"
        ? smsTemplates.buildCreditDeclined(`${customerDetail.first_name} ${customerDetail.last_name}`, company_name)
        : application_status === "Suspended"
        ? smsTemplates.buildCreditSuspended(`${customerDetail.first_name} ${customerDetail.last_name}`, company_name)
        : null;

    const receivers = [company_email];
    const emailSubj = `BuildCredit Application Update`;

    if (formattedPhone && smsTemplate) {
      const joinedCustomerPhones = formattedPhone.join(",");
      const whispirText = await whispir.messaging.singleMessage(
        {
          recipientNumber: joinedCustomerPhones,
          customTemplate: smsTemplate,
          senderAlias: "BuildCredit SMS",
        },
        "custom"
      );
    }
    if (receivers.length > 0) {
      const emailResponse = await emailBuilder(
        receivers,
        [],
        emailSubj,
        true,
        await buildCreditMailTemplate(contact_person, company_name, credit_limit, credit_term, application_status),
        []
      );
      res.status(200).json({
        success: true,
        msg: "Email sent",
        emailResponse,
      });
    } else {
      res.status(200).json({ success: false, msg: "No receivers found." });
    }
  } catch (err) {
    next(err);
  }
};

exports.sendEmailOrderDenied = async (req, res, next) => {
  const { reference_no } = req.body;

  try {
    const orderForm = await OrderForm.findOne({
      where: {
        reference_no,
      },
      attributes: ["name", "email"],
    });

    if (!orderForm) throw new Error("Order not found");

    const emailSubj = `Buildhub - Denied Order #: ${reference_no}`;
    const receivers = [orderForm.email];

    if (receivers.length > 0) {
      const emailResponse = await emailBuilder(
        receivers,
        [],
        emailSubj,
        true,
        adminDeniedOrder(orderForm.name, reference_no),
        []
      );
      res.status(200).json({ success: true, msg: "Email sent", emailResponse });
    } else {
      res.status(200).json({ success: false, msg: "No receivers found." });
    }
  } catch (err) {
    next(err);
  }
};

exports.sendEmailDelivered = async (req, res, next) => {
  const { reference_no, customer_email } = req.body;

  try {
    const orderForm = await OrderForm.findOne({
      where: {
        reference_no,
      },
      attributes: [
        "customer_id",
        "name",
        "reference_no",
        "date_created",
        "voucher_id_used",
        "delivery_fee",
        "total_amount",
        "seller_id",
        "shipping_type",
        "address",
        "date_delivered",
      ],
      include: [
        {
          model: OrderFormDetails,
          as: "order_form_details",
          attributes: ["product_id", "quantity", "discounted_price", "price", "amount"],
          include: [
            {
              model: Product,
              as: "product",
              attributes: ["menu", "photo", "discounted_price", "price"],
            },
          ],
        },
        {
          model: Voucher,
          as: "voucher_details",
          attributes: ["amount", "amount_in_percent"],
          required: false,
        },
        {
          model: SellersCompany,
          as: "sellers_company_details",
          attributes: ["shop_name", "company_name", "address"],
        },
      ],
    });

    if (!orderForm) throw new Error("Order Form not found");

    let voucherAmount = 0;
    if (orderForm.voucher_details) {
      const voucherDetail = orderForm.voucher_details;

      if (voucherDetail.amount_in_percent) {
        const totalAmount = orderForm.total_amount;
        const percent = parseFloat(voucherDetail.amount_in_percent);
        voucherAmount = (totalAmount * percent) / 100;
      } else {
        voucherAmount = parseFloat(voucherDetail.amount);
      }
    }

    const orderSummary = {
      date_delivered: orderForm.date_delivered,
      voucher_amount: voucherAmount,
      shipping_fee: orderForm.delivery_fee,
      shipping_type: orderForm.shipping_type,
      total_amount: orderForm.total_amount,
      seller_name:
        orderForm.sellers_company_details.shop_name === "" || orderForm.sellers_company_details.shop_name === null
          ? orderForm.sellers_company_details.company_name
          : orderForm.sellers_company_details.shop_name,
      seller_address: orderForm.sellers_company_details.address,
      customer_address: orderForm.address,
    };

    const productDetails = [];

    for (const orderFormDetail of orderForm.order_form_details) {
      let __productPrice = orderFormDetail.product.price;
      if (orderFormDetail.product.discounted_price && orderFormDetail.product.discounted_price > 0) {
        __productPrice = orderFormDetail.product.discounted_price;
      }

      productDetails.push({
        photo: orderFormDetail.product.photo,
        menu: orderFormDetail.product.menu,
        qty: orderFormDetail.quantity,
        price: __productPrice,
      });
    }
    const receivers = [customer_email];
    const emailResponse = await emailBuilder(
      receivers,
      [],
      "Buildhub - Order Status Update",
      true,
      orderDeliveredTemplate(reference_no, orderSummary, productDetails),
      []
    );

    res.status(200).json({ success: true, emailResponse });
  } catch (err) {
    next(err);
  }
};
exports.sendEmailPickedup = async (req, res, next) => {
  const { reference_no, customer_email } = req.body;

  try {
    const orderForm = await OrderForm.findOne({
      where: {
        reference_no,
      },
      attributes: [
        "customer_id",
        "name",
        "reference_no",
        "date_created",
        "voucher_id_used",
        "delivery_fee",
        "total_amount",
        "seller_id",
        "shipping_type",
        "address",
        "date_delivered",
      ],
      include: [
        {
          model: OrderFormDetails,
          as: "order_form_details",
          attributes: ["product_id", "quantity", "discounted_price", "price", "amount"],
          include: [
            {
              model: Product,
              as: "product",
              attributes: ["menu", "photo", "discounted_price", "price"],
            },
          ],
        },
        {
          model: Voucher,
          as: "voucher_details",
          attributes: ["amount", "amount_in_percent"],
          required: false,
        },
        {
          model: SellersCompany,
          as: "sellers_company_details",
          attributes: ["shop_name", "company_name", "address"],
        },
      ],
    });

    if (!orderForm) throw new Error("Order Form not found");

    let voucherAmount = 0;
    if (orderForm.voucher_details) {
      const voucherDetail = orderForm.voucher_details;

      if (voucherDetail.amount_in_percent) {
        const totalAmount = orderForm.total_amount;
        const percent = parseFloat(voucherDetail.amount_in_percent);
        voucherAmount = (totalAmount * percent) / 100;
      } else {
        voucherAmount = parseFloat(voucherDetail.amount);
      }
    }

    const orderSummary = {
      customer_name: orderForm.name,
      date_delivered: orderForm.date_delivered,
      voucher_amount: voucherAmount,
      shipping_fee: orderForm.delivery_fee,
      shipping_type: orderForm.shipping_type,
      total_amount: orderForm.total_amount,
      seller_name:
        orderForm.sellers_company_details.shop_name === "" || orderForm.sellers_company_details.shop_name === null
          ? orderForm.sellers_company_details.company_name
          : orderForm.sellers_company_details.shop_name,
      seller_address: orderForm.sellers_company_details.address,
      customer_address: orderForm.address,
    };

    const productDetails = [];

    for (const orderFormDetail of orderForm.order_form_details) {
      let __productPrice = orderFormDetail.product.price;
      if (orderFormDetail.product.discounted_price && orderFormDetail.product.discounted_price > 0) {
        __productPrice = orderFormDetail.product.discounted_price;
      }

      productDetails.push({
        photo: orderFormDetail.product.photo,
        menu: orderFormDetail.product.menu,
        qty: orderFormDetail.quantity,
        price: __productPrice,
      });
    }
    const receivers = [customer_email];
    const emailResponse = await emailBuilder(
      receivers,
      [],
      "Buildhub - Order Picked Up",
      true,
      orderPickedUpTemplate(reference_no, orderSummary, productDetails),
      []
    );

    res.status(200).json({ success: true, emailResponse });
  } catch (err) {
    next(err);
  }
};
