const OrderForm = require("../models/OrderForm");
const { Sequelize } = require('sequelize'); // Import Sequelize
const jwt = require("jsonwebtoken");
const errorHandler = require("../util/errorHandler");
const multer = require('multer');

// Get all
exports.getAllOrderform = async (req, res) => {
  try {
    const orderform = await OrderForm.findAll();

    const Orderforresponse = orderform.map(order => ({
      OrderForm_Id: order.id,
      Email_Address: order.email,
      Name: order.name,
      Customer_ID: order.customer_id,
      AgentCode: order.agentCode,
      Contact_Number: order.contact_number,
      Pickup_Date: order.pickup_date,
      Note: order.note,
      Pickup_Method: order.pickup_method,
      Mode_of_Payment: order.mode_of_payment,
      Subtotal_Amount: order.subtotal_amount,
      Total_Amount: order.total_amount,
      Proof_of_Payment: order.proof_of_payment,
      Pickup_by: order.pickup_by,
      Released_by: order.released_by,
      Reference_Number: order.reference_no,
      Payment_Date: order.payment_date,
      Status: order.status,
      Total_Quantity: order.total_qty,
      Released_Status: order.released_status,
      Released_Date: order.released_date,
      Pickup_Location: order.pickup_location,
      Price: order.price,
      Address: order.address,
      Longitude: order.longitude,
      Latitude: order.latitude,
      Pickup_DateTime: order.pickup_datetime,
      Payment_Method: order.payment_method,
      Rpaf_Due_Date: order.rpaf_due_date,
      Total_Distance: order.total_distance,
      Delivery_Fee: order.delivery_fee,
      Shipping_Type: order.shipping_type,
      Delivery_Status: order.delivery_status,
      Signature: order.signature,
      Seller_ID: order.seller_id,
      Driver: order.driver,
      Truck: order.truck,
      Date_delivered: order.date_delivered,
      Delivered_Picture: order.delivered_picture,
      Voucher_ID_Used: order.voucher_id_used,
      DateTime_Verified: order.dateTime_verified,
      DateTime_for_Preparation: order.dateTime_for_preparation,
      DateTime_Ready_Pickup: order.dateTime_ready_pickup,
      DateTime_for_Delivery: order.dateTime_for_delivery,
      Logistics_ID: order.logistics_id,
      Pickup_Photo: order.pickup_photo,
      Upload_Pickup_Photo: order.upload_pickup_photo,
      Remarks: order.remarks,
      Split_Payment_ID: order.split_payment_id,
      Cancel_Reason: order.cancel_reason,
      Release_Order_Image: order.release_order_image,
      Warehouse_Delivery_Release_Image: order.warehouse_delivery_release_image,
      Admin_Remarks: order.admin_remarks,
      Absolute_Logistics_Fee: order.absolute_logistics_fee,
      Logistic_Fee: order.logistics_fee,
      Loading_Fee: order.loading_fee,
      Unloading_fee: order.unloading_fee,
      Order_Verified_By: order.order_verified_by,
      Has_Sub_Variation_Chosen: order.has_sub_variation_chosen,
      Product_Variation_Id: order.product_variation_id,
      Product_Sub_Variation_id: order.product_sub_variation_id
    }));

    res.status(200).json(Orderforresponse);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

// Get by ID
exports.getrorderformId = async (req, res) => {
  const { orderformID } = req.params;

  try {
      const order = await OrderForm.findByPk(orderformID);

      if (!order) {
          return res.status(404).json({ error: "OrderForm ID not found" });
      }

      // Mapping of fields in the response
      const response = {
        OrderForm_Id: order.id,
        Email_Address: order.email,
        Name: order.name,
        Customer_ID: order.customer_id,
        AgentCode: order.agentCode,
        Contact_Number: order.contact_number,
        Pickup_Date: order.pickup_date,
        Note: order.note,
        Pickup_Method: order.pickup_method,
        Mode_of_Payment: order.mode_of_payment,
        Subtotal_Amount: order.subtotal_amount,
        Total_Amount: order.total_amount,
        Proof_of_Payment: order.proof_of_payment,
        Pickup_by: order.pickup_by,
        Released_by: order.released_by,
        Reference_Number: order.reference_no,
        Payment_Date: order.payment_date,
        Status: order.status,
        Total_Quantity: order.total_qty,
        Released_Status: order.released_status,
        Released_Date: order.released_date,
        Pickup_Location: order.pickup_location,
        Price: order.price,
        Address: order.address,
        Longitude: order.longitude,
        Latitude: order.latitude,
        Pickup_DateTime: order.pickup_datetime,
        Payment_Method: order.payment_method,
        Rpaf_Due_Date: order.rpaf_due_date,
        Total_Distance: order.total_distance,
        Delivery_Fee: order.delivery_fee,
        Shipping_Type: order.shipping_type,
        Delivery_Status: order.delivery_status,
        Signature: order.signature,
        Seller_ID: order.seller_id,
        Driver: order.driver,
        Truck: order.truck,
        Date_delivered: order.date_delivered,
        Delivered_Picture: order.delivered_picture,
        Voucher_ID_Used: order.voucher_id_used,
        DateTime_Verified: order.dateTime_verified,
        DateTime_for_Preparation: order.dateTime_for_preparation,
        DateTime_Ready_Pickup: order.dateTime_ready_pickup,
        DateTime_for_Delivery: order.dateTime_for_delivery,
        Logistics_ID: order.logistics_id,
        Pickup_Photo: order.pickup_photo,
        Upload_Pickup_Photo: order.upload_pickup_photo,
        Remarks: order.remarks,
        Split_Payment_ID: order.split_payment_id,
        Cancel_Reason: order.cancel_reason,
        Release_Order_Image: order.release_order_image,
        Warehouse_Delivery_Release_Image: order.warehouse_delivery_release_image,
        Admin_Remarks: order.admin_remarks,
        Absolute_Logistics_Fee: order.absolute_logistics_fee,
        Logistic_Fee: order.logistics_fee,
        Loading_Fee: order.loading_fee,
        Unloading_fee: order.unloading_fee,
        Order_Verified_By: order.order_verified_by,
        Has_Sub_Variation_Chosen: order.has_sub_variation_chosen,
        Product_Variation_Id: order.product_variation_id,
        Product_Sub_Variation_id: order.product_sub_variation_id
      };

      res.status(200).json(response);
  } catch (error) {
      console.error(error);
      res.status(500).json({ error: "Internal Server Error" });
  }
};


  // Delete by ID
exports.deleteorderform = (req, res) => {
    const { orderformID } = req.params;
  
    try {
      const deletedRowCount = OrderForm.destroy({
        where: {
          id: orderformID,
        },
      });
  
      if (deletedRowCount === 0) {
        return res.status(404).json({ error: "OrderForm not found" });
      }
  
      res.status(204).send();
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: "Internal Server Error" });
    }
  };

  exports.createorderform = async (req, res, next) => {
    try {
        const { data } = req.body;
        const {
            // Request body fields
            email,
            name,
            customer_id,
            agentCode,
            contact_number,
            pickup_method,
            mode_of_payment,
            subtotal_amount,
            total_amount,
            proof_of_payment,
            pickup_by,
            released_by,
            status,
            total_qty,
            released_status,
            pickup_location,
            price,
            address,
            longitude,
            latitude,
            payment_method,
            total_distance,
            delivery_fee,
            shipping_type,
            delivery_status,
            signature,
            seller_id,
            driver,
            truck,
            voucher_id_used,
            logistics_id,
            pickup_photo,
            upload_pickup_photo,
            remarks,
            split_payment_id,
            cancel_reason,
            release_order_image,
            warehouse_delivery_release_image,
            admin_remarks,
            absolute_logistics_fee,
            logistics_fee,
            loading_fee,
            unloading_fee,
            order_verified_by,
            has_sub_variation_chosen,
            product_variation_id,
            product_sub_variation_id,
        } = data;

        const reference_no = "RPREF" + Math.random().toString(36).substring(2, 10).toUpperCase();

        const currentDate = new Date();

        const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

        if (!isValidEmail) {
            return res.status(400).json({ error: 'Please enter a valid email address' });
        }

        if (status !== "Delivered" && status !== "Ready for Pickup" && status !== "Cancelled" && status !== "Verified" && status !== "To received" && status !== "Ready for Customer Pickup" && status !== "Received" && status !== "Denied" && status !== "To Deliver" && status !== "Pending") {
            return errorHandler('status must be "Delivered", "Ready for Pickup", "Cancelled" , "Verified" , "To received" ,"Ready for Customer Pickup" ,"Received"', 404);
        }

        if (!req.files || !req.files.note) {
            return errorHandler("note photo is missing from the request.", 500);
        }

        if (!req.files || !req.files.delivered_picture) {
            return errorHandler("delivered_picture is missing from the request.", 500);
        }

        const uploadedImage = req.files.uploadedImage || [];
        const delivered_picture = req.files.delivered_picture || [];

        const orderForm = new OrderForm({
            email: email,
            name: name,
            customer_id: customer_id,
            agentCode: agentCode,
            contact_number: contact_number,
            pickup_date: currentDate,
            note: uploadedImage.length > 0 ? uploadedImage[0].filename : null,
            pickup_method: pickup_method,
            mode_of_payment: mode_of_payment,
            subtotal_amount: subtotal_amount,
            total_amount: total_amount,
            proof_of_payment: proof_of_payment,
            pickup_by: pickup_by,
            released_by: released_by,
            reference_no: reference_no,
            currentDate: currentDate,
            status: status,
            total_qty: total_qty,
            released_status: released_status,
            currentDate: currentDate,
            pickup_location: pickup_location,
            price: price,
            address: address,
            longitude: longitude,
            latitude: latitude,
            pickup_datetime: currentDate,
            Payment_Method: payment_method,
            rpaf_due_date: currentDate,
            total_distance: total_distance,
            delivery_fee: delivery_fee,
            shipping_type: shipping_type,
            delivery_status: delivery_status,
            signature: signature,
            seller_id: seller_id,
            driver: driver,
            truck: truck,
            date_delivered: currentDate,
            delivered_picture: delivered_picture.length > 0 ? delivered_picture[0].filename : null,
            voucher_id_used: voucher_id_used,
            date_delivered: currentDate,
            dateTime_for_preparation: currentDate,
            dateTime_ready_pickup: currentDate,
            dateTime_for_delivery: currentDate,
            logistics_id: logistics_id,
            pickup_photo: pickup_photo,
            upload_pickup_photo: upload_pickup_photo,
            remarks: remarks,
            split_payment_id: split_payment_id,
            cancel_reason: cancel_reason,
            release_order_image: release_order_image,
            warehouse_delivery_release_image: warehouse_delivery_release_image,
            admin_remarks: admin_remarks,
            absolute_logistics_fee: absolute_logistics_fee,
            logistics_fee: logistics_fee,
            loading_fee: loading_fee,
            unloading_fee: unloading_fee,
            order_verified_by: order_verified_by,
            has_sub_variation_chosen: has_sub_variation_chosen,
            product_variation_id: product_variation_id,
            product_sub_variation_id: product_sub_variation_id,
        });

        await orderForm.save();

        // Response fields
        res.status(201).json({ 
            success: true,
            OrderFormCreated: 
            {
            reference_no: orderForm.reference_no,
            orderForm_id: orderForm.id,
            created_at: orderForm.createdAt,
            email: email,
            customer_name: name,
            customer_id: customer_id,
            agentCode: agentCode,
            contact_number: contact_number,
            pickup_date: currentDate,
            note: uploadedImage.length > 0 ? uploadedImage[0].filename : null,
            pickup_method: pickup_method,
            mode_of_payment: mode_of_payment,
            subtotal_amount: subtotal_amount,
            total_amount: total_amount,
            proof_of_payment: proof_of_payment,
            pickup_by: pickup_by,
            released_by: released_by,
            reference_no: reference_no,
            currentDate: currentDate,
            status: status,
            total_qty: total_qty,
            released_status: released_status,
            currentDate: currentDate,
            pickup_location: pickup_location,
            price: price,
            address: address,
            longitude: longitude,
            latitude: latitude,
            pickup_datetime: currentDate,
            Payment_Method: payment_method,
            rpaf_due_date: currentDate,
            total_distance: total_distance,
            delivery_fee: delivery_fee,
            shipping_type: shipping_type,
            delivery_status: delivery_status,
            signature: signature,
            seller_id: seller_id,
            driver: driver,
            truck: truck,
            date_delivered: currentDate,
            delivered_picture: delivered_picture.length > 0 ? delivered_picture[0].filename : null,
            voucher_id_used: voucher_id_used,
            date_delivered: currentDate,
            dateTime_for_preparation: currentDate,
            dateTime_ready_pickup: currentDate,
            dateTime_for_delivery: currentDate,
            logistics_id: logistics_id,
            pickup_photo: pickup_photo,
            upload_pickup_photo: upload_pickup_photo,
            remarks: remarks,
            split_payment_id: split_payment_id,
            cancel_reason: cancel_reason,
            release_order_image: release_order_image,
            warehouse_delivery_release_image: warehouse_delivery_release_image,
            admin_remarks: admin_remarks,
            absolute_logistics_fee: absolute_logistics_fee,
            logistics_fee: logistics_fee,
            loading_fee: loading_fee,
            unloading_fee: unloading_fee,
            order_verified_by: order_verified_by,
            has_sub_variation_chosen: has_sub_variation_chosen,
            product_variation_id: product_variation_id,
            product_sub_variation_id: product_sub_variation_id,

            }
        });
    } catch (error) {
        next(error);
    }
};


