const sequelize = require("../config/dbconnection");
const { empty } = require('../Helpers/Common');
const CustomerOrderProduct = require('../models/customerOrderProduct')
const Installation = require('../models/installation')
const CustomerOrder = require('../models/customerOrder')
const Product = require('../models/product')
const Requests = require('../models/request')
const signAgreement = require('../models/signAgreement');
const Community=require("../models/community");
const { FACILITY_ID } = require("../config/SplitManagementDb");
const { filteredSignwiseInstalations } = require("../Helpers/SplitManagementHelper");
const { default: axios } = require("axios");
const SplitManagementModel = require('../models/SplitManagementModel');
const Request = require('../models/request');
const { PRODUCTION, realmId, getNewAccessToken } = require("../quickbook/quickbook");

//////////////////////////Qb

const fetchTaxAmountFromEstimateById = async (estimateId, installation_acceptance) => {
    let token = await getNewAccessToken();
    try {
      const qbType  = installation_acceptance == 1 ? 'invoice' : 'estimate';
      const apiUrl = PRODUCTION
        ? `https://quickbooks.api.intuit.com/v3/company/${realmId}/${qbType}/${estimateId}`
        : `https://sandbox-quickbooks.api.intuit.com/v3/company/${realmId}/${qbType}/${estimateId}`;
  
      const response = await axios.get(apiUrl, {
        headers: {
          Authorization: `Bearer ${token}`,
          'Accept': 'application/json',
        },
      });
  
      if (response.status === 200) {
        // Extract the estimate object
        let estimate = null
        if(installation_acceptance == 1){
            estimate = response.data.Invoice;
        }else{
            estimate = response.data.Estimate;
        }
  
        // Filter for the Sales Tax Line with ItemRef value == 3428
        const salesTaxLine = estimate.Line.find(item => 
          item.SalesItemLineDetail && item.SalesItemLineDetail.ItemRef && item.SalesItemLineDetail.ItemRef.value == '3428'
        );
  
        // Check if the Sales Tax Line exists
        if (salesTaxLine) {
          // Return the sales tax amount directly
          const salesTaxAmount = salesTaxLine.Amount || 0;
          console.log("Sales Tax Amount:", salesTaxAmount);
          return salesTaxAmount;
        } else {
          console.log("Sales Tax Line with ItemRef value 3428 not found.");
          return 0;
        }
      } else {
        console.log("Failed to fetch the estimate.");
        return 0;
      }
    } catch (error) {
      if (error.response) {
        console.error('Error fetching estimate. Status:', error.response.status);
        console.error('Error data:', error.response.data);
      } else {
        console.error('Error message:', error.message);
      }
      return 0;
    }
  };


