import sendEmail from "../../Utils/sendEmail.js";
import { Order } from "./orderModel.js";

export const getAllOrder = async (req, res) => {
  try {
    const { status } = req.params;
    const order = await Order.find({
      // payment_status: { $in: ["success", "failed"] },
      payment_status: "success",
      orderStatus: status,
    })
      .populate({
        path: "user",
        select: "name -_id",
      })
      .populate({
        path: "shippingInfo.addressId",

        // populate: {
        //   path: "Franchisee",
        //   select: "banner price_Lable ",
        // },
      })
      .sort({ updatedAt: -1 });
    if (order) {
      res.status(201).json({
        success: true,
        order,
        message: "All Order Fetched",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};
export const getOrders = async (req, res) => {
  try {
    const order = await Order.find({
      // payment_status: "success",
    })
      .populate({
        path: "user",
        select: "name -_id",
      })
      .populate({
        path: "shippingInfo.addressId",
      })
      .sort({ updatedAt: -1 });
    if (order) {
      res.status(201).json({
        success: true,
        order,
        message: "All Order Fetched",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};
export const getSingleOrder = async (req, res) => {
  try {
    if (!req.params.id)
      return res.status(400).json({ message: "please Provide Order Id" });

    // console.log("dddddddddddddddddddddddd");
    const order = await Order.findById(req.params.id)
      .populate({
        path: "user",
        select: "name email -_id ",
      })
      .populate({
        path: "couponUsed",
        select: "coupon_code discount_amount -_id", // Only select coupon_code and discount_amount from the couponUsed model
      })
      .populate({
        path: "shippingInfo.addressId",
      })
      .sort({ createdAt: -1 });
    if (order) {
      res.status(201).json({
        success: true,
        order,
        message: " Order Fetched",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};

//get self User Order
export const getUserSelf = async (req, res) => {
  if (!req?.user) return res.status(400).json({ message: "please login !" });
  try {
    const order = await Order.find({
      user: req.user?._id,
      payment_status: "success",
    }).sort({ createdAt: -1 });

    if (order) {
      return res.status(200).json({
        success: true,
        order,
        message: "self Order fetched",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};

export const deleteOneOrder = async (req, res) => {
  try {
    if (!req?.user) return res.status(400).json({ message: "please login !" });
    if (!req.params.id)
      return res.status(400).json({ message: "please Provide Order Id" });
    const getOrder = await Order.findById(req.params.id);
    if (!getOrder) {
      return res.status(404).json({
        success: false,
        message: "No Order  Found!",
      });
    }
    const order = await Order.findByIdAndDelete(req.params.id);

    await order.remove();
    res.status(200).json({
      success: true,
      message: "Order Deleted Successfully!!",
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message ? error.message : "Something went Wrong",
    });
  }
};
export const updateOrderStatusById = async (req, res) => {
  try {
    let body = { orderStatus: req.body.status };

    const currentDate = new Date();
    body["status_timeline." + req.body.status] = currentDate;
    // if (req.body?.package_weight) body.package_weight = req.body.package_weight;
    const order = await Order.findById(req.params.id)
      .populate({
        path: "user",
        select: "name email -_id",
      })
      .populate({
        path: "couponUsed",
        select: "coupon_code discount_amount -_id", // Only select coupon_code and discount_amount from the couponUsed model
      });
    // console.log("order", order);
    // const parentData = { email: order?.parent?.email };
    if (req.body.status === "cancelled") {
      body["order_Cancelled_Reason"] = req.body?.ReasonforCancellation;
      body["iscancelled"] = true;
      await Order.findByIdAndUpdate(order._id, body);
      await sendEmail({
        to: `${order?.user?.email}`, // Change to your recipient
        from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender
        subject: `Order #${order?.orderID} Update: Cancellation and Refund Process`,
        html: `<strong style="color: #1b03a3; font-size: 16px"> Hi ${order?.shippingInfo?.first_Name
          },</strong> 
        <h3 style="color: #333;  font-family: Arial, sans-serif;">We hope this message finds you well. We're writing to inform you that your order ${order?.orderID
          } has been canceled. We understand that circumstances may change, and we're here to assist you throughout the process.</h3>
         
         <h4 style="color: #333; font-family: Arial, sans-serif;">Any Discount : ${order?.isCouponUsed
            ? "Yes  ,₹" +
            Number(order?.couponUsed?.discount_amount) +
            " ,  COUPON_CODE:" +
            order?.couponUsed?.coupon_code
            : "No Discount"
          }</h4>     
        <h4 style="color: #333; font-family: Arial, sans-serif;"> Items :</h4>
        <table style="border-collapse: collapse; width: 100%;">
  <thead>
    <tr>
          <th style="border: 1px solid #555; padding: 2px; text-align: center;">S No.</th>
      <th style="border: 1px solid #555; padding: 2px; text-align: center;">Product Name</th>
                 <th style="border: 1px solid #555; padding: 2px; text-align: center;">Variant</th> 
            <th style="border: 1px solid #555; padding: 2px; text-align: center;">Image</th>
      <th style="border: 1px solid #555; padding: 2px; text-align: center;">Quantity</th>
      <th style="border: 1px solid #555; padding: 2px; text-align: center;">Price</th>
            <th style="border: 1px solid #555; padding: 2px; text-align: center;">GST Amount</th>
            <th style="border: 1px solid #555; padding: 2px; text-align: center;">SubTotal</th>

    </tr>
  </thead>
  <tbody>
    ${order?.orderItems
            ?.map(
              (product, index) => `
      <tr>
              <td style="border: 1px solid #555; padding: 2px; text-align: center;">${index + 1
                }</td>

        <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product.name
                }</td>
        <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product?.variant_Name
                }</td>
                <td style="border: 1px solid #555; padding: 2px; text-align: center;"><img src="${product?.image[0]?.url
                }" alt="${product.name
                }"  style="max-width: 40px; height: auto;"></td>

        <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product.quantity
                }</td>
        <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product.price
                }</td>
         <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product?.gst_amount
                }</td>
                <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product.product_Subtotal
                }</td>

      </tr>
    `
            )
            .join("")}
       <tr>
      <th colspan="7" style="border: 1px solid #555; padding: 2px; text-align: right;">Total Amount :</th>
      <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${order?.total_amount
          }</td>
    </tr>
  </tbody>
</table>
 <h4 style="color: #333; font-family: Arial, sans-serif;">Cancellation Reason : ${req.body?.ReasonforCancellation
          }</h4>
 <h4 style="color: #333; font-family: Arial, sans-serif;">Refund Information: The amount from your canceled order will be processed for a refund. Please allow up to 7 working days for the amount to be transferred back to your original payment method.</h4>

        <h5 style="color: #333; font-family: Arial, sans-serif;">If you have any concerns or further questions, please feel free to reply to this email. We appreciate your understanding and hope to serve you better in the future.
</h5>
<br/>
        <span style="color: #555; font-size: 13px;">Best regards,</span><br/>
        
        <span style="color: #555; font-size: 13px;">Team Cheminova</span>`,
      });
      return res
        .status(200)
        .json({ status: "ok", message: "Order status updated successfully!" });
    } else if (req.body.status === "processing") {
      await Order.findByIdAndUpdate(order._id, body);

      await sendEmail({
        to: `${order?.user?.email}`, // Change to your recipient
        from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender
        subject: `Your Order #${order?.orderID} is in Processing!`,
        html: ` <h3 style="color: #333;  font-family: Arial, sans-serif;">Exciting news! Your order #${order?.orderID
          } has entered the processing phase. Our team is diligently preparing your items for dispatch. Rest assured, we're working hard to ensure everything is perfect for you.</h3>
         <strong style="color: #1b03a3; font-size: 16px"> Hi ${order?.shippingInfo?.first_Name
          },</strong>
               <h4 style="color: #333; font-family: Arial, sans-serif;">Order Status : Processing</h4>
                             
 <h4 style="color: #333; font-family: Arial, sans-serif;">Any Discount : ${order?.isCouponUsed
            ? "Yes  ,₹" +
            Number(order?.couponUsed?.discount_amount) +
            " ,  COUPON_CODE:" +
            order?.couponUsed?.coupon_code
            : "No Discount"
          }</h4>

        <h4 style="color: #333; font-family: Arial, sans-serif;">Order Items :</h4>
        <table style="border-collapse: collapse; width: 100%;">
  <thead>
    <tr>
          <th style="border: 1px solid #555; padding: 2px; text-align: center;">S No.</th>

      <th style="border: 1px solid #555; padding: 2px; text-align: center;">Product Name</th>
                  <th style="border: 1px solid #555; padding: 2px; text-align: center;">Variant</th>
            <th style="border: 1px solid #555; padding: 2px; text-align: center;">Image</th>

      <th style="border: 1px solid #555; padding: 2px; text-align: center;">Quantity</th>
      <th style="border: 1px solid #555; padding: 2px; text-align: center;">Price</th>
            <th style="border: 1px solid #555; padding: 2px; text-align: center;">GST Amount</th>

            <th style="border: 1px solid #555; padding: 2px; text-align: center;">SubTotal</th>

    </tr>
  </thead>
  <tbody>
    ${order?.orderItems
            ?.map(
              (product, index) => `
      <tr>
              <td style="border: 1px solid #555; padding: 2px; text-align: center;">${index + 1
                }</td>

        <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product.name
                }</td>
        <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product?.variant_Name
                }</td>
                <td style="border: 1px solid #555; padding: 2px; text-align: center;"><img src="${product?.image[0]?.url
                }" alt="${product.name
                }"  style="max-width: 40px; height: auto;"></td>

        <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product.quantity
                }</td>
        <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product.price
                }</td>
         <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product?.gst_amount
                }</td>
                <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product.product_Subtotal
                }</td>

      </tr>
    `
            )
            .join("")}
       <tr>
      <th colspan="7" style="border: 1px solid #555; padding: 2px; text-align: right;">Total Amount :</th>
      <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${order?.total_amount
          }</td>
      
    </tr>
  </tbody>
</table>
        <h5 style="color: #333; font-family: Arial, sans-serif;">We'll send you another email with the tracking details as soon as your order is dispatched. If you have any questions or need assistance, feel free to reply to this email.</h5>
                <h5 style="color: #333; font-family: Arial, sans-serif;">Thank you for choosing Cheminova!</h5>
<br/>
        <span style="color: #555; font-size: 13px;">Best regards,</span><br/>
        
        <span style="color: #555; font-size: 13px;">Team Cheminova</span>`,
      });
      return res
        .status(200)
        .json({ status: "ok", message: "Order status updated successfully!" });
    }
    // else if (body.status === "dispatched") {
    //   const noBalanceRemaining =
    //     order?.sales_items?.filter((e) => Number(e?.balance_quantity) > 0)
    //       ?.length === 0
    //       ? true
    //       : false;
    //   if (!noBalanceRemaining)
    //     return res
    //       .status(400)
    //       .json({ message: "Few items still have balance quantity!" });
    //   await OrderDispatchedEmail(parentData.email, order.order_id, body);
    //   await Invoice.updateMany(
    //     { order: order._id, status: { $in: ["processing"] } },
    //     { status: body.status, "status_timeline.dispatched": currentDate }
    //   );
    // } else if (body.status === "delivered") {
    //   await OrderDeliveredEmail(parentData.email, order.order_id);
    //   await Invoice.updateMany(
    //     { order: order._id, status: { $in: ["processing", "dispatched"] } },
    //     { status: body.status, "status_timeline.delivered": currentDate }
    //   );
    // }
    else if (req.body.status === "dispatched") {
      body["courier_name"] = req.body.courierName;
      body["courier_tracking_id"] = req.body.TrackingID;
      await Order.findByIdAndUpdate(order._id, body);
      await sendEmail({
        to: `${order?.user?.email}`, // Change to your recipient
        from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender
        subject: `Your Order #${order?.orderID} is On Its Way!`,
        html: `<strong style="color: #1b03a3; font-size: 16px"> Hi ${order?.shippingInfo?.first_Name
          },</strong> 
        <h3 style="color: #333;  font-family: Arial, sans-serif;">Exciting news! Your order #${order?.orderID
          } has been dispatched and is en route to you. 🚚 Here are the details:</h3>

        <h4 style="color: #333;  font-family: Arial, sans-serif;">Courier Name : ${req.body.courierName
          } </h4>
        <h4 style="color: #333;  font-family: Arial, sans-serif;">Courier Tracking ID : ${req.body.TrackingID
          }</h4>
         
         <h4 style="color: #333; font-family: Arial, sans-serif;">Any Discount : ${order?.isCouponUsed
            ? "Yes  ,₹" +
            Number(order?.couponUsed?.discount_amount) +
            " ,  COUPON_CODE:" +
            order?.couponUsed?.coupon_code
            : "No Discount"
          }</h4>     
        <h4 style="color: #333; font-family: Arial, sans-serif;"> Items :</h4>
        <table style="border-collapse: collapse; width: 100%;">
  <thead>
    <tr>
          <th style="border: 1px solid #555; padding: 2px; text-align: center;">S No.</th>

      <th style="border: 1px solid #555; padding: 2px; text-align: center;">Product Name</th>
                  <th style="border: 1px solid #555; padding: 2px; text-align: center;">Variant</th>
            <th style="border: 1px solid #555; padding: 2px; text-align: center;">Image</th>

      <th style="border: 1px solid #555; padding: 2px; text-align: center;">Quantity</th>
      <th style="border: 1px solid #555; padding: 2px; text-align: center;">Price</th>
            <th style="border: 1px solid #555; padding: 2px; text-align: center;">GST Amount</th>

            <th style="border: 1px solid #555; padding: 2px; text-align: center;">SubTotal</th>

    </tr>
  </thead>
  <tbody>
    ${order?.orderItems
            ?.map(
              (product, index) => `
      <tr>
              <td style="border: 1px solid #555; padding: 2px; text-align: center;">${index + 1
                }</td>

        <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product.name
                }</td>
        <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product?.variant_Name
                }</td>
                <td style="border: 1px solid #555; padding: 2px; text-align: center;"><img src="${product?.image[0]?.url
                }" alt="${product.name
                }"  style="max-width: 40px; height: auto;"></td>

        <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product.quantity
                }</td>
        <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product.price
                }</td>
         <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product?.gst_amount
                }</td>
                <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product.product_Subtotal
                }</td>

      </tr>
    `
            )
            .join("")}
       <tr>
      <th colspan="7" style="border: 1px solid #555; padding: 2px; text-align: right;">Total Amount :</th>
      <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${order?.total_amount
          }</td>
    </tr>
  </tbody>
</table>
 <h3 style="color: #333; font-family: Arial, sans-serif;">Order Status : Dispatched</h3>
        <h4 style="color: #333; font-family: Arial, sans-serif;">If you have any questions or need assistance, feel free to reply to this email.
</h4>
<h5 style="color: #333; font-family: Arial, sans-serif;">Thanks for choosing Cheminova! We hope you enjoy your purchase.
</h5>
<br/>
        <span style="color: #555; font-size: 13px;">Best regards,</span><br/>
        
        <span style="color: #555; font-size: 13px;">Team Cheminova</span>`,
      });
      return res
        .status(200)
        .json({ status: "ok", message: "Order status updated successfully!" });
    } else if (req.body.status === "delivered") {
      body["isDelivered"] = true;
      body["DeliveredDate"] = req.body.DDate;
      await Order.findByIdAndUpdate(order._id, body);
      await sendEmail({
        to: `${order?.user?.email}`, // Change to your recipient
        from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender
        subject: `Your Order #${order?.orderID} Has Been Delivered!`,
        html: `<strong style="color: #1b03a3; font-size: 16px"> Hi ${order?.shippingInfo?.first_Name
          },</strong>
              <h3 style="color: #333;  font-family: Arial, sans-serif;">Great news! Your order #${order?.orderID
          } has been successfully delivered to your doorstep. We hope everything is just as you expected!</h3>
              <h4 style="color: #333; font-family: Arial, sans-serif;">Any Discount : ${order?.isCouponUsed
            ? "Yes  ,₹" +
            Number(order?.couponUsed?.discount_amount) +
            " ,  COUPON_CODE:" +
            order?.couponUsed?.coupon_code
            : "No Discount"
          }</h4>
              <h4 style="color: #333; font-family: Arial, sans-serif;"> Items :</h4>
              <table style="border-collapse: collapse; width: 100%;">
        <thead>
          <tr>
                <th style="border: 1px solid #555; padding: 2px; text-align: center;">S No.</th>

            <th style="border: 1px solid #555; padding: 2px; text-align: center;">Product Name</th>
                        <th style="border: 1px solid #555; padding: 2px; text-align: center;">Variant</th>
                  <th style="border: 1px solid #555; padding: 2px; text-align: center;">Image</th>
            <th style="border: 1px solid #555; padding: 2px; text-align: center;">Quantity</th>
            <th style="border: 1px solid #555; padding: 2px; text-align: center;">Price</th>
                  <th style="border: 1px solid #555; padding: 2px; text-align: center;">GST Amount</th>

                  <th style="border: 1px solid #555; padding: 2px; text-align: center;">SubTotal</th>

          </tr>
        </thead>
        <tbody>
          ${order?.orderItems
            ?.map(
              (product, index) => `
            <tr>
                    <td style="border: 1px solid #555; padding: 2px; text-align: center;">${index + 1
                }</td>

              <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product.name
                }</td>
              <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product?.variant_Name
                }</td>
                      <td style="border: 1px solid #555; padding: 2px; text-align: center;"><img src="${product?.image[0]?.url
                }" alt="${product.name
                }"  style="max-width: 40px; height: auto;"></td>

              <td style="border: 1px solid #555; padding: 2px; text-align: center;">${product.quantity
                }</td>
              <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product.price
                }</td>
               <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product?.gst_amount
                }</td>
                      <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${product.product_Subtotal
                }</td>

            </tr>
          `
            )
            .join("")}
             <tr>
            <th colspan="7" style="border: 1px solid #555; padding: 2px; text-align: right;">Total Amount :</th>
            <td style="border: 1px solid #555; padding: 2px; text-align: center;">₹${order?.total_amount
          }</td>
          </tr>
        </tbody>
      </table>
       <h3 style="color: #333; font-family: Arial, sans-serif;">Delivery Date: ${req.body.DDate
          }</h3>
              <h4 style="color: #333; font-family: Arial, sans-serif;">Your satisfaction is our priority, and we'd love to hear about your experience. Please take a moment to share your thoughts by leaving a review. Your feedback is invaluable to us!
      </h4>
      <h5 style="color: #333; font-family: Arial, sans-serif;">If you have any questions or concerns about your order, feel free to reply to this email.
      </h5>
      <h5 style="color: #333; font-family: Arial, sans-serif;">Thank you for choosing Cheminova! We hope to serve you again soon.

      </h5>
      <br/>
              <span style="color: #555; font-size: 13px;">Best regards,</span><br/>

              <span style="color: #555; font-size: 13px;">Team Cheminova</span>`,
      });

      return res
        .status(200)
        .json({ status: "ok", message: "Order status updated successfully!" });
    } else {
      // await Order.findByIdAndUpdate(order._id, body);
      // console.log(order);
      res
        .status(200)
        .json({ status: "ok", message: "Order status updated successfully!" });
    }
  } catch (error) {
    console.log(error);
    res
      .status(500)
      .json({ message: error?.message || "Something went wrong!" });
  }
};