exports.updateorderform = (req, res) => {
  const { orderformID } = req.params; // id
  const { data } = req.body;
  const {
      email,
      name,
      agentCode,
      contact_number,
      pickup_method,
      mode_of_payment,
      subtotal_amount,
      total_amount,
      proof_of_payment,
      pickup_by,
      released_by,
      status,
      total_qty,
      released_status,
      pickup_location,
      price,
      address,
      longitude,
      latitude,
      payment_method,
      total_distance,
      delivery_fee,
      shipping_type,
      delivery_status,
      signature,
      seller_id,
      driver,
      truck,
      voucher_id_used,
      logistics_id,
      pickup_photo,
      upload_pickup_photo,
      remarks,
      split_payment_id,
      cancel_reason,
      release_order_image,
      warehouse_delivery_release_image,
      admin_remarks,
      absolute_logistics_fee,
      logistics_fee,
      loading_fee,
      unloading_fee,
      order_verified_by,
      has_sub_variation_chosen,
      product_variation_id,
      product_sub_variation_id,
  } = data;

  const reference_no = "RPREF" + Math.random().toString(36).substring(2, 10).toUpperCase();

  const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  if (!isValidEmail) {
      return res.status(400).json({ error: 'Please enter a valid email address' });
  }

  const currentDate = new Date();

  const { note } = req.files;
  const { delivered_picture } = req.files;

  OrderForm.findOne({
          where: {
              id: orderformID,
          },
      })
      .then((orderform) => {
          if (!orderform) {
              return errorHandler("OrderForm ID does not exist!", 404);
          }

          if (status !== "Delivered" && status !== "Ready for Pickup" && status !== "Cancelled" && status !== "Verified" && status !== "To received" && status !== "Ready for Customer Pickup" && status !== "Received") {
              return errorHandler('status must be "Delivered", "Ready for Pickup", "Cancelled" , "Verified" , "To received" ,"Ready for Customer Pickup" ,"Received"', 404);
          }

          if (note && note.length > 0) {
              orderform.note = note[0].filename;
          } else {
              orderform.note = null;
          }

          if (delivered_picture && delivered_picture.length > 0) {
              orderform.delivered_picture = delivered_picture[0].filename;
          } else {
              orderform.delivered_picture = null;
          }

          // Update orderform with new data
          orderform.email = email;
          orderform.name = name;
          orderform.agentCode = agentCode;
          orderform.contact_number = contact_number;
          orderform.pickup_date = currentDate;
          orderform.pickup_method = pickup_method;
          orderform.mode_of_payment = mode_of_payment;
          orderform.subtotal_amount = subtotal_amount;
          orderform.total_amount = total_amount;
          orderform.proof_of_payment = proof_of_payment;
          orderform.pickup_by = pickup_by;
          orderform.released_by = released_by;
          orderform.reference_no = reference_no;
          orderform.currentDate = currentDate;
          orderform.status = status;
          orderform.total_qty = total_qty;
          orderform.released_status = released_status;
          orderform.pickup_location = pickup_location;
          orderform.price = price;
          orderform.address = address;
          orderform.longitude = longitude;
          orderform.latitude = latitude;
          orderform.pickup_datetime = currentDate;
          orderform.payment_method = payment_method;
          orderform.rpaf_due_date = currentDate;
          orderform.total_distance = total_distance;
          orderform.delivery_fee = delivery_fee;
          orderform.shipping_type = shipping_type;
          orderform.delivery_status = delivery_status;
          orderform.signature = signature;
          orderform.seller_id = seller_id;
          orderform.driver = driver;
          orderform.truck = truck;
          orderform.date_delivered = currentDate;
          orderform.voucher_id_used = voucher_id_used;
          orderform.date_delivered = currentDate;
          orderform.dateTime_for_preparation = currentDate;
          orderform.dateTime_ready_pickup = currentDate;
          orderform.dateTime_for_delivery = currentDate;
          orderform.logistics_id = logistics_id;
          orderform.pickup_photo = pickup_photo;
          orderform.upload_pickup_photo = upload_pickup_photo;
          orderform.remarks = remarks;
          orderform.split_payment_id = split_payment_id;
          orderform.cancel_reason = cancel_reason;
          orderform.release_order_image = release_order_image;
          orderform.warehouse_delivery_release_image = warehouse_delivery_release_image;
          orderform.admin_remarks = admin_remarks;
          orderform.absolute_logistics_fee = absolute_logistics_fee;
          orderform.logistics_fee = logistics_fee;
          orderform.loading_fee = loading_fee;
          orderform.unloading_fee = unloading_fee;
          orderform.order_verified_by = order_verified_by;
          orderform.has_sub_variation_chosen = has_sub_variation_chosen;
          orderform.product_variation_id = product_variation_id;
          orderform.product_sub_variation_id = product_sub_variation_id;

          return orderform.save();
      })
      .then((updatedOrderForm) => {
        res.status(200).json({
            success: true,
            OrderFormUpdated: 
            {
            OrderForm_Id: updatedOrderForm.id,
            email,
            customer_Name:name,
            agentCode,
            contact_number,
            pickup_method,
            mode_of_payment,
            subtotal_amount,
            total_amount,
            proof_of_payment,
            pickup_by,
            released_by,
            reference_no: updatedOrderForm.reference_no,
            currentDate,
            status,
            total_qty,
            released_status,
            pickup_location,
            price,
            address,
            longitude,
            latitude,
            pickup_datetime: currentDate,
            payment_method,
            rpaf_due_date: currentDate,
            total_distance,
            delivery_fee,
            shipping_type,
            delivery_status,
            signature,
            seller_id,
            driver,
            truck,
            date_delivered: currentDate,
            voucher_id_used,
            dateTime_for_preparation: currentDate,
            dateTime_ready_pickup: currentDate,
            dateTime_for_delivery: currentDate,
            logistics_id,
            pickup_photo,
            upload_pickup_photo,
            remarks,
            split_payment_id,
            cancel_reason,
            release_order_image,
            warehouse_delivery_release_image,
            admin_remarks,
            absolute_logistics_fee,
            logistics_fee,
            loading_fee,
            unloading_fee,
            order_verified_by,
            has_sub_variation_chosen,
            product_variation_id,
            product_sub_variation_id
            }
        });
      })

      .catch((error) => {
          console.error(error);
          res.status(500).json({ error: 'Internal server error' });
      });
};