///////////////////////////
const customerOrderProductById = async (req, res) => {
    try {
        const { isMirrored = false, targetFacilityId = null, userType = null, userId = null, From = null, teamId = null} = req.body || {};
        let { id } = req.params;
        if(isMirrored && targetFacilityId && id ){
            const targetFacility = filteredSignwiseInstalations.find(
                f => f.id === Number(targetFacilityId)
              );
              console.log('targetFacility.url 1', targetFacility.url , id)
              if (!targetFacility?.url) return null;
              console.log('targetFacility.url 2', targetFacility.url, id)
              const projectResponse = await axios.post(
                `${targetFacility.url}get-customer-order-product/${id}`);
              if(projectResponse?.data){
                return res.send(projectResponse.data)
              }else{
                console.log('Error in fetching requets by id')
                res.send({ status: 0, message: "Error in fetching requets by id from mirrored facility" })
              }
        }
        if(id && id != 'undefined'){
            let orderData = await CustomerOrder.getCustomerOrderRequestId(id)
            let order_id = orderData.id

            if(orderData.syncWithQuickbooks == 1 && orderData.tax_amount == 0){  
                const taxAmount = await fetchTaxAmountFromEstimateById(orderData.estimate_id, orderData.installation_acceptance);
                console.log('taxAmount 123', taxAmount)
                if(taxAmount > 0){ //SkyFrond
                    
                    const updateData ={
                        tax_amount: taxAmount,
                        total: parseFloat(orderData.total + taxAmount),
                        grandTotal: parseFloat(orderData.grandTotal + taxAmount),
                    }
                    await CustomerOrder.updateCustomerOrder(order_id, updateData);
                    orderData.tax_amount = updateData.tax_amount;
                    orderData.total = updateData.total;
                    orderData.grandTotal = updateData.grandTotal;
                }
            }

            if (!empty(order_id)) {
                // let results =[]
                // let jobCostResults =[]
                let errors = [] // Declare errors array to handle mirror data retrieval errors
                // // if(orderData.project_category == 12 && (orderData.isReview !== 2 && orderData.isReview !== 1)){
                // //     results =[]
                // //     jobCostResults = []
                // // }else{
                //     results =await CustomerOrderProduct.getCustomerOrderProductsbyId(order_id)
                //     jobCostResults = await CustomerOrderProduct.getJobCostProductsbyId(order_id);
                // // }

                // // let results = await CustomerOrderProduct.getCustomerOrderProductsbyId(order_id)
                // let resultsLocation = await CustomerOrderProduct.getCustomerOrderProductsbyIdWithLocation(order_id)
                // // let jobCostResults = await CustomerOrderProduct.getJobCostProductsbyId(order_id);
                // let jobcostService = await Requests.getRequestServices(orderData?.request_id, false, false, false, orderData?.project_category);
                let [results, jobCostResults, resultsLocation, jobcostService] = await Promise.all([
                    CustomerOrderProduct.getCustomerOrderProductsbyId(order_id),
                    CustomerOrderProduct.getJobCostProductsbyId(order_id),
                    CustomerOrderProduct.getCustomerOrderProductsbyIdWithLocation(order_id),
                    (orderData?.is_split_order == 1 && orderData?.project_category !== 15)
                        ? Requests.getSplitRequestServices(orderData?.request_id, false, false, false, orderData?.project_category)
                        : Requests.getRequestServices(orderData?.request_id, false, false, false, orderData?.project_category)
                ]);

                if (jobCostResults && jobCostResults.length > 0) {
                    jobCostResults = jobCostResults.map(mat => {
                      // Parse values or default to 0
                      const unitPrice = Number(mat.unit_price || 0);
                      const total = Number(mat.total || 0);
                      const materialMarkupPercentage = Number(mat.material_markup_percentage || 0);
                      const finalUnitPrice = Number(mat.unit_price || 0);
                      const finalTotalPrice = Number(mat.total || 0);
                    //   const finalUnitPrice = unitPrice + (unitPrice * materialMarkupPercentage / 100);
                    //   const finalTotalPrice = total + (total * materialMarkupPercentage / 100);
                      return {
                        ...mat,
                        oldUnitPrice:unitPrice,
                        oldTotal:total,
                        unit_price: parseFloat(finalUnitPrice.toFixed(2)),
                        total: parseFloat(finalTotalPrice.toFixed(2)), 
                        new_unit_price: parseFloat(finalUnitPrice.toFixed(2)),
                        new_total: parseFloat(finalTotalPrice.toFixed(2)), 
                      };
                    });
                  }
                  
                if (jobcostService && jobcostService.length > 0) {
                    jobcostService = jobcostService?.map(service => {
                      console.log('service123', service)
                    if(orderData?.project_category == 13){
                        service.service_original_cost = service.unit_cost
                        service.originalMarkup = service.markup
                        }
                    let totalCost = parseFloat(service.service_original_cost || 0);
                    if(orderData?.project_category ==12 && orderData?.is_split_order == 1 && (service.facility_id != FACILITY_ID && service.facility_id != null)){
                        service.service_original_cost = parseFloat(service.unit_cost || 0);
                        totalCost = parseFloat(service.unit_cost || 0);
                        service.quantity = parseFloat(service.jobcost_quantity || 0) || parseFloat(service.quantity || 0);
                    }
                    //   const jobcostQuantity = parseFloat(service.jobcost_quantity || 0);
                      const jobcostQuantity = (orderData?.project_category == 12 && service?.fixed_service_cost !== 1) ? parseFloat(service.jobcost_quantity || 0) : parseFloat(service.quantity || 0);
                      let totalServiceCost = totalCost * jobcostQuantity;
                  
                    //   if(orderData?.project_category ==12 && service.labour_cost_service_id !== 10){  uncomment if needed
                        if(orderData?.project_category ==12 && (service.facility_id == FACILITY_ID || service.facility_id == null)){
                        // service.quantity = parseFloat(service.jobcost_quantity).toFixed(2)
                        service.total_cost =totalServiceCost // parseFloat(service.jobcost_total_cost)
                        service.quantity =jobcostQuantity 
                        service.qty =jobcostQuantity 
                        // totalServiceCost =parseFloat(Number(service.jobcost_total_cost))
                     }

                      return {
                        ...service,
                        total_service_cost: totalServiceCost.toFixed(2),
                      };
                    });
                }


                let jobcostTotal = 0
                let jobcostServiceTotal = 0
                if(jobCostResults && jobCostResults?.length > 0){
                  jobcostTotal = jobCostResults?.reduce((sum, product) => {
                    return sum + (product.total || 0);
                  }, 0);
                }
                if(jobcostService && jobcostService?.length > 0){
                    jobcostServiceTotal = jobcostService?.filter(it=>it.total_cost == 0)?.reduce((sum, product) => {
                    return sum + (parseFloat(product.total_service_cost) || 0);
                  }, 0);
                }
                const total = orderData?.total || 0;
                const extraDiscount = parseFloat(orderData?.extra_discount) || 0;
                const taxAmount = parseFloat(orderData?.tax_amount) || 0;

                let grandTotal = (total + (jobcostTotal || 0) + (jobcostServiceTotal || 0));
                let additionalAmount = ((jobcostTotal || 0) + (jobcostServiceTotal || 0));
                let updateOrderData = {
                    grandTotal : parseFloat(grandTotal).toFixed(2),
                    addl_amount : parseFloat(additionalAmount).toFixed(2),
                }
                
                let updatedOrderId = await CustomerOrder.updateCustomerOrder(order_id, updateOrderData);
                  
                const fetchedNoteData = await Installation.fetchNotesByRequestId(orderData.requestId)
                if (!empty(results)) {
                    for (const product of results) {
                        product.install_cost = (product?.material == 1 || product?.rfp == 1) ? null : product.install_cost
                        let services = await Product.getServiceByProduct(product.product_id);
                        let resultArray = [];
                        let materials = await Product.getMaterialByProduct(product.product_id)
                        // for (let serviceData of services) {
                        //     let subResult = await Requests.getRequestServices(orderData?.request_id, serviceData.id,product.product_id,product.product_index);
                            
                        //     if (!empty(subResult)) {
                        //         resultArray.push(subResult);
                        //     }
                        // }
                        product.services = resultArray.flatMap(service => service);
                        product.materials = materials || []
                        //////////////FOR SPLIT CALCULATION
                        if(orderData?.is_split_order == 1 && product.facility_id != FACILITY_ID && product?.material != 1 && product?.rfp != 1 && orderData?.project_category !== 15){
                            let amountWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) * (Number(product.split_percentage) / 100)).toFixed(2)
                            let expectedCostWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithOutgoingPercentage)).toFixed(2)
                            console.log('expectedCostWithOutgoingPercentage 1', amountWithOutgoingPercentage)
                            console.log('expectedCostWithOutgoingPercentage 2', expectedCostWithOutgoingPercentage)
                            let amountWithIncomingPercentage = parseFloat(Number(expectedCostWithOutgoingPercentage) * (Number(product.incoming_split_percentage) / 100)).toFixed(2)
                            let expectedCostWithIncomingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithIncomingPercentage)).toFixed(2)
                            let totalAmount = parseFloat(Number(expectedCostWithOutgoingPercentage) + Number(amountWithIncomingPercentage)).toFixed(2)
                            console.log('expectedCostWithOutgoingPercentage 3', amountWithIncomingPercentage)
                            console.log('expectedCostWithOutgoingPercentage 4', totalAmount)
                            console.log('expectedCostWithOutgoingPercentage 5', product)
                            product.actual_retail_price = totalAmount
                            product.wholesale_price = Number(expectedCostWithOutgoingPercentage)
                        }else if(orderData?.is_split_order == 1 && (orderData?.for_parent_facility == 1 || orderData?.for_parent_facility == 2) && product?.material != 1 && product?.rfp != 1 ){
                            let amountWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) * (Number(product.split_percentage) / 100)).toFixed(2)
                            let expectedCostWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithOutgoingPercentage)).toFixed(2)
                            product.actual_retail_price = expectedCostWithOutgoingPercentage
                        }
                        if(orderData?.project_category == 13 && (product.rfp != 1 && product.material != 1)){
                            const expectedCost = parseFloat(parseFloat(product.expected_cost || 0).toFixed(2))
                            const installCost = parseFloat(parseFloat(product.install_cost || 0).toFixed(2))
                            // If install_cost is available, add it to expected_cost
                            const nochargeRetailprice = installCost > 0 ? expectedCost + installCost : expectedCost
                            console.log('nochargeRetailprice---', nochargeRetailprice)
                            product.actual_retail_price = expectedCost
                            product.product_retail_price = nochargeRetailprice
                            product.product_total = nochargeRetailprice * (product.location_quantity || 1)
                        }else if(orderData?.project_category == 13 && (product.rfp == 1 || product.material == 1)){
                            product.product_retail_price = product.product_price
                            product.actual_retail_price = product.product_price
                            product.product_total = product.product_price * (product.location_quantity || 1)
                        }else if(product?.material != 1 && product?.rfp != 1){
                            product.product_retail_price =(product.install_cost || (orderData?.is_split_order == 1 && product.facility_id != FACILITY_ID)) ?  product.product_retail_price : product.actual_retail_price || product.product_retail_price
                            product.product_total = ((product.install_cost || (orderData?.is_split_order == 1 && product.facility_id != FACILITY_ID)) ?  product.product_retail_price : product.actual_retail_price || product.product_retail_price ) * (product.location_quantity || 1)
                            product.actual_retail_price =product?.materialInvId ? (product?.unit_cost ): product?.actual_retail_price
                        }
                        //////////////FOR SPLIT CALCULATION
                        // if(orderData?.is_split_order == 1 && product.facility_id != FACILITY_ID && product?.material != 1 && product?.rfp != 1){
                        //     let amountWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) * (Number(product.split_percentage) / 100)).toFixed(2)
                        //     let expectedCostWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithOutgoingPercentage)).toFixed(2)
                        //     console.log('expectedCostWithOutgoingPercentage 1', amountWithOutgoingPercentage)
                        //     console.log('expectedCostWithOutgoingPercentage 2', expectedCostWithOutgoingPercentage)
                        //     let amountWithIncomingPercentage = parseFloat(Number(expectedCostWithOutgoingPercentage) * (Number(product.incoming_split_percentage) / 100)).toFixed(2)
                        //     let expectedCostWithIncomingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithIncomingPercentage)).toFixed(2)
                        //     let totalAmount = parseFloat(Number(expectedCostWithOutgoingPercentage) + Number(amountWithIncomingPercentage)).toFixed(2)
                        //     console.log('expectedCostWithOutgoingPercentage 3', amountWithIncomingPercentage)
                        //     console.log('expectedCostWithOutgoingPercentage 4', totalAmount)
                        //     console.log('expectedCostWithOutgoingPercentage 5', product)
                        //     product.actual_retail_price = totalAmount
                        //     product.wholesale_price = Number(expectedCostWithOutgoingPercentage)
                        // }else if(orderData?.is_split_order == 1 && orderData?.for_parent_facility == 1 && product?.material != 1 && product?.rfp != 1 ){
                        //     let amountWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) * (Number(product.split_percentage) / 100)).toFixed(2)
                        //     let expectedCostWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithOutgoingPercentage)).toFixed(2)
                        //     product.actual_retail_price = expectedCostWithOutgoingPercentage
                        // }
                        // if(product.inhouse == 0){//in customer order product in unit_price we are aving the actual_retail_price || retail_price
                            
                        if(product?.material !== 1 && product?.rfp != 1){
                            let installCost = product?.install_cost || 0
                            let installQty = product?.install_qty || 1
                            let installTotal = installCost * installQty
                            product.install_total = installTotal
                            product.actual_retail_price  =product?.unit_cost 
                            product.product_retail_price =product?.unit_cost //previos one after commenting this the marketing ADj calculation issue was fixed now we have seperate qty for install cost  + (product?.install_cost || 0) 
                            product.product_total =product?.unit_cost 
                        }
                       
                      
                        // if(product?.materialInvId == null){
                        //     product.actual_retail_price =product?.actual_retail_price + (product?.adj_value_type == 1 ? Number(product?.adjustment || 0) : -Number(product?.adjustment || 0))
                        //     product.product_total =product?.product_total + (product?.adj_value_type == 1 ? Number(product?.adjustment || 0) : -Number(product?.adjustment || 0))
                        // }
                        //     if(!product?.install_cost && product?.materialInvId == null){
                        //         product.product_retail_price =product?.product_retail_price + (product?.adj_value_type == 1 ? Number(product?.adjustment || 0) : -Number(product?.adjustment || 0))
                        //     }else{
                        //         product.product_retail_price =product?.actual_retail_price  + product?.install_cost

                        //     }
                        // if(product?.material !== 1 && product?.rfp != 1 && orderData?.for_parent_facility == 2){
                        //     product.actual_retail_price  =product?.unit_cost 
                        //     product.product_retail_price =product?.unit_cost + (product?.install_cost || 0) 
                        //     product.product_total = product?.unit_cost + (product?.install_cost || 0)
                        // }
                        if(orderData?.is_split_order == 1 && orderData?.requestId && product?.material != 1 && product?.rfp != 1 && orderData?.project_category !== 15){
                            const requestId = orderData?.requestId;
                            const originFacilityId = orderData?.origin_facility_id;
                            const facilityTypes = (orderData?.facility_type || "")
                            .split(",")
                            .map(v => v.trim())
                            .filter(v => v !== ""); // Remove empty strings
                            const targettedFacilityId = facilityTypes.filter(id => id !== String(FACILITY_ID));

                            if (targettedFacilityId && targettedFacilityId.length > 0) {
                                for (const facilityId of targettedFacilityId) {
                                    try {
                                        console.log(`Getting mirror data from facility ID: ${facilityId}`);

                                        // Get mirror data from the target facility
                                        const result = await SplitManagementModel.getSplitMirrorData(
                                            requestId,
                                            facilityId
                                        );

                                        if (result.success && result.data) {
                                            console.log(`Mirror data retrieved successfully from facility ${facilityId}:`, result.data);

                                            // Check if the facility matches the product facility
                                            if (result.data.facility_id == product.facility_id) {
                                                // Add the three fields to the product
                                                product.split_status = result.data.status;
                                                product.split_mirror_status = result.data.split_mirror_status;
                                                product.received_status = result.data.received_status;
                                                product.minPaymentStatus = result.data?.min_payment_status;
                                                if(result?.data?.received_status == 2 && result?.data?.status == 4 && result?.data?.request_id){
                                                    const request = await Request.getAllRequests(result?.data?.request_id, userId, userType)
                                                    const reqData = request?.data?.[0]
                                                    if(reqData){
                                                        product.installation_acceptance = reqData?.installation_acceptance;
                                                        product.allInstallation_completed = reqData?.allInstallationCompleted;
                                                        product.installation_status = reqData?.installationStatus;
                                                        product.installation_complete_status = reqData?.installationCompleteStatus;
                                                        product.minPaymentStatus = reqData?.min_payment_status;
                                                        product.project_status = reqData?.proj_status
                                                    }
                                                    console.log('requesttttt', request)
                                                }
                                                console.log(`Added mirror data to product for facility ${facilityId}`);
                                            }

                                            // Don't push to results array - it contains products, not results
                                        } else {
                                            console.error(`Failed to get mirror data from facility ${facilityId}:`, result?.message);
                                            errors.push({
                                                facilityId: facilityId,
                                                success: false,
                                                message: result?.message
                                            });
                                        }
                                    } catch (facilityError) {
                                        console.error(`Error processing facility ${facilityId}:`, facilityError);
                                        errors.push({
                                            facilityId: facilityId,
                                            success: false,
                                            message: 'Error processing facility: ' + facilityError?.message
                                        });
                                    }
                                }
                            }
                        }
                    }
                    orderData['cust_product'] = results;
                } else {
                    orderData['cust_product'] = [];
                }
                if (!empty(resultsLocation)) {
                    orderData['cust_product_location'] = resultsLocation;
                } else {
                    orderData['cust_product_location'] = [];
                }
                if (!empty(jobCostResults)) {
                    orderData['jobcost_product'] = jobCostResults;
                } else {
                    orderData['jobcost_product'] = [];
                }
                if (!empty(jobcostService)) {
                    orderData['jobcost_service'] = jobcostService;
                } else {
                    orderData['jobcost_service'] = [];
                }
                if (!empty(fetchedNoteData)) {
                    orderData['note_data'] = fetchedNoteData;
                } else {
                    orderData['note_data'] = [];
                }
                // Fetch sign agreements based on the request_id
                if (orderData.request_id) {
                    const signAgreements = await signAgreement.getSignAgreementsByRequestId(orderData.request_id);
                    orderData['sign_agreements'] = signAgreements;
                } else {
                    orderData['sign_agreements'] = [];
                }
                let community = await Community.getAllCommunitiesByClient(false,orderData['customer_id'],userType,From,teamId);
                res.send({ status: 1, data: orderData,community, message: "Data fetched successfully" });
            } else {
                res.send({ status: 0, message: "Error fetching data" })
            }
        }else{
            res.send({ status: 0, message: "id not available" })
        }
    } catch (error) {
        console.log(error)
        res.send({ staus: 0, message: 'Internal server error' })
    }
}
// const customerOrderProductById = async (req, res) => {
//     try {
//         const { isMirrored = false, targetFacilityId = null, userType = null, userId = null, From = null, teamId = null} = req.body || {};
//         let { id } = req.params;
//         if(isMirrored && targetFacilityId && id ){
//             const targetFacility = filteredSignwiseInstalations.find(
//                 f => f.id === Number(targetFacilityId)
//               );
//               console.log('targetFacility.url 1', targetFacility.url , id)
//               if (!targetFacility?.url) return null;
//               console.log('targetFacility.url 2', targetFacility.url, id)
//               const projectResponse = await axios.post(
//                 `${targetFacility.url}get-customer-order-product/${id}`);
//               if(projectResponse?.data){
//                 return res.send(projectResponse.data)
//               }else{
//                 console.log('Error in fetching requets by id')
//                 res.send({ status: 0, message: "Error in fetching requets by id from mirrored facility" })
//               }
//         }
//         if(id && id != 'undefined'){
//             let orderData = await CustomerOrder.getCustomerOrderRequestId(id)
//             let order_id = orderData.id

//             if (!empty(order_id)) {
//                 let results =[]
//                 let jobCostResults =[]
//                 let errors = [] // Declare errors array to handle mirror data retrieval errors
//                 // if(orderData.project_category == 12 && (orderData.isReview !== 2 && orderData.isReview !== 1)){
//                 //     results =[]
//                 //     jobCostResults = []
//                 // }else{
//                     results =await CustomerOrderProduct.getCustomerOrderProductsbyId(order_id)
//                     jobCostResults = await CustomerOrderProduct.getJobCostProductsbyId(order_id);
//                 // }

//                 // let results = await CustomerOrderProduct.getCustomerOrderProductsbyId(order_id)
//                 let resultsLocation = await CustomerOrderProduct.getCustomerOrderProductsbyIdWithLocation(order_id)
//                 // let jobCostResults = await CustomerOrderProduct.getJobCostProductsbyId(order_id);
//                 let jobcostService = await Requests.getRequestServices(orderData?.request_id, false, false, false, orderData?.project_category);

//                 if (jobCostResults && jobCostResults.length > 0) {
//                     jobCostResults = jobCostResults.map(mat => {
//                       // Parse values or default to 0
//                       const unitPrice = Number(mat.unit_price || 0);
//                       const total = Number(mat.total || 0);
//                       const materialMarkupPercentage = Number(mat.material_markup_percentage || 0);
//                       const finalUnitPrice = Number(mat.unit_price || 0);
//                       const finalTotalPrice = Number(mat.total || 0);
//                     //   const finalUnitPrice = unitPrice + (unitPrice * materialMarkupPercentage / 100);
//                     //   const finalTotalPrice = total + (total * materialMarkupPercentage / 100);
//                       return {
//                         ...mat,
//                         oldUnitPrice:unitPrice,
//                         oldTotal:total,
//                         unit_price: parseFloat(finalUnitPrice.toFixed(2)),
//                         total: parseFloat(finalTotalPrice.toFixed(2)), 
//                         new_unit_price: parseFloat(finalUnitPrice.toFixed(2)),
//                         new_total: parseFloat(finalTotalPrice.toFixed(2)), 
//                       };
//                     });
//                   }
                  