exports.getAllOrdersByAgent = async (req, res) => {
  try {
    const orderform = await OrderForm.findAll({
      where: {
        agentCode: {
          [Sequelize.Op.not]: null, // agentCode is not null
          [Sequelize.Op.not]: ''   // agentCode is not empty
        }
      }
    });

    const Orderforresponse = orderform.map(order => ({
      OrderForm_Id: order.id,
      Email_Address: order.email,
      Name: order.name,
      Customer_ID: order.customer_id,
      AgentCode: order.agentCode,
      Contact_Number: order.contact_number,
      Pickup_Date: order.pickup_date,
      Note: order.note,
      Pickup_Method: order.pickup_method,
      Mode_of_Payment: order.mode_of_payment,
      Subtotal_Amount: order.subtotal_amount,
      Total_Amount: order.total_amount,
      Proof_of_Payment: order.proof_of_payment,
      Pickup_by: order.pickup_by,
      Released_by: order.released_by,
      Reference_Number: order.reference_no,
      Payment_Date: order.payment_date,
      Status: order.status,
      Total_Quantity: order.total_qty,
      Released_Status: order.released_status,
      Released_Date: order.released_date,
      Pickup_Location: order.pickup_location,
      Price: order.price,
      Address: order.address,
      Longitude: order.longitude,
      Latitude: order.latitude,
      Pickup_DateTime: order.pickup_datetime,
      Payment_Method: order.payment_method,
      Rpaf_Due_Date: order.rpaf_due_date,
      Total_Distance: order.total_distance,
      Delivery_Fee: order.delivery_fee,
      Shipping_Type: order.shipping_type,
      Delivery_Status: order.delivery_status,
      Signature: order.signature,
      Seller_ID: order.seller_id,
      Driver: order.driver,
      Truck: order.truck,
      Date_delivered: order.date_delivered,
      Delivered_Picture: order.delivered_picture,
      Voucher_ID_Used: order.voucher_id_used,
      DateTime_Verified: order.dateTime_verified,
      DateTime_for_Preparation: order.dateTime_for_preparation,
      DateTime_Ready_Pickup: order.dateTime_ready_pickup,
      DateTime_for_Delivery: order.dateTime_for_delivery,
      Logistics_ID: order.logistics_id,
      Pickup_Photo: order.pickup_photo,
      Upload_Pickup_Photo: order.upload_pickup_photo,
      Remarks: order.remarks,
      Split_Payment_ID: order.split_payment_id,
      Cancel_Reason: order.cancel_reason,
      Release_Order_Image: order.release_order_image,
      Warehouse_Delivery_Release_Image: order.warehouse_delivery_release_image,
      Admin_Remarks: order.admin_remarks,
      Absolute_Logistics_Fee: order.absolute_logistics_fee,
      Logistic_Fee: order.logistics_fee,
      Loading_Fee: order.loading_fee,
      Unloading_fee: order.unloading_fee,
      Order_Verified_By: order.order_verified_by,
      Has_Sub_Variation_Chosen: order.has_sub_variation_chosen,
      Product_Variation_Id: order.product_variation_id,
      Product_Sub_Variation_id: order.product_sub_variation_id
    }));

    res.status(200).json(Orderforresponse);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};