//                 if (jobcostService && jobcostService.length > 0) {
//                     jobcostService = jobcostService?.map(service => {
//                     if(orderData?.project_category == 13){
//                         service.service_original_cost = service.unit_cost
//                         service.originalMarkup = service.markup
//                         }
//                       const totalCost = parseFloat(service.service_original_cost || 0);
//                     //   const jobcostQuantity = parseFloat(service.jobcost_quantity || 0);
//                       const jobcostQuantity = (orderData?.project_category == 12 && service?.fixed_service_cost !== 1) ? parseFloat(service.jobcost_quantity || 0) : parseFloat(service.quantity || 0);
//                       let totalServiceCost = totalCost * jobcostQuantity;
                  
//                     //   if(orderData?.project_category ==12 && service.labour_cost_service_id !== 10){  uncomment if needed
//                         if(orderData?.project_category ==12){
//                         // service.quantity = parseFloat(service.jobcost_quantity).toFixed(2)
//                         service.total_cost =totalServiceCost // parseFloat(service.jobcost_total_cost)
//                         service.quantity =jobcostQuantity 
//                         service.qty =jobcostQuantity 
//                         // totalServiceCost =parseFloat(Number(service.jobcost_total_cost))
//                      }

//                       return {
//                         ...service,
//                         total_service_cost: totalServiceCost.toFixed(2),
//                       };
//                     });
//                 }


//                 let jobcostTotal = 0
//                 let jobcostServiceTotal = 0
//                 if(jobCostResults && jobCostResults?.length > 0){
//                   jobcostTotal = jobCostResults?.reduce((sum, product) => {
//                     return sum + (product.total || 0);
//                   }, 0);
//                 }
//                 if(jobcostService && jobcostService?.length > 0){
//                     jobcostServiceTotal = jobcostService?.filter(it=>it.total_cost == 0)?.reduce((sum, product) => {
//                     return sum + (parseFloat(product.total_service_cost) || 0);
//                   }, 0);
//                 }
//                 const total = orderData?.total || 0;
//                 const extraDiscount = parseFloat(orderData?.extra_discount) || 0;
//                 const taxAmount = parseFloat(orderData?.tax_amount) || 0;

//                 let grandTotal = (total + (jobcostTotal || 0) + (jobcostServiceTotal || 0));
//                 let additionalAmount = ((jobcostTotal || 0) + (jobcostServiceTotal || 0));
//                 let updateOrderData = {
//                     grandTotal : parseFloat(grandTotal).toFixed(2),
//                     addl_amount : parseFloat(additionalAmount).toFixed(2),
//                 }
                
//                 let updatedOrderId = await CustomerOrder.updateCustomerOrder(order_id, updateOrderData);
                  
//                 const fetchedNoteData = await Installation.fetchNotesByRequestId(orderData.requestId)
//                 if (!empty(results)) {
//                     for (const product of results) {
//                         product.install_cost = (product?.material == 1 || product?.rfp == 1) ? null : product.install_cost
//                         let services = await Product.getServiceByProduct(product.product_id);
//                         let resultArray = [];
//                         let materials = await Product.getMaterialByProduct(product.product_id)
//                         // for (let serviceData of services) {
//                         //     let subResult = await Requests.getRequestServices(orderData?.request_id, serviceData.id,product.product_id,product.product_index);
                            
//                         //     if (!empty(subResult)) {
//                         //         resultArray.push(subResult);
//                         //     }
//                         // }
//                         product.services = resultArray.flatMap(service => service);
//                         product.materials = materials || []
//                         //////////////FOR SPLIT CALCULATION
//                         if(orderData?.is_split_order == 1 && product.facility_id != FACILITY_ID && product?.material != 1 && product?.rfp != 1 && orderData?.project_category !== 15){
//                             let amountWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) * (Number(product.split_percentage) / 100)).toFixed(2)
//                             let expectedCostWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithOutgoingPercentage)).toFixed(2)
//                             console.log('expectedCostWithOutgoingPercentage 1', amountWithOutgoingPercentage)
//                             console.log('expectedCostWithOutgoingPercentage 2', expectedCostWithOutgoingPercentage)
//                             let amountWithIncomingPercentage = parseFloat(Number(expectedCostWithOutgoingPercentage) * (Number(product.incoming_split_percentage) / 100)).toFixed(2)
//                             let expectedCostWithIncomingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithIncomingPercentage)).toFixed(2)
//                             let totalAmount = parseFloat(Number(expectedCostWithOutgoingPercentage) + Number(amountWithIncomingPercentage)).toFixed(2)
//                             console.log('expectedCostWithOutgoingPercentage 3', amountWithIncomingPercentage)
//                             console.log('expectedCostWithOutgoingPercentage 4', totalAmount)
//                             console.log('expectedCostWithOutgoingPercentage 5', product)
//                             product.actual_retail_price = totalAmount
//                             product.wholesale_price = Number(expectedCostWithOutgoingPercentage)
//                         }else if(orderData?.is_split_order == 1 && (orderData?.for_parent_facility == 1 || orderData?.for_parent_facility == 2) && product?.material != 1 && product?.rfp != 1 ){
//                             let amountWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) * (Number(product.split_percentage) / 100)).toFixed(2)
//                             let expectedCostWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithOutgoingPercentage)).toFixed(2)
//                             product.actual_retail_price = expectedCostWithOutgoingPercentage
//                         }
//                         if(orderData?.project_category == 13 && (product.rfp != 1 && product.material != 1)){
//                             const expectedCost = parseFloat(parseFloat(product.expected_cost || 0).toFixed(2))
//                             const installCost = parseFloat(parseFloat(product.install_cost || 0).toFixed(2))
//                             // If install_cost is available, add it to expected_cost
//                             const nochargeRetailprice = installCost > 0 ? expectedCost + installCost : expectedCost
//                             console.log('nochargeRetailprice---', nochargeRetailprice)
//                             product.actual_retail_price = expectedCost
//                             product.product_retail_price = nochargeRetailprice
//                             product.product_total = nochargeRetailprice * (product.location_quantity || 1)
//                         }else if(orderData?.project_category == 13 && (product.rfp == 1 || product.material == 1)){
//                             product.product_retail_price = product.product_price
//                             product.actual_retail_price = product.product_price
//                             product.product_total = product.product_price * (product.location_quantity || 1)
//                         }else if(product?.material != 1 && product?.rfp != 1){
//                             product.product_retail_price =(product.install_cost || (orderData?.is_split_order == 1 && product.facility_id != FACILITY_ID)) ?  product.product_retail_price : product.actual_retail_price || product.product_retail_price
//                             product.product_total = ((product.install_cost || (orderData?.is_split_order == 1 && product.facility_id != FACILITY_ID)) ?  product.product_retail_price : product.actual_retail_price || product.product_retail_price ) * (product.location_quantity || 1)
//                             product.actual_retail_price =product?.materialInvId ? (product?.unit_cost ): product?.actual_retail_price
//                         }
//                         //////////////FOR SPLIT CALCULATION
//                         // if(orderData?.is_split_order == 1 && product.facility_id != FACILITY_ID && product?.material != 1 && product?.rfp != 1){
//                         //     let amountWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) * (Number(product.split_percentage) / 100)).toFixed(2)
//                         //     let expectedCostWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithOutgoingPercentage)).toFixed(2)
//                         //     console.log('expectedCostWithOutgoingPercentage 1', amountWithOutgoingPercentage)
//                         //     console.log('expectedCostWithOutgoingPercentage 2', expectedCostWithOutgoingPercentage)
//                         //     let amountWithIncomingPercentage = parseFloat(Number(expectedCostWithOutgoingPercentage) * (Number(product.incoming_split_percentage) / 100)).toFixed(2)
//                         //     let expectedCostWithIncomingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithIncomingPercentage)).toFixed(2)
//                         //     let totalAmount = parseFloat(Number(expectedCostWithOutgoingPercentage) + Number(amountWithIncomingPercentage)).toFixed(2)
//                         //     console.log('expectedCostWithOutgoingPercentage 3', amountWithIncomingPercentage)
//                         //     console.log('expectedCostWithOutgoingPercentage 4', totalAmount)
//                         //     console.log('expectedCostWithOutgoingPercentage 5', product)
//                         //     product.actual_retail_price = totalAmount
//                         //     product.wholesale_price = Number(expectedCostWithOutgoingPercentage)
//                         // }else if(orderData?.is_split_order == 1 && orderData?.for_parent_facility == 1 && product?.material != 1 && product?.rfp != 1 ){
//                         //     let amountWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) * (Number(product.split_percentage) / 100)).toFixed(2)
//                         //     let expectedCostWithOutgoingPercentage = parseFloat(Number(product.expected_formula_price) + Number(amountWithOutgoingPercentage)).toFixed(2)
//                         //     product.actual_retail_price = expectedCostWithOutgoingPercentage
//                         // }
//                         // if(product.inhouse == 0){//in customer order product in unit_price we are aving the actual_retail_price || retail_price
                            
//                         if(product?.material !== 1 && product?.rfp != 1){
//                             let installCost = product?.install_cost || 0
//                             let installQty = product?.install_qty || 1
//                             let installTotal = installCost * installQty
//                             product.install_total = installTotal
//                             product.actual_retail_price  =product?.unit_cost 
//                             product.product_retail_price =product?.unit_cost //previos one after commenting this the marketing ADj calculation issue was fixed now we have seperate qty for install cost  + (product?.install_cost || 0) 
//                             product.product_total =product?.unit_cost 
//                         }
                       
                      
//                         // if(product?.materialInvId == null){
//                         //     product.actual_retail_price =product?.actual_retail_price + (product?.adj_value_type == 1 ? Number(product?.adjustment || 0) : -Number(product?.adjustment || 0))
//                         //     product.product_total =product?.product_total + (product?.adj_value_type == 1 ? Number(product?.adjustment || 0) : -Number(product?.adjustment || 0))
//                         // }
//                         //     if(!product?.install_cost && product?.materialInvId == null){
//                         //         product.product_retail_price =product?.product_retail_price + (product?.adj_value_type == 1 ? Number(product?.adjustment || 0) : -Number(product?.adjustment || 0))
//                         //     }else{
//                         //         product.product_retail_price =product?.actual_retail_price  + product?.install_cost

//                         //     }
//                         // if(product?.material !== 1 && product?.rfp != 1 && orderData?.for_parent_facility == 2){
//                         //     product.actual_retail_price  =product?.unit_cost 
//                         //     product.product_retail_price =product?.unit_cost + (product?.install_cost || 0) 
//                         //     product.product_total = product?.unit_cost + (product?.install_cost || 0)
//                         // }
//                         if(orderData?.is_split_order == 1 && orderData?.requestId && product?.material != 1 && product?.rfp != 1 && orderData?.project_category !== 15){
//                             const requestId = orderData?.requestId;
//                             const originFacilityId = orderData?.origin_facility_id;
//                             const facilityTypes = (orderData?.facility_type || "")
//                             .split(",")
//                             .map(v => v.trim())
//                             .filter(v => v !== ""); // Remove empty strings
//                             const targettedFacilityId = facilityTypes.filter(id => id !== String(FACILITY_ID));

//                             if (targettedFacilityId && targettedFacilityId.length > 0) {
//                                 for (const facilityId of targettedFacilityId) {
//                                     try {
//                                         console.log(`Getting mirror data from facility ID: ${facilityId}`);

//                                         // Get mirror data from the target facility
//                                         const result = await SplitManagementModel.getSplitMirrorData(
//                                             requestId,
//                                             facilityId
//                                         );

//                                         if (result.success && result.data) {
//                                             console.log(`Mirror data retrieved successfully from facility ${facilityId}:`, result.data);

//                                             // Check if the facility matches the product facility
//                                             if (result.data.facility_id == product.facility_id) {
//                                                 // Add the three fields to the product
//                                                 product.split_status = result.data.status;
//                                                 product.split_mirror_status = result.data.split_mirror_status;
//                                                 product.received_status = result.data.received_status;
//                                                 product.minPaymentStatus = result.data?.min_payment_status;
//                                                 if(result?.data?.received_status == 2 && result?.data?.status == 4 && result?.data?.request_id){
//                                                     const request = await Request.getAllRequests(result?.data?.request_id, userId, userType)
//                                                     const reqData = request?.data?.[0]
//                                                     if(reqData){
//                                                         product.installation_acceptance = reqData?.installation_acceptance;
//                                                         product.allInstallation_completed = reqData?.allInstallationCompleted;
//                                                         product.installation_status = reqData?.installationStatus;
//                                                         product.installation_complete_status = reqData?.installationCompleteStatus;
//                                                         product.minPaymentStatus = reqData?.min_payment_status;
//                                                         product.project_status = reqData?.proj_status
//                                                     }
//                                                     console.log('requesttttt', request)
//                                                 }
//                                                 console.log(`Added mirror data to product for facility ${facilityId}`);
//                                             }

//                                             // Don't push to results array - it contains products, not results
//                                         } else {
//                                             console.error(`Failed to get mirror data from facility ${facilityId}:`, result?.message);
//                                             errors.push({
//                                                 facilityId: facilityId,
//                                                 success: false,
//                                                 message: result?.message
//                                             });
//                                         }
//                                     } catch (facilityError) {
//                                         console.error(`Error processing facility ${facilityId}:`, facilityError);
//                                         errors.push({
//                                             facilityId: facilityId,
//                                             success: false,
//                                             message: 'Error processing facility: ' + facilityError?.message
//                                         });
//                                     }
//                                 }
//                             }
//                         }
//                     }
//                     orderData['cust_product'] = results;
//                 } else {
//                     orderData['cust_product'] = [];
//                 }
//                 if (!empty(resultsLocation)) {
//                     orderData['cust_product_location'] = resultsLocation;
//                 } else {
//                     orderData['cust_product_location'] = [];
//                 }
//                 if (!empty(jobCostResults)) {
//                     orderData['jobcost_product'] = jobCostResults;
//                 } else {
//                     orderData['jobcost_product'] = [];
//                 }
//                 if (!empty(jobcostService)) {
//                     orderData['jobcost_service'] = jobcostService;
//                 } else {
//                     orderData['jobcost_service'] = [];
//                 }
//                 if (!empty(fetchedNoteData)) {
//                     orderData['note_data'] = fetchedNoteData;
//                 } else {
//                     orderData['note_data'] = [];
//                 }
//                 let community = await Community.getAllCommunitiesByClient(false,orderData['customer_id'],userType,From,teamId);
//                 res.send({ status: 1, data: orderData,community, message: "Data fetched successfully" });
//             } else {
//                 res.send({ status: 0, message: "Error fetching data" })
//             }
//         }else{
//             res.send({ status: 0, message: "id not available" })
//         }
//     } catch (error) {
//         console.log(error)
//         res.send({ staus: 0, message: 'Internal server error' })
//     }
// }

module.exports = {
    customerOrderProductById,
}