const sequelize = require("../config/dbconnection");
const { empty, arrayDiffAssoc, removeNull } = require("../Helpers/Common");
const moment = require("moment");
const Admin = require("../models/admin");
const Onboard = require("../models/onboard");
const OnboardWorkFlowStages = require("../models/onboardWorkFlowStages");
const OnboardWorkFlowDocuments = require("../models/onboardWorkflowDocuments");
const OnboardWorkFlowFields = require("../models/onboardWorkflowFields");
const OnboardWorkFlowQuestionnaires = require("../models/onboardWorkflowQuestionnaires");
const CustomFieldTemplates = require("../models/customFieldTemplate");
const Documents = require("../models/documents");
const QuestionairesTemplates = require("../models/questionairetemplate");
const PartnerTypes = require("../models/partnerType");
const ParrtnerGroup = require("../models/partnerGroup");
const Groups = require("../models/groups");
const Clients = require("../models/client");
const Staffmembers = require("../models/staffmember");
const TeamStages = require('../models/teamStages')
const PartnerStage = require("../models/partnerStage");
const { EmailAddress } = require("@sendgrid/helpers/classes");
const { portalName, BASE_URL, SEND_EMAIL } = require("../constants/constant");
const { activateProfile, onboardTemplate } = require("../constants/emailTemplates");
const sgMail = require("@sendgrid/mail");
const Group = require("../models/groups");
const Team=require("../models/teams")
const Request=require("../models/request")
const nodemailer = require('nodemailer');


const transporter = nodemailer.createTransport({
  host: 'mail.signwisesolutions.com', 
  port: 465, 
  secure: true, 
  auth: {
    user: 'noreply@signwisesolutions.com', 
    pass: 'signwise@2024', 
  },
});

const getAllWorkflows = async (req, res) => {
  try {
    let result = await Onboard.getAllOnboardingWorkflows();
    if (!empty(result)) {
      res.send({
        status: 1,
        result,
        msg: "fetched successfully",
      });
    }
  } catch (error) {
    console.log(error, "Error in fetching all workflows");
  }
};
const getAllProductionWorkflows = async (req, res) => {
  try {
    let result = await Onboard.getAllOnboardsProduction();
    if (!empty(result)) {
      res.send({
        status: 1,
        result,
        msg: "fetched successfully",
      });
    }else{
      res.send({
        status: 0,
        result:[],
        msg: "Data not found",
      });
    }
  } catch (error) {
    console.log(error, "Error in fetching all workflows");
    res.send({
      status: 0,
      result:[],
      msg: "Data not found",
    });
  }
};
const getAllServicesWorkflows = async (req, res) => {
  try {
    let result = await Onboard.getAllOnboardsService();
    if (!empty(result)) {
      res.send({
        status: 1,
        result,
        msg: "fetched successfully",
      });
    }else{
      res.send({
        status: 0,
        result:[],
        msg: "Data not found",
      });
    }
  } catch (error) {
    console.log(error, "Error in fetching all service workflows");
    res.send({
      status: 0,
      result:[],
      msg: "Data not found",
    });
  }
};
const getAllClientFacingWorkflows = async (req, res) => {
  try {
    let result = await Onboard.getAllClientFacingWorkflow();
    
      res.send({
        status: 1,
        result,
        msg: "fetched successfully",
      });
    
   
  } catch (error) {
    console.log(error, "Error in fetching all workflows");
  }
};
const getAllProductWorkflows = async (req, res) => {
  try {
    let result = await Onboard.getAllProductWorkflow();
    
      res.send({
        status: 1,
        result,
        msg: "fetched successfully",
      });
    
   
  } catch (error) {
    console.log(error, "Error in fetching all workflows");
  }
};
const getAllServiceWorkflows = async (req, res) => {
  try {
    let result = await Onboard.getAllServiceWorkflow();
    
      res.send({
        status: 1,
        result,
        msg: "fetched successfully",
      });
    
   
  } catch (error) {
    console.log(error, "Error in fetching all service workflows");
  }
};
const ViewOnboardWorkflow = async (req, res) => {
  try {
    const { id } = req.body;
    let workflow = await Onboard.getWorkFlowbyId(id);
    let stageInProgress = await Onboard.getAllWorkflowStageInProgress(id);

    let teamInProgress = await Onboard.getAllWorkFlowTeamStageInProgress(id);
    let statusofWorkFlow = await Onboard.getAllWorkflowsStageStatus(id);
    let review = []
    for (let stage of statusofWorkFlow) {
      console.log("FFFFFFFFFFFFFFFFFFFF");
      let row = await Onboard.getStagePartners(stage.stage_id)
      console.log("FFFFFFFFFFFFFFFFFFFF0", row);
      if (!empty(row)) {
        review.push(row)
      }
    }
    res.send({
      status: 1,
      msg: "fetched successfully",
      workflow,
      stageInProgress,
      teamInProgress,
      statusofWorkFlow,
      review,
    });
  } catch (error) {
    console.log(error, "Error in fetching  workflows by id");
  }
};
const addWorkFlow = async (req, res) => {
  try {
    const { userId, values, savedStages, stageSubmit,productWorkflow, serviceWorkflow} = req.body;

    let workflow = {};
    let onBoardStages = [];
    let currentDate = Math.round(moment().valueOf() / 1000);
    if (!empty(stageSubmit)) {
      const workflowName = (stageSubmit.name || "").trim();
      if (empty(workflowName)) {
        return res.send({
          status: 0,
          message: "Workflow name is required.",
        });
      }

      const existingWorkflow = await Onboard.isWorkflowNameExists(workflowName);
      if (!empty(existingWorkflow)) {
        return res.send({
          status: 0,
          message: "Workflow name already exists. Please use a different name.",
        });
      }

      workflow["name"] = workflowName;
      workflow["is_default"] = stageSubmit.isDefault;
      workflow["timestamp"] = currentDate;
      workflow["updated_on"] = currentDate;
      workflow["added_by"] = userId;
      workflow["status"] =productWorkflow ? 4 : (serviceWorkflow ? 9 : 1);
      if (!empty(savedStages)) {
        onBoardStages = savedStages;
      } else {
        
        return res.send({
          status: 0,
          msg: "Failed to create workflow!",
        });
      }
      let workflowId = await Onboard.addWorkFlow(workflow);

      let stage = [];
      if (!empty(workflowId)) {
        let i = 1;
        for (let onboardstage of onBoardStages) {

          let stage = {};
          stage["workflow_id"] = workflowId.id;
          stage["name"] = onboardstage["stage_name"];
          stage["stage_type"] = onboardstage["stage_type"].id;
          stage["internal_stage"] =
            onboardstage["stage_type"].session == "internal_stages" ? 1 : 0;
          // stage["flow_type"] = onboardstage["type_of_stage"] == ("Automatic" || "automatic") ? 1 : 2;
          stage["flow_type"] = 1;
          stage["message"] = onboardstage["description"]
            ? onboardstage["description"]
            : "";
          stage["position_order"] = onboardstage["order"]
            ? onboardstage["order"]
            : i++;
          if (!empty(onboardstage["partnerTypes"])) {
            stage["partner_type"] = onboardstage["partnerTypes"].id;
          }
          if (!empty(onboardstage["group_ids"])) {
            stage["group_ids"] = onboardstage["groups"]
              .map((item) => item.id)
              .join(",");
          }
          if (!empty(onboardstage["managers"])) {
            stage["relationship_manager_ids"] = onboardstage["managers"]
              .map((item) => item.id)
              .join(",");
          }
          if (!empty(onboardstage["bank_details"])) {
            stage["bank_form_type"] = onboardstage["bank_details"]
              .map((item) => item.id)
              .join(",");
            // stage["bank_form_type"] = onboardstage["bank_details"].id
          
          }
          if(!empty(onboardstage)){
            stage['skill_ids'] = onboardstage['skills']?.map((item)=>item.id).join(',');
            stage['service_id'] = onboardstage['services']?.id || null;
          }
          stage["timestamp"] = currentDate;
          stage["updated_on"] = currentDate;
          stage["added_by"] = userId;
          stage["status"] = 1;
          console.log("each stage", stage);       
         
          let stageId = await OnboardWorkFlowStages.addStage(stage);

          let stageFieldTemplates = [];
          if (!empty(stageId)) {
            if (!empty(onboardstage["template"])) {
              for (let fieldTemplateId of onboardstage["template"]) {
                let stageFieldTemplates = {};
                stageFieldTemplates["stage_id"] = stageId.id;
                stageFieldTemplates["field_template_id"] = fieldTemplateId.id;
                stageFieldTemplates["timestamp"] = currentDate;
                stageFieldTemplates["updated_on"] = currentDate;
                stageFieldTemplates["added_by"] = userId;
                stageFieldTemplates["status"] = 1;
                let result =
                  await OnboardWorkFlowFields.addOnboardworkFlowFields(
                    stageFieldTemplates
                  );
              }
            }
            ////
            if (!empty(onboardstage["documents"])) {
              for (let requested_document_id of onboardstage["documents"]) {
                let stageRequestDocuments = {};
                stageRequestDocuments["stage_id"] = stageId.id;
                stageRequestDocuments["document_id"] = requested_document_id.id;
                stageRequestDocuments["timestamp"] = currentDate;
                stageRequestDocuments["updated_on"] = currentDate;
                stageRequestDocuments["added_by"] = userId;
                stageRequestDocuments["status"] = 1;
                let result =
                  await OnboardWorkFlowDocuments.addOnboardworkFlowDocuments(
                    stageRequestDocuments
                  );
              }
            }
            ////
            if (!empty(onboardstage["agreements"])) {
              for (let sign_agreement_id of onboardstage["agreements"]) {
                let stageSignAgreements = {};
                stageSignAgreements["stage_id"] = stageId.id;
                stageSignAgreements["document_id"] = sign_agreement_id.id;
                stageSignAgreements["timestamp"] = currentDate;
                stageSignAgreements["updated_on"] = currentDate;
                stageSignAgreements["added_by"] = userId;
                stageSignAgreements["status"] = 1;
                let result =
                  await OnboardWorkFlowDocuments.addOnboardworkFlowDocuments(
                    stageSignAgreements
                  );
              }
            }
            console.log("REEEEEEEERE", onboardstage["questions"]);
            console.log("REEEEEEEERE", onboardstage["questions"]);
            ////
            if (!empty(onboardstage["questions"])) {
              let stage_questionnaires = {};
              for (let questionnaire_id of onboardstage["questions"]) {
                stage_questionnaires["stage_id"] = stageId.id;
                stage_questionnaires["qns_template_id"] = questionnaire_id.id;
                stage_questionnaires["timestamp"] = currentDate;
                stage_questionnaires["updated_on"] = currentDate;
                stage_questionnaires["added_by"] = userId;
                stage_questionnaires["status"] = 1;
                console.log("REEEEEEEERE", questionnaire_id.id);
                console.log("REEEEEEEERE", stage_questionnaires);
                let result =
                  await OnboardWorkFlowQuestionnaires.addOnboardQuestions(
                    stage_questionnaires
                  );
              }
            }
          }
        }
        //// Notifications
        let notificationMsg = productWorkflow
        ? `New Product workflow <strong>. ${workflow["name"]}.</strong> has been created.`
        : (serviceWorkflow ?
          `New Service workflow <strong>. ${workflow["name"]}.</strong> has been created.`
          : `New Onboarding workflow <strong>. ${workflow["name"]}.</strong> has been created.`);
        let notificationUrl = "onbaord";
        if (userId !== 1) {
          Admin.incrementField(userId, "noti_count", 1);
          Admin.addNotification({
            user_id: userId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          });
        }
        let adminId = await Admin.getAllAdminIds();
        for (let eachAdminId of adminId) {
          Admin.incrementField(eachAdminId, "noti_count", 1);
          Admin.addNotification({
            user_id: eachAdminId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          });
        }
        res.send({
          status: 1,
          workflowId,
          message: productWorkflow ? 
          "Product workflow created successfully."
          : (serviceWorkflow ?
            "Service workflow created successfully."
            :
            "Onboard workflow created successfully."),
        });
      } else {
        res.send({
          status: 0,
          message: "Failed to create workflow",
        });
      }
    }
  } catch (error) {
    console.log(error, "error in adding workflow");
  }
};
const editWorkFlow = async (req, res) => {
  try {
    let { workflowId, savedStages, stageSubmit, userId, productWorkflow, serviceWorkflow } = req.body;
  
    let workflow = {};
    let onBoardStages = [];
    let currentDate = Math.round(moment().valueOf() / 1000);
    if (!empty(stageSubmit)) {
      const submittedName = (stageSubmit.name || "").trim();
      const workflowRecord = await Onboard.getWorkFlowbyId(workflowId);
      const existingWorkflowName = !empty(workflowRecord) && workflowRecord[0]
        ? (workflowRecord[0].name || "").trim()
        : "";

      const hasNameChanged =
        submittedName &&
        submittedName.toLowerCase() !== existingWorkflowName.toLowerCase();

      if (hasNameChanged) {
        const existingWorkflow = await Onboard.isWorkflowNameExists(
          submittedName,
          workflowId
        );
        if (!empty(existingWorkflow)) {
          return res.send({
            status: 0,
            message: "Workflow name already exists. Please use a different name.",
          });
        }
      }

      workflow["name"] = submittedName;
      workflow["is_default"] = stageSubmit.isDefault;
      workflow["timestamp"] = currentDate;
      workflow["updated_on"] = currentDate;
      workflow["added_by"] = userId;
      workflow["status"] = productWorkflow ? 4 : (serviceWorkflow ? 9 : 1);
      if (!empty(savedStages)) {
        onBoardStages = savedStages;
      } else {
        console.log("Failed to create  workflow!");
        res.send({
          status: 0,
          msg: "Failed to update workflow!",
        });
      }

      let workflowIdupdate = await Onboard.updateWorkFlow(workflowId, workflow);
      let oldStageids = await Onboard.getstageIdByWorkflowId(workflowId, 1);

      const ACTIONSTAGE=[
        {
            id: 7,
            label: 'Action Stage',
            session: 'onboard_stages',
            type: 'action-stage',
          },
    ]
    const ClientFacing = [
      {
        id: 1,
       
        label: 'Data Collection',
        session: 'onboard_stages',
        type: 'data-collection',
      },
      {
        id: 2,
       
        label: 'Bank Information',
        session: 'onboard_stages',
        type: 'bank-information',
        shot: 'bank',
      },
      {
        id: 3,
       
        label: 'Tax Information',
        session: 'onboard_stages',
        shot: 'tax',
        type: 'tax-information',
      },
      {
        id: 4,
       
        label: 'Portfolio',
        session: 'onboard_stages',
        type: 'portfolio',
        shot: 'previous works',
      },
      {
        id: 5,
      
        label: 'Questionnaire',
        session: 'onboard_stages',
        type: 'questionnaire',
      },
      {
        id: 6,
      
        label: 'Sign Agreement',
        session: 'onboard_stages',
        type: 'sign-agreement',
      },
    ]
   
    const result = onBoardStages.map(stage => {
      console.log("########stage", stage);
      const clientFaceMapping = ClientFacing.find(clientFace => clientFace.id === stage.stage_type);
      
  
      if (clientFaceMapping) {
          const { id, label, session, type, } = clientFaceMapping;
  
          stage.stage_type = {
              id,
              label,
              session,
              type,
              
          };
      }
      if(stage.type_of_stage==1){
        stage.type_of_stage="automatic"
      }
      
        stage.description=stage.description //exit_message
        stage.order= stage.position_order
        // stage["partnerTypes"].id=stage.partner_type 
        if(!empty(stage.field_template_ids)){
          stage.template=stage.field_template_ids.map(id => ({ id }));
        }
        
        if(!empty(stage.bank_form_type)){
        
          stage.bank_details=stage.bank_form_type.map(id => ({ id }));
        }
       if(!empty(stage.requested_document_ids)){
        stage.documents=stage.requested_document_ids.map(id => ({ id }));
       }
     if(!empty(stage.sign_agreement_ids))
        {
          stage.agreements=stage.sign_agreement_ids.map(id => ({ id }));
        }
        if(!empty(stage.questionnaire_ids)){
          stage.questions=stage.questionnaire_ids.map(id => ({ id }));
        }
        if(!empty(stage.name)){
          stage.stage_name=stage.name
        }
        
  
      return stage;
  });
  
  
 console.log('resultresultresultresultresultstage==',result)
      if (!empty(result)) {
        if(!empty(oldStageids)){
          for (let oldStageid of oldStageids) {
            let deleted = await OnboardWorkFlowStages.deleteWorkFlowStage(
              oldStageid.id
            );
          }
      
        }
        
        let i = 1;
       
        for (let onboardstage of result) {
          let stage = {};
          stage["workflow_id"] = workflowId;
          stage["name"] = onboardstage["stage_name"];
          stage["stage_type"] = onboardstage["stage_type"].id;
          stage["internal_stage"] =  (onboardstage["stage_type"].session == "internal_stages") ? 1 : 0;
          stage["flow_type"] =1;
            // onboardstage["type_of_stage"] ==  onboardstage["type_of_stage"] == ("Automatic" || "automatic") ? 1 : 2;
          stage["message"] = onboardstage["description"]
            ? onboardstage["description"]
            : "";
          stage["position_order"] = onboardstage["order"]
            ? onboardstage["order"]
            : i++;
          if (!empty(onboardstage["partnerTypes"])) {
            stage["partner_type"] = onboardstage["partnerTypes"].id;
          }
          if (!empty(onboardstage["group_ids"])) {
            stage["group_ids"] = onboardstage["groups"]
              .map((item) => item.id)
              .join(",");
          }
          if (!empty(onboardstage["managers"])) {
            stage["relationship_manager_ids"] = onboardstage["managers"]
              .map((item) => item.id)
              .join(",");
          }
          if (!empty(onboardstage["bank_details"])) {
            stage["bank_form_type"] = onboardstage["bank_details"]
              .map((item) => item.id)
              .join(",");
          }
          if(!empty(onboardstage)){
            stage['skill_ids'] = onboardstage['skills']?.map((item)=>item.id).join(',')||onboardstage['skill_ids'];
            stage['service_id'] = onboardstage['services']?.id || onboardstage['service_id'] || null;
          }
          stage["timestamp"] = currentDate;
          stage["updated_on"] = currentDate;
          stage["added_by"] = userId;
          stage["status"] = 1;

          console.log("nush****************",stage);
         
          let stageId = await OnboardWorkFlowStages.addStage(stage);
          console.log("nush****************", stageId);
          let stageFieldTemplates = [];
          if (!empty(stageId)) {
            console.log("HIIIIIIIIIIII");
            if (!empty(onboardstage["template"])) {
              for (let fieldTemplateId of onboardstage["template"]) {
                let stageFieldTemplates = {};
                stageFieldTemplates["stage_id"] = stageId.id;
                stageFieldTemplates["field_template_id"] = fieldTemplateId.id;
                stageFieldTemplates["timestamp"] = currentDate;
                stageFieldTemplates["updated_on"] = currentDate;
                stageFieldTemplates["added_by"] = userId;
                stageFieldTemplates["status"] = 1;
                let result =
                  await OnboardWorkFlowFields.addOnboardworkFlowFields(
                    stageFieldTemplates
                  );
              }
            }
            ////
            if (!empty(onboardstage["documents"])) {
              for (let requested_document_id of onboardstage["documents"]) {
                let stageRequestDocuments = {};
                stageRequestDocuments["stage_id"] = stageId.id;
                stageRequestDocuments["document_id"] = requested_document_id.id;
                stageRequestDocuments["timestamp"] = currentDate;
                stageRequestDocuments["updated_on"] = currentDate;
                stageRequestDocuments["added_by"] = userId;
                stageRequestDocuments["status"] = 1;
                let result =
                  await OnboardWorkFlowDocuments.addOnboardworkFlowDocuments(
                    stageRequestDocuments
                  );
              }
            }
            ////
            if (!empty(onboardstage["agreements"])) {
              for (let sign_agreement_id of onboardstage["agreements"]) {
                let stageSignAgreements = {};
                stageSignAgreements["stage_id"] = stageId.id;
                stageSignAgreements["document_id"] = sign_agreement_id.id;
                stageSignAgreements["timestamp"] = currentDate;
                stageSignAgreements["updated_on"] = currentDate;
                stageSignAgreements["added_by"] = userId;
                stageSignAgreements["status"] = 1;
                let result =
                  await OnboardWorkFlowDocuments.addOnboardworkFlowDocuments(
                    stageSignAgreements
                  );
              }
            }
            ////
            console.log("$$$$$$$$$$$$$$$$$$nushhhhhhhhhh", onboardstage["questions"]);
            if (!empty(onboardstage["questions"])) {
              let stage_questionnaires = {};
              for (let questionnaire_id of onboardstage["questions"]) {
                stage_questionnaires["stage_id"] = stageId.id;
                stage_questionnaires["qns_template_id"] = questionnaire_id.id;
                stage_questionnaires["timestamp"] = currentDate;
                stage_questionnaires["updated_on"] = currentDate;
                stage_questionnaires["added_by"] = userId;
                stage_questionnaires["status"] = 1;
                let result =
                  await OnboardWorkFlowQuestionnaires.addOnboardQuestions(
                    stage_questionnaires
                  );
              }
            }
          }
        }
        //// Notifications
        let notificationMsg = productWorkflow ?
        `Product Workflow <strong>. ${workflow["name"]}.</strong> has been updated`
        : (serviceWorkflow ?
            `Service Workflow <strong>. ${workflow["name"]}.</strong> has been updated`
          : `Onboarding Workflow <strong>. ${workflow["name"]}.</strong> has been updated`);
        let notificationUrl = "onbaord";
        if (userId !== 1) {
          Admin.incrementField(userId, "noti_count", 1);
          Admin.addNotification({
            user_id: userId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          });
        }
        let adminId = await Admin.getAllAdminIds();
        for (let eachAdminId of adminId) {
          Admin.incrementField(eachAdminId, "noti_count", 1);
          Admin.addNotification({
            user_id: eachAdminId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          });
        }
        res.send({
          status: 1,
          message: productWorkflow ? 
          "Product workflow updated successfully" : 
          (serviceWorkflow ? 
          "Service workflow updated successfully" : 
          "Onboard workflow updated successfully"),
        });
      }
    }
    res.send({
      status: 1,
      message: "Failed to update  workflow ",
    });
  } 
  catch (error) {
    console.log(error, "error in adding workflow");
  }
};
const duplicateWorkFlow = async (req, res) => {
  try {
    let { id, savedStages, stageSubmit, userId,status } = req.body;
    let originalWorkflow = await Onboard.getWorkFlowbyId(id);
    
    let OriginalonboardStages = await OnboardWorkFlowStages.getStagesDataByWorkflowId(
      id
    );
   
    let workflow = {};
    let onBoardStages = [];
    let currentDate = Math.round(moment().valueOf() / 1000);
    if (!empty(originalWorkflow)) {
      workflow["name"] = originalWorkflow[0].name+currentDate;
      workflow["is_default"] = originalWorkflow[0].isDefault;
      workflow["timestamp"] = currentDate;
      workflow["updated_on"] = currentDate;
      workflow["added_by"] = userId;
      workflow["status"] = status;
      if (!empty(OriginalonboardStages)) {
        onBoardStages = OriginalonboardStages;
      } else {
        console.log("Failed to create onboarding workflow!");
        res.send({
          status: 0,
          msg: "Failed to create onboarding workflow!",
        });
      }

      let workflowId = await Onboard.addWorkFlow( workflow);
      workflowId=workflowId.id
      let oldStageids = await Onboard.getstageIdByWorkflowId(workflowId, 1);

      const ACTIONSTAGE=[
        {
            id: 7,
            label: 'Action Stage',
            session: 'onboard_stages',
            type: 'action-stage',
          },
    ]
    const ClientFacing = [
      {
        id: 1,
       
        label: 'Data Collection',
        session: 'onboard_stages',
        type: 'data-collection',
      },
      {
        id: 2,
       
        label: 'Bank Information',
        session: 'onboard_stages',
        type: 'bank-information',
        shot: 'bank',
      },
      {
        id: 3,
       
        label: 'Tax Information',
        session: 'onboard_stages',
        shot: 'tax',
        type: 'tax-information',
      },
      {
        id: 4,
       
        label: 'Portfolio',
        session: 'onboard_stages',
        type: 'portfolio',
        shot: 'previous works',
      },
      {
        id: 5,
      
        label: 'Questionnaire',
        session: 'onboard_stages',
        type: 'questionnaire',
      },
      {
        id: 6,
      
        label: 'Sign Agreement',
        session: 'onboard_stages',
        type: 'sign-agreement',
      },
    ]
   
    const result = onBoardStages.map(stage => {
      console.log("########stage", stage);
      // const clientFaceMapping = ClientFacing.find(clientFace => clientFace.id === stage.stage_type);
      
  
      // if (clientFaceMapping) {
      //     const { id, label, session, type, } = clientFaceMapping;
  
      //     stage.stage_type = {
      //         id,
      //         label,
      //         session,
      //         type,
              
      //     };
      // }
      if(stage.type_of_stage==1){
        stage.type_of_stage="automatic"
      }
      
        stage.description=stage.exit_message
        stage.order= stage.position_order
        // stage["partnerTypes"].id=stage.partner_type 
        if(!empty(stage.field_template_ids)){
          stage.template=stage.field_template_ids.map(id => ({ id }));
        }
        
        if(!empty(stage.bank_form_type)){
        
          stage.bank_details=stage.bank_form_type.map(id => ({ id }));
        }
       if(!empty(stage.requested_document_ids)){
        stage.documents=stage.requested_document_ids.map(id => ({ id }));
       }
     if(!empty(stage.sign_agreement_ids))
        {
          stage.agreements=stage.sign_agreement_ids.map(id => ({ id }));
        }
        if(!empty(stage.questionnaire_ids)){
          stage.questions=stage.questionnaire_ids.map(id => ({ id }));
        }
        if(!empty(stage.name)){
          stage.stage_name=stage.name
        }
        
  
      return stage;
  });
  
  
 console.log("#############ResultData",result);
      if (!empty(result)) {
        if(!empty(oldStageids)){
          for (let oldStageid of oldStageids) {
            let deleted = await OnboardWorkFlowStages.deleteWorkFlowStage(
              oldStageid.id
            );
          }
      
        }
        
        let i = 1;
       
        for (let onboardstage of result) {
          let stage = {};
          stage["workflow_id"] = workflowId;
          stage["name"] = onboardstage["stage_name"];
          stage["stage_type"] = onboardstage["stage_type"];
          stage["internal_stage"] = onboardstage["internal_stage"];
          stage["flow_type"] =1;
            // onboardstage["type_of_stage"] ==  onboardstage["type_of_stage"] == ("Automatic" || "automatic") ? 1 : 2;
            onboardstage["type_of_stage"]=1
            stage["message"] = onboardstage["description"]
            ? onboardstage["description"]
            : "";
          stage["position_order"] = onboardstage["order"]
            ? onboardstage["order"]
            : i++;
          if (!empty(onboardstage["partnerTypes"])) {
            stage["partner_type"] = onboardstage["partnerTypes"].id;
          }
          if (!empty(onboardstage["group_ids"])) {
            stage["group_ids"] = onboardstage["groups"]
              .map((item) => item.id)
              .join(",");
          }
          if (!empty(onboardstage["managers"])) {
            stage["relationship_manager_ids"] = onboardstage["managers"]
              .map((item) => item.id)
              .join(",");
          }
          if (!empty(onboardstage["bank_details"])) {
            stage["bank_form_type"] = onboardstage["bank_details"]
              .map((item) => item.id)
              .join(",");
          }
          if(!empty(onboardstage)){
            // stage['skill_ids'] = onboardstage['skills']?.map((item)=>item.id).join(',');
            stage['skill_ids'] = onboardstage['skill_ids'];
            stage['service_id'] = onboardstage['service_id'];
          }
          stage["timestamp"] = currentDate;
          stage["updated_on"] = currentDate;
          stage["added_by"] = userId;
          stage["status"] = 1;

          console.log("nush****************",stage);
         
          let stageId = await OnboardWorkFlowStages.addStage(stage);
          console.log("nush****************", stageId);
          let stageFieldTemplates = [];
          if (!empty(stageId)) {
            console.log("HIIIIIIIIIIII");
            if (!empty(onboardstage["template"])) {
              for (let fieldTemplateId of onboardstage["template"]) {
                let stageFieldTemplates = {};
                stageFieldTemplates["stage_id"] = stageId.id;
                stageFieldTemplates["field_template_id"] = fieldTemplateId.id;
                stageFieldTemplates["timestamp"] = currentDate;
                stageFieldTemplates["updated_on"] = currentDate;
                stageFieldTemplates["added_by"] = userId;
                stageFieldTemplates["status"] = 1;
                let result =
                  await OnboardWorkFlowFields.addOnboardworkFlowFields(
                    stageFieldTemplates
                  );
              }
            }
            ////
            if (!empty(onboardstage["documents"])) {
              for (let requested_document_id of onboardstage["documents"]) {
                let stageRequestDocuments = {};
                stageRequestDocuments["stage_id"] = stageId.id;
                stageRequestDocuments["document_id"] = requested_document_id.id;
                stageRequestDocuments["timestamp"] = currentDate;
                stageRequestDocuments["updated_on"] = currentDate;
                stageRequestDocuments["added_by"] = userId;
                stageRequestDocuments["status"] = 1;
                let result =
                  await OnboardWorkFlowDocuments.addOnboardworkFlowDocuments(
                    stageRequestDocuments
                  );
              }
            }
            ////
            if (!empty(onboardstage["agreements"])) {
              for (let sign_agreement_id of onboardstage["agreements"]) {
                let stageSignAgreements = {};
                stageSignAgreements["stage_id"] = stageId.id;
                stageSignAgreements["document_id"] = sign_agreement_id.id;
                stageSignAgreements["timestamp"] = currentDate;
                stageSignAgreements["updated_on"] = currentDate;
                stageSignAgreements["added_by"] = userId;
                stageSignAgreements["status"] = 1;
                let result =
                  await OnboardWorkFlowDocuments.addOnboardworkFlowDocuments(
                    stageSignAgreements
                  );
              }
            }
            ////
            console.log("$$$$$$$$$$$$$$$$$$nushhhhhhhhhh", onboardstage["questions"]);
            if (!empty(onboardstage["questions"])) {
              let stage_questionnaires = {};
              for (let questionnaire_id of onboardstage["questions"]) {
                stage_questionnaires["stage_id"] = stageId.id;
                stage_questionnaires["qns_template_id"] = questionnaire_id.id;
                stage_questionnaires["timestamp"] = currentDate;
                stage_questionnaires["updated_on"] = currentDate;
                stage_questionnaires["added_by"] = userId;
                stage_questionnaires["status"] = 1;
                let result =
                  await OnboardWorkFlowQuestionnaires.addOnboardQuestions(
                    stage_questionnaires
                  );
              }
            }
          }
        }
        //// Notifications
        let notificationMsg = `Workflow <strong>. ${workflow["name"]}.</strong> has been updated`;
        let notificationUrl = "onbaord";
        if (userId !== 1) {
          Admin.incrementField(userId, "noti_count", 1);
          Admin.addNotification({
            user_id: userId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          });
        }
        let adminId = await Admin.getAllAdminIds();
        for (let eachAdminId of adminId) {
          Admin.incrementField(eachAdminId, "noti_count", 1);
          Admin.addNotification({
            user_id: eachAdminId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          });
        }
        res.send({
          status: 1,
          message: "Onboard workflow updated successfully",
        });
      }
    }
    res.send({
      status: 1,
      message: "Failed to update onboard workflow ",
    });
  } 
  catch (error) {
    console.log(error, "error in adding workflow");
  }
};
const loadSidePanelForAddWorkFlow = async (req, res) => {
  try {
    let { layout, userId, internalStage, stageuId, sessionVariable } = req.body;
    let data = {};

    if (!sessionVariable) {
      sessionVariable = "onboard_stages";
    }

    data["stage_uid"] = stageuId;

    let onboardStage = null;

    if (sessionVariable) {
      onboardStage = sessionVariable;
    } else {
      onboardStage = [];
    }

    if (!empty(stageuId)) {
      data["internal_stage"] = onboardStage[stageuId]["internal_stage"];
      data["stage"] = onboardStage[stageuId];
      let json = {};
      json["action_stages"] = [];

      if (data["stage"]["partner_type"]) {
        json["action_stages"].push(1);
      }
      if (data["stage"]["group_ids"]) {
        json["action_stages"].push(2);
      }
      if (data["stage"]["relationship_manager_ids"]) {
        json["action_stages"].push(3);
      }
    } else {
      data["internal_stage"] = internalStage;
    }

    if (layout === "data-collection") {
      data["field_templates"] = await CustomFieldTemplates.getAllCustomFields();

      data["requested_documents"] = await Documents.getAllRequestedDocuments(1);
      if (data["stage"]) {
        if (data["stage"]["field_template_ids"]) {
          data["stage_field_templates"] =
            await CustomFieldTemplates.getAllTemplateIds(
              data["stage"]["field_template_ids"]
            );
        }
        if (data["stage"]["requested_document_ids"]) {
          data["stage_requested_documents"] = await Documents.getAllDocumentIds(
            1,
            data["stage"]["requested_document_ids"]
          );
        }
      }
    } else if (layout === "questionnaire") {
      data["questionnaires"] =
        await QuestionairesTemplates.getAllQuestionaireTemplates();

      if (data["stage"]) {
        if (data["stage"]["questionnaire_ids"]) {
          data["stage_questionnaires"] =
            await QuestionairesTemplates.getAllQuestionaireTemplateIds(
              data["stage"]["questionnaire_ids"]
            );
        }
      }
    } else if (layout === "sign-agreement") {
      data["sign_agreements"] = await Documents.getAllRequestedDocuments(2);

      if (data["stage"]) {
        if (data["stage"]["sign_agreement_ids"]) {
          data["stage_sign_agreements"] = await Documents.getAllDocumentIds(
            2,
            data["stage"]["sign_agreement_ids"]
          );
        }
      }
    } else if (layout === "action-stage") {
      data["partner_types"] = await PartnerTypes.getAllPartnerTypes();
      data["groups"] = await Groups.getAllGroups();
      data["staff_members"] = await Staffmembers.getAllWorkflow();
    }
    console.log("badassma ", data);
    if (!empty(data)) {
      res.send({
        data,
        status: 1,
        msg: "Fetch all data for the side panel",
      });
    } else {
      res.send({
        status: 0,
        msg: "Failed to fetch all data for the side panel",
      });
    }
  } catch (error) {
    console.log(error, "Error in loading the side panel");
    res.status(500).send("Server error" + error);
  }
};
const createDocumentRequest = async (req, res) => {
  try {
    let { newDocument, userId, userType } = req.body;
    let data = [];
    let documentRequest = {};
    let currentDate = Math.round(moment().valueOf() / 1000);
    documentRequest["name"] = newDocument;
    documentRequest["timestamp"] = currentDate;
    documentRequest["updated_on"] = currentDate;
    documentRequest["added_by"] = userId;
    documentRequest["status"] = 1;

    let documentRequestRes = await Documents.addDocument(documentRequest);
    if (!empty(documentRequestRes)) {
      let notificationMsg = `New document request <strong>".${documentRequest["name"]}."</strong> has been created.`;
      let notificationUrl = "onboard";
      if (userType != 1) {
        const incrementResult_User = await Admin.incrementField(
          userId,
          "noti_count",
          1
        );
        let notificationData_user = {
          user_id: userId,
          url: notificationUrl,
          timestamp: currentDate,
          message: notificationMsg,
          status: 1,
          from_id: userId,
        };

        const addNotificationResult_user = await Admin.addNotification(
          notificationData_user
        );
      }
      let adminIds = await Admin.getAllAdminIds();
      let notificationData = {};

      for (const adminId of adminIds) {
        const incrementResult = await Admin.incrementField(
          adminId,
          "noti_count",
          1
        );
        notificationData = {
          user_id: userId,
          url: notificationUrl,
          timestamp: currentDate,
          message: notificationMsg,
          status: 1,
          from_id: userId,
        };

        const addNotificationResult = await Admin.addNotification(
          notificationData
        );
      }
      res.send({
        documentRequestRes,
        status: 1,
        message: `${documentRequest["name"]} is added successfully`,
      });
    } else {
      res.send({
        status: 0,
        message: `Failed to add${documentRequest["name"]}`,
      });
    }
  } catch (error) {
    console.log(error);
  }
};
const createSignAgreement = async (req, res) => {
  try {
  } catch (error) {
    console.log(error, "error in saving agreement");
  }
};
//  public function create_sign_agreement(){
//     $data = array();
//     if($this->input->post()){
//         $agreement['name']=$this->input->post('agreement_name');
//         $agreement['document_type']=2;
//         $agreement['timestamp']=time();
//         $agreement['updated_on']=time();
//         $agreement['added_by']=$this->session->userdata('user_id');
//         $agreement['status']=1;

//         $uploaded=$this->onboard_model->do_upload('attachment');
//         if(isset($uploaded['error'])){
//             $json['msg_type']=2;
//             $json['msg']=$uploaded['error'];
//         }else{
//             if($uploaded['file_name']!='') {
//                 $agreement['attachment']=$uploaded['file_name'];
//             }
//         }

//         $agreement_id = $this->onboard_model->add_document_request($agreement);
//         if($agreement_id){
//             // Notification
//             $notification_msg="New sign agreement <strong>".$agreement['name']."</strong> has been created.";
//             $notification_url="onboard";
//             if($this->session->userdata('user_type')!=1) {
//                 // Alert assigned user of updation
//                 $this->admin_model->increment_field($this->session->userdata('user_id'), "noti_count", 1);
//                 $this->admin_model->add_notification(array(
//                         "user_id" => $this->session->userdata('user_id'),
//                         "url" => $notification_url,
//                         "timestamp" => time(),
//                         "message" => $notification_msg,
//                         "status" => 1,
//                         "from_id" => $this->session->userdata('user_id'),

//                     )
//                 );
//             }
//             $admin_ids=$this->admin_model->get_all_admin_ids();
//             foreach($admin_ids as $admin_id){
//                 // Alert assigned user of updation
//                 $this->admin_model->increment_field($admin_id, "noti_count", 1);
//                 $this->admin_model->add_notification(array(
//                         "user_id" => $admin_id,
//                         "url" => $notification_url,
//                         "timestamp" => time(),
//                         "message" => $notification_msg,
//                         "status" => 1,
//                         "from_id" => $this->session->userdata('user_id'),

//                     )
//                 );
//             }
//         }
//         $requested_documents=$this->onboard_model->get_all_requested_documents(2);
//         $json['content']='<option value=""></option>';
//         if(!empty($requested_documents)){
//             foreach($requested_documents as $requested_document){
//                 $json['content'].='<option value="'.$requested_document['id'].'">'.$requested_document['name'].'</option>';
//             }
//         }
//         echo json_encode($json);
//     }
// }

//the below sav stage in not necessary *********************
const saveStages = async (req, res) => {
  try {
    let {
      sessionVariable,
      userId,
      userType,
      stageuId,
      values,
      internalStage,
      partner_type,
    } = req.body;
    if (empty(sessionVariable)) {
      sessionVariable = "onboard_stages";
    }
    let onboardStage = [];
    if (!empty(sessionVariable)) {
      onboardStage = sessionVariable;
    } else {
      onboardStage = [];
    }
    let stage = {};
    stage["name"] = values.name;
    stage["stage_type"] = values.stage_type;
    stage["internal_stage"] = internalStage;
    if (values.type_of_stage == "automatic") {
      stage["type_of_stage"] = 1;
    } else {
      stage["type_of_stage"] = 2;
    }
    stage["exit_message"] = values.description;
    stage["old_stage"] = 0;
    if (!empty(values.template)) {
      for (let eachTemplate of values.template) {
        stage["field_template_ids"] = eachTemplate.id;
      }
    }
    if (!empty(values.documents)) {
      for (let eachDocs of values.documents) {
        stage["requested_document_ids"] = eachDocs.id;
      }
    }
    if (!empty(values.agreements)) {
      for (let eachAgreement of values.agreements) {
        stage["sign_agreement_ids"] = eachAgreement.id;
      }
    }
    if (!empty(values.questions)) {
      for (let eachQuestion of values.questions) {
        stage["questionnaire_ids"] = eachQuestion.id;
      }
    }
    if (!empty(partner_type)) {
      stage["partner_type"] = partner_type;
    } else {
      stage["partner_type"] = 0;
    }
    if (!empty(values.group)) {
      for (let eachGroup of values.group) {
        stage["group_ids"] = eachGroup.id;
      }
    }
    if (!empty(values.relationshipManager)) {
      for (let eachmanager of values.relationshipManager) {
        stage["relationship_manager_ids"] = eachmanager.id;
      }
    }
    if (!empty(values.bank_form_type)) {
      for (let eachForm of values.bankForm) {
        stage["bank_form_type"] = eachForm.id;
      }
    } else {
      stage["bank_form_type"] = [];
    }
    if (!empty(stageuId)) {
      stage["order"] = onboardStage.length + 1;
    } else {
      stage["order"] = onboardStage[stageuId]["order"];
      stage["old_stage"] = onboardStage[stageuId]["old_stage"];
    }
    onboardStage[stageuId] = stage;
  } catch (error) {
    console.log(error, "error in savinng stages");
  }
};
const deletWorkFlow = async (req, res) => {
  try {
    let currentDate = Math.round(moment().valueOf() / 1000);
    let { id, status, userId, userType,productWorkflow, serviceWorkflow } = req.body;
    let workflow = {};
    workflow["status"] = status;

    if (!empty(id)) {
      let data = await Onboard.getWorkFlowbyId(id);
      let deleted = await Onboard.updateWorkFlow(id, workflow);

      if (workflow["status"] == 2) {
        if (deleted) {
          //notification
          console.log("###########Product",productWorkflow);
          let notificationMsg = (productWorkflow === true
          ? `The Product Workflow <strong>"${data[0].name}"</strong> has been deleted.`
          : (serviceWorkflow === true
            ? `The Service Workflow <strong>"${data[0].name}"</strong> has been deleted.`
            : `The Onboard Workflow <strong>"${data[0].name}"</strong> has been deleted.`));
      
          let notificationUrl = "onboard";
          if (userType !== 1) {
            Admin.incrementField(userId, "noti_count", 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          let adminId = await Admin.getAllAdminIds();
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, "noti_count", 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          res.send({
            status: 2,
            message: productWorkflow === true ?
            `The Product Workflow ${data[0].name} has been deleted.`
            : serviceWorkflow === true ?
            `The Service Workflow ${data[0].name} has been deleted.`
            : `The Onboard Workflow ${data[0].name} has been deleted.`,
          });
        }
      } 
      else if (workflow["status"] == 1) {
        if (deleted) {
          let notificationMsg = `The Onboard Workflow <strong>".${data[0].name}."</strong> has been made active.`;
          let notificationUrl = "onboard";
          if (userType !== 1) {
            Admin.incrementField(userId, "noti_count", 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          let adminId = await Admin.getAllAdminIds();
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, "noti_count", 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          res.send({
            status: 1,
            message: `The Onboard Workflow ${data[0].name} has been made active.`,
          });
        }
      } 
      else if (workflow["status"] == 0) {
        if (deleted) {
          let notificationMsg = `The Onboard Workflow <strong>".${data[0].name}."</strong> has been made inactive.`;
          let notificationUrl = "onboard";
          if (userType !== 1) {
            Admin.incrementField(userId, "noti_count", 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          let adminId = await Admin.getAllAdminIds();
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, "noti_count", 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          res.send({
            status: 0,
            message: `The Onboard Workflow ${data[0].name} has been made inactive!`,
          });
        }
      }
      else if(workflow["status"] == 8){
        if (deleted) {
          let notificationMsg = `The Product Workflow <strong>".${data[0].name}."</strong> has been made inactive.`;
          let notificationUrl = "onboard";
          if (userType !== 1) {
            Admin.incrementField(userId, "noti_count", 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          let adminId = await Admin.getAllAdminIds();
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, "noti_count", 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          res.send({
            status: 0,
            message: `The Onboard Workflow ${data[0].name} has been made inactive!`,
          });
        }
      }
      else if (workflow["status"] == 4) {
        if (deleted) {
          let notificationMsg = `The Product Workflow <strong>".${data[0].name}."</strong> has been made active.`;
          let notificationUrl = "onboard";
          if (userType !== 1) {
            Admin.incrementField(userId, "noti_count", 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          let adminId = await Admin.getAllAdminIds();
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, "noti_count", 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          res.send({
            status: 1,
            message: `The Onboard Workflow ${data[0].name} has been made active.`,
          });
        }
      } 
      else if (workflow["status"] == 9) {
        if (deleted) {
          let notificationMsg = `The Service Workflow <strong>".${data[0].name}."</strong> has been made active.`;
          let notificationUrl = "onboard";
          if (userType !== 1) {
            Admin.incrementField(userId, "noti_count", 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          let adminId = await Admin.getAllAdminIds();
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, "noti_count", 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          res.send({
            status: 1,
            message: `The Product Workflow ${data[0].name} has been made active.`,
          });
        }
      } 
      else if(workflow["status"] == 10){
        if (deleted) {
          let notificationMsg = `The Service Workflow <strong>".${data[0].name}."</strong> has been made inactive.`;
          let notificationUrl = "onboard";
          if (userType !== 1) {
            Admin.incrementField(userId, "noti_count", 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          let adminId = await Admin.getAllAdminIds();
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, "noti_count", 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }

          res.send({
            status: 0,
            message: `The Service Workflow ${data[0].name} has been made inactive!`,
          });
        }
      }
    }
  } catch (error) {
    console.log(error, "error in deleting workflow");
  }
};
const fetchWorkFlowById = async (req, reply) => {
  try {
    let { id } = req.body;
    let workflow = await Onboard.getWorkFlowbyId(id);
    let partner_types = await PartnerTypes.getAllPartnerTypes();
    let groups = await Groups.getAllGroups();
    let staff_members = await Staffmembers.getAllWorkflow();
    let onboard_stages = await OnboardWorkFlowStages.getStagesDataByWorkflowId(
      id
    );

    if (!empty(onboard_stages)) {
      reply.send({
        status: 1,
        workflow,
        partner_types,
        groups,
        onboard_stages,
        staff_members,
        message: "Fetched Successfully",
      });
    } else {
      reply.send({
        status: 1,
        workflow,
        partner_types,
        groups,
        onboard_stages,
        staff_members,
        message: "Fetched Successfully",
      });
    }
  } catch (error) {
    reply.send({ status: 0, message: "Failed to fetch" + error });
  }
};
const onboardProcess = async (req, res) => {
  try {
    let { userId, userType, currentStageId, currentPartnerId, values } =
      req.body;
    let currentDate = Math.round(moment().valueOf() / 1000);
    let data = {};
    data["partner"] = await Admin.getPartnerByUserId(userId);
    console.log("Midhun###########", data);
    if (empty(data["partner"])) {
      return;
    }
    data["completed"] = 0;
    data["process_url"] = "process";
    let partnerId = data["partner"]["id"];
    data["workflows"] = await Onboard.getOnboardingWorkflows(
      partnerId,
      data["partner"]["workflows"]
    );

    if (empty(data["partner"]["workflows"])) {
      // $this->load->view('admin/onboard/onboard-views/no-onboarding',$data);
      res.send({ status: 4, msg: "No onboarding", data });
    }
    let partnerStageRes = await Onboard.ispartnerStages(partnerId);
    console.log("###########nnnn", partnerStageRes);
    let stage = [];
    console.log("###########nnnnOn", data["workflows"]);
    if (empty(data["workflows"]) && partnerStageRes) {
      console.log("NNNNNNNNNNNNNNN");
      data["completed"] = 1;
      let isOnboardComplete = await Admin.isOnboardComplete(
        partnerId,
        "partners"
      );
      console.log("############Onboard",isOnboardComplete);
      if (!isOnboardComplete) {
        console.log("############Onboarding111111",partnerId);
        let updatedpartner = await Clients.updateClient( { onboard_complete: 1 }, partnerId);

        let adminEmails = await Admin.getAllAdminEmails();
        let adminSubject = portalName + " -  Onboarding completed";
        let adminWelcome = "Hello ! Admin" + ",";
        let admin_email_content = `${data["partner"]["name"]} has been completed the onboarding.`;
        let adminEmailContentNext="All required documents and necessary requirements have been submitted and processed."
        let adminMessage = onboardTemplate();
        adminMessage = adminMessage.replace("[emailContent]",admin_email_content);
        adminMessage = adminMessage.replace("[emailContentNext]",adminEmailContentNext);
        adminMessage = adminMessage.replace("[CONTENT]", adminWelcome);
       

        adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
        for (const row of adminEmails) {
          console.log("$$$$$$$$$$$$$$$nush", row);
          // const msg = {
          //   to: row,
          //   from: "nushara@skyniche.com",
          //   subject: adminSubject,
          //   text: adminSubject,
          //   html: adminMessage,
          // };
          // sgMail
          //   .send(msg)
          //   .then(() => {
          //     console.log("Email sent");
          //   })
          //   .catch((error) => {
          //     console.error(error);
          //   });

          const mailOptions = {
            to:  row , 
            from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
            subject: adminSubject,
            text: adminSubject,
            html: adminSubject,
          }
          try {
              if(SEND_EMAIL){
            await transporter.sendMail(mailOptions);
            console.log('Email sent');
              }
          } catch (error) {
            console.error('##########Err', error);
           
          }
        }
        let clientMessage = onboardTemplate();
        let subject="Congratulations! You're Onboarded 🚀"
        let welcomeMsg = "Hello ! " +data["partner"]['name']+",";
        let email_content = `We're happy to inform you that you have successfully completed the onboarding process! 🎉`;
        let emailContentNext=  `Thank you for choosing ${portalName}. We look forward to a successful collaboration.`
        clientMessage = clientMessage.replace("[emailContent]",email_content);
        clientMessage = clientMessage.replace("[emailContentNext]",emailContentNext);
        clientMessage = clientMessage.replace("[CONTENT]", welcomeMsg);
        

        clientMessage = clientMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
        
          
          // const msg = {
          //   to: data['partner']['email'],
          //   from: "nushara@skyniche.com",
          //   subject: subject,
          //   text: adminSubject,
          //   html: clientMessage,
          // };
          // sgMail
          //   .send(msg)
          //   .then(() => {
          //     console.log("Email sent");
          //   })
          //   .catch((error) => {
          //     console.error(error);
          //   });

          const mailOptions = {
            to:  data['partner']['email'],
            from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
            subject: subject,
            text: adminSubject,
            html: clientMessage,
          }
          try {
            if(SEND_EMAIL){
            await transporter.sendMail(mailOptions);
            console.log('Email sent');
            }
          } catch (error) {
            console.error('##########Err', error);
           
          }
        
        let relationshipManagerdata = await Admin.getAllRelationshipManagerdata(partnerId);
        console.log("$$$$$$$$$$$$$$$$$$$$$$", relationshipManagerdata);
        if(!empty(relationshipManagerdata)){
          let realtionSubject = portalName + " -  Onboarding completed";
          let relationWelcome = "Hello ! Admin" + ",";
          let relation_email_content = `${relationshipManagerdata["partner"]["name"]}." has completed the onboarding.`;
          let relationMessage = activateProfile();
          adminMessage = adminMessage.replace(
            "[emailContent]",
            relation_email_content
          );
          adminMessage = adminMessage.replace("[CONTENT]", relationWelcome);
          adminMessage = adminMessage.replace("[NAME]", data["partner"]["name"]);
          // adminMessage = adminMessage.replace("[PASSWORD]", values.password);
          adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
          for (const row of relationshipManagerdata) {
            console.log("$$$$$$$$$$$$$$$nush", row);
            // const msg = {
            //   to: row,
            //   from: "nushara@skyniche.com",
            //   subject: realtionSubject,
            //   text: realtionSubject,
            //   html: relationMessage,
            // };
            // sgMail
            //   .send(msg)
            //   .then(() => {
            //     console.log("Email sent");
            //   })
            //   .catch((error) => {
            //     console.error(error);
            //   });

            const mailOptions = {
              to:  row , 
              from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
              subject: realtionSubject,
              text: realtionSubject,
              html: relationMessage,
            }
            try {
              if(SEND_EMAIL){
              await transporter.sendMail(mailOptions);
              console.log('Email sent');
              }
            } catch (error) {
              console.error('##########Err', error);
             
            }
          }
        }
       
      }
    }
    let partnerStageStatus = req.body.partnerStageStatus
    console.log("###########xxxx", values);
    if (!empty(values)) {
      let partnerStageId = req.body.partnerStage_id
      let workflowId = req.body.workflow_id
      let stageId = req.body.stage_id
      let stageType = req.body.stage_type
      let position_order = req.body.position_order
      let stage_submit = req.body.stage_submit
      // let partnerStageStatus = req.body.partnerStageStatus
      let isPartnerExist = await Onboard.ispartnerstageExistthenid(partnerId, stageId)
      console.log("$$$$$$$$$$nush", isPartnerExist);
      if (empty(partnerStageId) && !isPartnerExist) {
        isPartnerExist;
      }
      if (!empty(partnerStageId)) {
        let currentPartnerStage = await Onboard.getpartnerStageByid(
          partnerStageId
        );
        if (!empty(currentPartnerStage)) {
          if (
            currentPartnerStage["status"] == 1 &&
            currentPartnerStage["stage_submit"] == 1
          ) {
            // return
            // redirect('admin/onboard/process');
            res.send({ status: 1, msg: "onboard process", data });
          }
        }
      }
      let partner_stage = {};
      console.log("Hiiiii3", partnerStageId);

      if (empty(partnerStageId)) {
        console.log("####################Manual", stage_submit);
        partner_stage['partner_id'] = partnerId
        partner_stage['workflow_id'] = workflowId
        partner_stage['stage_id'] = stageId
        partner_stage['stage_type'] = stageType
        partner_stage['position_order'] = position_order
        partner_stage['stage_submit'] = stage_submit
        partner_stage['timestamp'] = currentDate
        partner_stage['updated_on'] = currentDate
        partner_stage['added_by'] = userId
        partner_stage['status'] = partnerStageStatus
        console.log("####################Manual", partner_stage);
        partnerStageId = await PartnerStage.addPartnerstage(partner_stage)
      }
      else {
        console.log("####################Manualup");
        partner_stage['updated_on'] = currentDate
        partner_stage['stage_submit'] = stage_submit
        partner_stage['status'] = partnerStageStatus
        await PartnerStage.updatePartnerStage(partnerStageId, partner_stage)
      }
      if (partnerStageStatus == 0 && stage_submit == 1) {
        let stageData = await Onboard.getpartnerStageByid(partnerStageId)
        console.log("####################Manualup", stageData);
        let adminEmails = await Admin.getAllAdminEmails();
        let adminSubject = portalName + " -" + stageData["name"] + "Approval.";
        let adminWelcome = "Hello ! Admin" + ",";
        let admin_email_content = `${data["partner"]["name"]}." has completed the stage <strong>.${stageData['name']}."</strong> and waiting for your approval`;
        let adminMessage = activateProfile();
        adminMessage = adminMessage.replace(
          "[emailContent]",
          admin_email_content
        );
        adminMessage = adminMessage.replace("[CONTENT]", adminWelcome);
        // adminMessage = adminMessage.replace("[NAME]", user["username"]);
        // adminMessage = adminMessage.replace("[PASSWORD]", values.password);
        adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
        for (const row of adminEmails) {
          console.log("$$$$$$$$$$$$$$$nush", row);
          // const msg = {
          //   to: row,
          //   from: "nushara@skyniche.com",
          //   subject: adminSubject,
          //   text: adminSubject,
          //   html: adminMessage,
          // };
          // sgMail
          //   .send(msg)
          //   .then(() => {
          //     console.log("Email sent");
          //   })
          //   .catch((error) => {
          //     console.error(error);
          //   });

          const mailOptions = {
            to:  row , 
            from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
            subject: adminSubject,
            text: adminSubject,
            html: adminMessage,
          }
          try {
            if(SEND_EMAIL){
            await transporter.sendMail(mailOptions);
            console.log('Email sent');
            }
          } catch (error) {
            console.error('##########Err', error);
           
          }
        }
        //notification
        let notificationUrl = "process"
        let notificationMsg = admin_email_content
        let adminId = await Admin.getAllAdminIds();
        for (let eachAdminId of adminId) {
          Admin.incrementField(eachAdminId, "noti_count", 1);
          Admin.addNotification({
            user_id: eachAdminId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          });
        }
      }
      console.log("partnerStageStatus", partnerStageStatus);
      if (partnerStageStatus == 1 && stage_submit == 1) {
        let nextStage = await OnboardWorkFlowStages.getnextStage(partnerId, workflowId)
        console.log("####################auto");
        if (!empty(nextStage)) {
          let next_partner_stage = {};
          if (nextStage["stage_type"] != 7 && !empty(nextStage["id"])) {
            next_partner_stage["partner_id"] = partnerId;
            next_partner_stage["workflow_id"] = workflowId;
            next_partner_stage["stage_id"] = nextStage["id"];
            next_partner_stage["stage_type"] = nextStage["stage_type"];
            next_partner_stage["position_order"] = nextStage["position_order"];
            next_partner_stage["stage_submit"] = 0;
            next_partner_stage["timestamp"] = currentDate;
            next_partner_stage["updated_on"] = currentDate;
            next_partner_stage["added_by"] = userId;
            next_partner_stage["status"] = 0;
            next_partner_stage_id =
              PartnerStage.addPartnerstage(next_partner_stage);
          } else {
            while (nextStage["stage_type"] == 7) {
              if (!empty(nextStage["partner_type"])) {
                await Clients.updateClient(
                  nextStage["partner_type"],
                  partnerId
                );
              }

              let partnerGroups = [];
              if (!empty(nextStage["group_ids"])) {
                nextStage.group_ids.forEach(async (group_id) => {
                  if (
                    !(await onboardModel.isPartnerGroupExist(
                      partnerId,
                      group_id
                    ))
                  ) {
                    const group = {
                      partner_id: partnerId,
                      group_id: group_id,
                      timestamp: Math.floor(new Date().getTime() / 1000),
                      added_by: userId, // Assuming 'session' is an object with 'userData' property
                      status: 1,
                    };
                    partnerGroups.push(group);
                    let partnerGroupId = await Group.addPartnerGroup(group);
                  }
                });
              }

              if (nextStage.relationship_managers.length > 0) {
                const partner_team_members = {};

                for (const teamId of nextStage.relationship_managers) {
                  if (
                    !(await onboardModel.isPartnerTeamMemberExist(
                      partnerId,
                      teamId
                    ))
                  ) {
                    const teamMember = {
                      partner_id: partnerId,
                      team_id: teamId,
                      timestamp: Math.floor(new Date().getTime() / 1000),
                      added_by: userId, // Assuming 'session' is an object with 'userData' property
                      status: 1,
                    };
                    partner_team_members.push(teamMember);
                    const partner_team_id = await PartnerStage.addPartnerTeam(
                      teamMember
                    );
                  }
                }
              }
              next_partner_stage["partner_id"] = partnerId;
              next_partner_stage["workflow_id"] = workflowId;
              next_partner_stage["stage_id"] = nextStage["id"];
              next_partner_stage["stage_type"] = nextStage["stage_type"];
              next_partner_stage["position_order"] =
                nextStage["position_order"];
              next_partner_stage["timestamp"] = moment().unix();
              next_partner_stage["updated_on"] == moment().unix();
              next_partner_stage["added_by"] = userId;
              next_partner_stage["status"] = 1;
              let next_partner_stage_id = await PartnerStage.addPartnerstage(
                next_partner_stage
              );
              nextStage = await OnboardWorkFlowStages.getnextStage(
                partnerId,
                workflowId
              );
            }
            if (nextStage['stage_type'] != 7 && !empty(nextStage['id'])) {
              next_partner_stage['partner_id'] = partnerId;
              next_partner_stage['workflow_id'] = workflowId;
              next_partner_stage['stage_id'] = nextStage['id'];
              next_partner_stage['stage_type'] = nextStage['stage_type'];
              next_partner_stage['position_order'] = nextStage['position_order'];
              next_partner_stage['stage_submit'] = 0;
              next_partner_stage['timestamp'] = moment().unix();
              next_partner_stage['updated_on'] = moment().unix();
              next_partner_stage['added_by'] = userId;
              next_partner_stage['status'] = 0;
              next_partner_stage_id = await OnboardWorkFlowStages.getnextStage(partnerId, workflowId)
            }
          }

        }

      }

      stage = await OnboardWorkFlowStages.getnextStage(partnerId, workflowId, stageId);

      if (stage.stage_type === 1) {
        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPP");
        let field_template_i = 0;
        const partner_fields = [];
        let fieldTemplates = values.fieldTemplates
        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPP", fieldTemplates);
        let partnerFields = []
        let partnerField = {}
        const field_value_pairs = [];
        let valueData = removeNull(fieldTemplates)

        for (const [key, value] of Object.entries(valueData)) {

          if (value && typeof value === 'object' && "value" in value) {
            field_value_pairs.push({ "field_id": value.field_id, "value": value.value,partner_id: partnerId,updated_on: moment().unix(),added_by: userId, status: 1,});
          } else if (value && Array.isArray(value) && value.every(item => typeof item === 'object' && "value" in item)) {
            for (const item of value) {
              if(!empty(item.value)){
                field_value_pairs.push({ "field_id": item.field_id, "value": item.value,partner_id: partnerId,updated_on: moment().unix(),added_by: userId, status: 1,});
              }
             
            }
          }
        
        }
        console.log("XXXXXXXXXXXXXXXXXX", field_value_pairs);
      
        console.log("############field_value_pairs", partnerFields);
        if (!empty(field_value_pairs)) {
          await Onboard.updateBatchData(
            "partner_custom_fields",
            field_value_pairs
          );

        }



        let requested_document_i = 0;
        const partner_requested_documents = [];

        if (stage.requested_documents && stage.requested_documents.length > 0) {
          for (const requested_document of stage.requested_documents) {
            // if(!empty(req.body.requested_document_hidden_+${requested_document.id})){
            //     const requested_document_hidden_value = req.body.`requested_document_hidden_${requested_document.id}`;
            // }

            partner_requested_documents[requested_document_i] = {
              id:
                requested_document_hidden_value ||
                requested_document.partner_document_id ||
                null,
              partner_id: partnerId,
              document_id: requested_document.id,
              document_type: 1,
              onboarding: 1,
              issue_date: moment(
                this.input.post(
                  `requested_document_issue_date_${requested_document.id}`
                )
              ).unix(),
              expiry_date: moment(
                this.input.post(
                  `requested_document_expiry_date_${requested_document.id}`
                )
              ).unix(),
              updated_on: moment().unix(),
              added_by: userId,
              status: 1,
            };

            const files =
              this.input.files[`requested_document_${requested_document.id}`];
            if (
              files &&
              files.name &&
              files.name.length > 0 &&
              files.name[0] !== ""
            ) {
              const uploaded = await onboardModel.doUpload(
                `requested_document_${requested_document.id}`,
                "partners"
              );

              if (uploaded.error) {
                this.session.flash("error_msg", uploaded.error);
                this.redirect("admin/onboard/process");
                return;
              } else if (uploaded.file_name !== "") {
                partner_requested_documents[requested_document_i].file_name =
                  uploaded.file_name;
              }
            } else {
              partner_requested_documents[requested_document_i].file_name =
                null;
            }

            requested_document_i++;
          }
        }

        if (partner_requested_documents.length > 0) {
          await onboardModel.updateBatchData(
            "partner_documents",
            partner_requested_documents
          );
        }
      } else if (stage["stage_type"] == 2) {
        console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%nnnnn");
        const bank_info = [
          {
            // id:values.bank_info_id || null,
            partner_id: partnerId,
            bank_name: values.bank || null,
            name_on_account: values.nameOnAccount || null,
            routing_number: values.routing || null,
            account_number: values.accountno || null,
            account_type: values.account_type?.id || 1,
            swift_code: values.swift || null,
            name_on_card: values.name_on_card || null,
            card_number: values.ccdc || null,
            expiration_date: values.expire_date ? moment(values.expire_date).unix() : null,
            card_cvv: values.card_cvv
              ? this.encrypt.encode(values.card_cvv)
              : null,
            // card_type: values.card_type || null,
            updated_on: moment().unix(),
            added_by: userId,
            status: 1,
          },
        ];
        console.log('Bank&&&&&&&&&&&&&&&&&&', bank_info);
        await Onboard.updateBatchData("partner_bank_info", bank_info);
      } else if (stage["stage_type"] == 3) {
        const tax_info = [
          {
            // id: req.body.tax_info_id|| null,
            partner_id: partnerId,
            business_type: values.approach=="individual"?2:1 || null,
            social_security_number: values.tax_num || null,
            first_name: values.first_name || null,
            middle_name: values.middle_name || null,
            last_name: values.last_name || null,
            address: values.address || null,
            city: values.city || null,
            state_id: values.states.id || null,
            zipcode: values.zip_code || null,
            is_business_name: values.business_name || 2,
            business_name: values.business_name_value || "",
            tax_classification: values.tax_clarify===false?0:1 || 0,
            updated_on: moment().unix(),
            added_by: userId,
            status: 1,
          },
        ];
        console.log("Tax=================");
        await Onboard.updateBatchData("partner_tax_info", tax_info);
      } else if (stage["stage_type"] == 4) {
        let titles = [];
        titles.push(values.title);
        let descriptions = [];
        descriptions.push(values.description);
        let files = [];
        files.push(values.avatarUrl);
        let i = 0;
        while (values.hasOwnProperty(`title${i}`)) {
          titles.push(req.body.values[`title${i}`]);
          i++;
        }

        i = 0;
        while (values.hasOwnProperty(`description${i}`)) {
          descriptions.push(values[`description${i}`]);
          i++;
        }
        i = 0;
        while (values.hasOwnProperty(`avatarUrl${i}`)) {
          files.push(values[`avatarUrl${i}`]);
          i++;
        }

        const portfolio_ids = req.body.portfolio_id;

        const portfolio_file_fields = req.body.portfolio_file_field;
        let portfolios = [];
        for (let i = 0; i < titles.length; i++) {
          const portfolio = {
            // id: portfolio_ids[key] || null,
            partner_id: partnerId,
            title: titles[i],
            description: descriptions[i],
            updated_on: moment().unix(),
            file_name: files[i],
            added_by: userId,
            status: 1,
          };
          portfolios.push(portfolio);
        }
        console.log("##############", portfolios);
       

        if (portfolios.length > 0) {
          await Onboard.updateBatchData("partner_portfolio", portfolios);
        }
      }
      else if (stage['stage_type'] == 5) {
       
        let field_template_i = 0;
        const partner_fields = [];
        let fieldTemplates = values.fieldTemplates
        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPP", fieldTemplates);
        let partnerFields = []
        let partnerField = {}
       
        console.log("XXXXXXXXXXXXXXXXXX", partnerFields);

          const field_value_pairs = [];
          let valueData = removeNull(fieldTemplates)

        for (const [key, value] of Object.entries(valueData)) {
         
          if (value && typeof value === 'object' && "value" in value) {
            field_value_pairs.push({ "field_id": value.field_id, "value": value.value,partner_id: partnerId,updated_on: moment().unix(),added_by: userId, status: 1,});
          } else if (value && Array.isArray(value) && value.every(item => typeof item === 'object' && "value" in item)) {
            for (const item of value) {
              if(!empty(item.value)){
              field_value_pairs.push({ "field_id": item.field_id, "value": item.value,partner_id: partnerId,updated_on: moment().unix(),added_by: userId, status: 1,});
              }
            }
          }
        }
        
        console.log("XXXXXXXXXXXXXXXXXX", field_value_pairs);
        if (field_value_pairs.length > 0) {
          await Onboard.updateBatchData("partner_questionnaires",
           field_value_pairs

          );
        }
      }
      else if (stage["stage_type"] === 6) {
        console.log("$$$%%%%%%%%%stage666666666666666666");
        const agreements =  [];
      for(let i=0;i<req.body.sign_agrement.length;i++){
        const agreementdata = {
          // id: this.input.post(`sign_agreement_id_hidden_${sign_agreement.id}`) || null,
          partner_id: partnerId,
          document_id: req.body.sign_agrement[i],
          file_name: values.sign_attach,
          document_type: 2,
          onboarding: 1,
          updated_on: moment().unix(),
          added_by: userId,
          status: 1
        }
        agreements.push(agreementdata);
      }
       
        console.log("$$$%%%%%%%%%", agreements);
        await Onboard.updateBatchData('partner_documents', agreements);
      
      }
    }

    if (!empty(data["workflows"])) {
      for (let eachworkflow of data["workflows"]) {
        data["stage"] = await OnboardWorkFlowStages.getnextStage(
          partnerId,
          eachworkflow["id"]
        );
        console.log("%%%%%%%%%%%%%%", data["stage"]);
        if (!empty(data["stage"])) {
          workflowId = eachworkflow["id"];
          break;
        }
      }
    }
    data["states"] = await Admin.getAllStates();
    if (
      !empty(stage) &&
      !empty(stage["message"]) &&
      !empty(partnerStageStatus) &&
      stage["stage_submit"] == 1
    ) {
      data["stage_submit"] = stage["stage_submit"];
      data["stage"] = stage;
      //   $this->load->view('admin/onboard/onboard-views/auto-onboarding',$data);
      res.send({ manual: 1, data, status: 1, });
      return;
    }


    if (!empty(data['stage'])) {
      if (!empty(data['stage']['partner_stage_id'])) {
        console.log("Anavia riyassssssssssssss", data['stage']['partner_stage_id']);
        let stagedata = await Onboard.getpartnerStageByid(data['stage']['partner_stage_id'])
        console.log("Anavia riyassssssssssssss", stagedata);
        if (stagedata[0]['stage_submit'] == 1) {
          data['stage_submit'] = stagedata[0]['stage_submit']
          //       $this->load->view('admin/onboard/onboard-views/no-onboarding',$data);
          console.log("Anavia riyassssssssssssss ohhhhhhhhhhh");
          res.send({ manual: 1, data, status: 1 });
          return
        }
      }

      let currentProcessingStageData = data["stage"];
      let currentProcessingPartnerId = partnerId;
      // if(data['stage']['stage_type']==1){
      //   //     $this->load->view('admin/onboard/onboard-views/data-collection',$data);
      // }else if(data['stage']['stage_type'] ==5){
      //   //     $this->load->view('admin/onboard/onboard-views/questionnaire',$data);
      // }
      // else if(await Onboard.isTeamStages(teamId)){
      //   //   redirect('admin/onboard/process-team');
      // }else{
      //   //   $this->load->view('admin/onboard/onboard-views/no-onboarding',$data);
      // }

  
      res.send({ stage: data["stage"]["stage_type"], data, status: 1 });
    } else if (await Onboard.ispartnerStages(partnerId)) {
      console.log("$$$$$$$$$$$$$$$$Nushhhhhhhhhhhhhh");
      res.send({ onboardCompleted: 1, data, status: 1 });

      // redirect('admin/onboard/process');
    } else {
      // $this->load->view('admin/onboard/onboard-views/no-onboarding',$data);
    }
  } catch (error) {
    res.status(500).send("error in process" + error)
    console.log(error, "error in process");
  }
}
const reviewOnboard = async (req, res) => {
  try {
    const {
      userId,
      partnerStage_id,
      onboardId
      ,
      stageId,
      stageType,
      positionOrder,
      partner_id,
      stage_submit
    } = req.body;
    let workflowId = onboardId
    let partnerId = partner_id
    if (!empty(stage_submit)) {
      console.log("###Nushhhhhhhhhhhhhhh", partnerStage_id);
      let currentDate = Math.round(moment().valueOf() / 1000);
      let partnerStage = {};
      partnerStage["approved_by"] = userId
      partnerStage["approved_on"] = currentDate,
        partnerStage["status"] = 1,
        await PartnerStage.updatePartnerStage(partnerStage_id, partnerStage);



      //notification
      let stage = await Onboard.getpartnerStageByid(partnerStage_id);
      let partner = await Clients.getClientById(partner_id);
      let notificationmsg = `The Onboarding stage ${stage["name"]} of <strong> ${partner["name"]} </strong> hsa been approved.`;
      let notificationUrl = `onboard/view/${workflowId}`;

      // Alert assigned user of updation
      Admin.incrementField(partner["user_id"], "noti_count", 1);
      Admin.addNotification({
        user_id: partner["user_id"],
        url: notificationUrl,
        timestamp: currentDate,
        message: notificationmsg,
        status: 1,
        from_id: userId,
      });
      let relationManagerids = await Admin.getAllRelationManagerId(partner_id);

      // Alert assigned user of updation
      if (!empty(relationManagerids)) {
        for (let eachid of relationManagerids) {
          await Admin.incrementField(eachid, "noti_count", 1);
          await Admin.addNotification({
            user_id: eachid,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationmsg,
            status: 1,
            from_id: userId,
          });
        }
      }

      let adminIds = await Admin.getAllAdminIds();
      for (let adminId of adminIds) {
        await Admin.incrementField(adminId, "noti_count", 1);
        await Admin.addNotification({
          user_id: adminId,
          url: notificationUrl,
          message: notificationmsg,
          from_id: userId,
          timestamp: currentDate,
          status: 1,
        });
      }
      let adminEmails = await Admin.getAllAdminEmails();
      let adminSubject = portalName + " -  Onboarding ";
      let adminWelcome = "Hello ! Admin" + ",";
      let admin_email_content = `The Onboarding stage ${stage[0]["name"]} of <strong> ${partner["name"]} </strong> hsa been approved.`;
      let adminMessage = onboardTemplate();
      adminMessage = adminMessage.replace("[emailContent]", admin_email_content);
      adminMessage = adminMessage.replace("[CONTENT]", adminWelcome);
      // adminMessage = adminMessage.replace("[NAME]", user["username"]);
      // adminMessage = adminMessage.replace("[PASSWORD]", values.password);
      console.log("$$$$$$$$$$$$$$$nush", stage);
      adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
      for (let row of adminEmails) {
        console.log("$$$$$$$$$$$$$$$nush", row);
        // const msg = {
        //   to: row,
        //   from: "nushara@skyniche.com",
        //   subject: adminSubject,
        //   text: adminSubject,
        //   html: adminMessage,
        // };
        // sgMail
        //   .send(msg)
        //   .then(() => {
        //     console.log("Email sent");
        //   })
        //   .catch((error) => {
        //     console.error(error);
        //   });

        const mailOptions = {
          to:  row , 
          from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
          subject: adminSubject,
          text: adminSubject,
          html: adminMessage,
        }
        try {
          if(SEND_EMAIL){
          await transporter.sendMail(mailOptions);
          console.log('Email sent');
          }
        } catch (error) {
          console.error('##########Err', error);
         
        }
      }

      let Subject =
        portalName + `Your onboarding stage  ${stage[0]["name"]} has been approved `;
      let Welcome = "Hello ! " + partner["name"] + ",";
      let relation_email_content =
        " The verification of the onboarding stage " +
        stage[0]["name"] +
        " has been completed. Please check your dashboard to proceed with the next stage.";
      let relationMessage = onboardTemplate();
      adminMessage = adminMessage.replace(
        "[emailContent]",
        relation_email_content
      );
      adminMessage = adminMessage.replace("[CONTENT]", Welcome);
      // adminMessage = adminMessage.replace("[NAME]", user["username"]);
      // adminMessage = adminMessage.replace("[PASSWORD]", values.password);
      adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
      // const msg = {
      //   to: partner['email'],
      //   from: "nushara@skyniche.com",
      //   subject: Subject,
      //   text: Subject,
      //   html: Welcome,
      // };
      // sgMail
      //   .send(msg)
      //   .then(() => {
      //     console.log("Email sent");
      //   })
      //   .catch((error) => {
      //     console.error(error);
      //   });

      const mailOptions = {
        to: partner['email'],
        from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
        subject: Subject,
        text: Subject,
        html: Welcome,
      }
      try {
        if(SEND_EMAIL){
        await transporter.sendMail(mailOptions);
        console.log('Email sent');
        }
      } catch (error) {
        console.error('##########Err', error);
       
      }
      // next stage
      let nextStage = await OnboardWorkFlowStages.getnextStage(
        partner_id,
        workflowId
      );
      if (!empty(nextStage)) {
        let nextpartnerStage = {};
        if (nextStage["stage_type"] != 7) {
          nextpartnerStage["partner_id"] = partner_id;
          nextpartnerStage["workflow_id"] = workflowId;
          nextpartnerStage["stage_id"] = nextStage["id"];
          nextpartnerStage["stage_type"] = nextStage["stage_type"];
          nextpartnerStage["stage_submit"] = 0;
          nextpartnerStage["position_order"] = nextStage["position_order"];
          nextpartnerStage["timestamp"] = currentDate;
          nextpartnerStage["updated_on"] = currentDate;
          nextpartnerStage["added_by"] = userId;
          nextpartnerStage["status"] = 0;
          let nextpartnerStageId = await PartnerStage.addPartnerstage(
            nextpartnerStage
          );
        }
        else {
          while (nextStage["stage_type"] == 7) {
            if (!empty($nextStage["partner_type"])) {
              await Clients.updateClient(
                partner_id,
                (partner_type = nextStage["partner_type"])
              );
            }
            if (!empty($nextStage["group_ids"])) {
              let partnerGroup = [];
              if (!empty(nextStage["group_ids"])) {
                for (let groupid of nextStage["group_ids"]) {
                  if (!(await Onboard.ispartnerStages(partner_id, groupid))) {
                    let group = {};
                    group["partner_id"] = partner_id;
                    group["group_id"] = groupid;
                    group["timestamp"] = currentDate;
                    group["added_by"] = userId;
                    group["status"] = 1;
                    partnerGroup = group;
                  }
                  let partnerGrpid = await ParrtnerGroup.batchInsertpartnergroup(
                    partnerGroup
                  );
                }
              }
            }
            if (!empty(nextStage["relationship_managers"])) {
              let partnerTeamMember = [];
              if (!empty(nextStage["relationship_managers"])) {
                for (let teamId of nextStage["relationship_managers"]) {
                  if (
                    !(await Onboard.ispartnerteamMemberExist(partnerId, stageId))
                  ) {
                    let teamMember = {};
                    teamMember["partner_id"] = partnerId;
                    teamMember["team_id"] = teamId;
                    teamMember["timestamp"] = currentDate;
                    teamMember["added_by"] = userId;
                    teamMember["status"] = 1;
                    partnerTeamMember = teamMember;
                  }
                  //in this batch_insert_partner_team is not created
                  let partnerteamId = await ParrtnerGroup.batchInsertpartnergroup(
                    partnerTeamMember
                  );
                }
              }
            }
            nextpartnerStage["partner_id"] = partnerId;
            nextpartnerStage["workflow_id"] = workflowId;
            nextpartnerStage["stage_id"] = nextStage["id"];
            nextpartnerStage["stage_type"] = nextStage["stage_type"];
            nextpartnerStage["position_order"] = nextStage["position_order"];
            nextpartnerStage["timestamp"] = currentDate;
            nextpartnerStage["updated_on"] = currentDate;
            nextpartnerStage["added_by"] = userId;
            nextpartnerStage["status"] = 1;
            nextpartnerStageId = await PartnerStage.addPartnerstage(
              nextpartnerStage
            );
            nextStage = await OnboardWorkFlowStages.getnextStage(
              partnerId,
              workflowId
            );
          }
          if (nextStage['stage_type'] != 7 && !empty(nextStage['id'])) {
            nextpartnerStage['partner_id'] = partnerId;
            nextpartnerStage['workflow_id'] = workflowId;
            nextpartnerStage['stage_id'] = nextStage['id'];
            nextpartnerStagee['stage_type'] = nextStage['stage_type'];
            nextpartnerStage['stage_submit'] = 0;
            nextpartnerStage['position_order'] = nextStage['position_order'];
            nextpartnerStage['timestamp'] = currentDate
            nextpartnerStage['updated_on'] = currentDate
            nextpartnerStage['added_by'] = userId
            nextpartnerStage['status'] = 0;
            nextpartnerStageId = await PartnerStage.addPartnerstage(
              nextpartnerStage
            );
          }
        }
      }
      // return
      res.send({

        msg: "data submitted successfully", status: 1
      })
    }
    else {

      let data = {}
      let partnerstage = await Onboard.getpartnerStageByid(partnerStage_id);
      console.log("######################", partnerstage[0]);
      data['partnerstage'] = partnerstage
      data['states'] = await Admin.getAllStates();
      data['process_url'] = 'review';
      data['stage'] = await OnboardWorkFlowStages.getnextStage(partnerstage[0]['partner_id'], partnerstage[0]['workflow_id'], partnerstage[0]['stage_id']);
      console.log("%%%%%%%%%Nush", data['stage']);
      if (data['stage']) {
        res.send({
          data,
          msg: "data"
        })
      }
    }

  } catch (error) {
    console.log("server error" + error);
  }
};
const teamProcess = async (req, res) => {
  try {
    const { userId, userType, values } = req.body;
    let currentDate = Math.round(moment().valueOf() / 1000);
    let data = {};
    data["partner"] = await Admin.getTeamByUserId(userId);
    data["partner"] = data["partner"][0]
    if (empty(data["partner"])) {
      return;
    }
    data["completed"] = 0;
    data["process_url"] = "process-team";
    console.log("######", data['partner']);
    let teamId = data["partner"]["id"];

    data["workflows"] = await Onboard.getOnboardingWorkflows(
      teamId,
      data["partner"]["workflows"],
      1
    );
    console.log("######Nushhhhhhhhh", data["workflows"]);
    if (empty(data["partner"]["workflows"])) {
      console.log("######NushhhhhhhhhMaillllllllll", data['partner']);
    }
    console.log("######NushhhhhhhhhMaillllllllll", data['partner']['onboard_complete'])
    if(data['partner']['onboard_complete']==0){
      if (empty(data["workflows"]) && (await Onboard.isTeamStages(teamId))) {
        data["completed"] = 1;
        console.log("Hifi");
        if (!(await Admin.isOnboardComplete(teamId, "staff_members"))) {
          await Team.updateTeam(teamId, { onboard_complete: 1 });
        }
        console.log("Hifi",!(await Admin.isOnboardComplete(teamId, "staff_members")));
        let adminEmails = await Admin.getAllAdminEmails();
        let adminSubject = portalName + " -  Onboarding completed";
        let adminWelcome = "Hello ! Admin" + ",";
        let admin_email_content = `Team member ${data["partner"]["first_name"]} has been completed the onboarding.`;
        let adminEmailContentNext="All required documents and necessary requirements have been submitted and processed."
        let adminMessage = onboardTemplate();
        adminMessage = adminMessage.replace("[emailContent]",admin_email_content);
        adminMessage = adminMessage.replace("[emailContentNext]",adminEmailContentNext);
        adminMessage = adminMessage.replace("[CONTENT]", adminWelcome);
      

        adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
        for (const row of adminEmails) {
          console.log("$$$$$$$$$$$$$$$nush", row);
          // const msg = {
          //   to: row,
          //   from: "nushara@skyniche.com",
          //   subject: adminSubject,
          //   text: adminSubject,
          //   html: adminMessage,
          // };
          // sgMail
          //   .send(msg)
          //   .then(() => {
          //     console.log("Email sent");
          //   })
          //   .catch((error) => {
          //     console.error(error);
          //   });

          const mailOptions = {
            to: row,
            from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
            subject: adminSubject,
            text: adminSubject,
            html: adminMessage,
          }
          try {
            if(SEND_EMAIL){
            await transporter.sendMail(mailOptions);
            console.log('Email sent');
            }
          } catch (error) {
            console.error('##########Err', error);
           
          }
        }
        let clientMessage = onboardTemplate();
        let subject="Congratulations! You're Onboarded 🚀"
        let welcomeMsg = "Hello ! " +data["partner"]['first_name']+",";
        let email_content = `We're happy to inform you that you have successfully completed the onboarding process! 🎉`;
        let emailContentNext=  `Thank you for choosing ${portalName}. We look forward to a successful collaboration.`
        clientMessage = clientMessage.replace("[emailContent]",email_content);
        clientMessage = clientMessage.replace("[emailContentNext]",emailContentNext);
        clientMessage = clientMessage.replace("[CONTENT]", welcomeMsg);
        

        clientMessage = clientMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
        
          
          // const msg = {
          //   to: data['partner']['email'],
          //   from: "nushara@skyniche.com",
          //   subject: subject,
          //   text: adminSubject,
          //   html: clientMessage,
          // };
          // sgMail
          //   .send(msg)
          //   .then(() => {
          //     console.log("Email sent");
          //   })
          //   .catch((error) => {
          //     console.error(error);
          //   });

          const mailOptions = {
            to: data['partner']['email'],
            from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
            subject: subject,
            text: adminSubject,
            html: clientMessage,
          }
          try {
            if(SEND_EMAIL){
            await transporter.sendMail(mailOptions);
            console.log('Email sent');
            }
          } catch (error) {
            console.error('##########Err', error);
           
          }
      }
   }
    ////////
    let stage = [];
    if (!empty(values)) {
      let partner_stage_id = req.body.partnerStage_id;
      let workflow_id = req.body.workflow_id;
      let stage_id = req.body.stage_id;
      let stage_type = req.body.stage_type;
      let position_order = req.body.position_order;
      let stage_submit = req.body.stage_submit;
      let partner_stage_status = req.body.partnerStageStatus;
      console.log("Enter to submit");
      if ( empty(partner_stage_id) && !empty(await Onboard.isTeamStageExistThenId(teamId, stage_id))) {
        partner_stage_id = await Onboard.isTeamStageExistThenId(
          teamId,
          stage_id
        );
      }
      console.log("partner_stage_id",partner_stage_id);
      if (!empty(partner_stage_id)) {
        let currentpartnerStage = await Onboard.getTeamStagebyId(
          partner_stage_id
        );
        if (!empty(currentpartnerStage)) {
          if (
            currentpartnerStage == 1 &&
            currentpartnerStage["stage_submit"] == 1
          ) {
            return;
          }
        }
      }
      let partnerStage = {}
      if (empty(partner_stage_id)) {
        console.log("Empty then  ****************");
        partnerStage['team_id'] = teamId;
        partnerStage['workflow_id'] = workflow_id;
        partnerStage['stage_id'] = stage_id;
        partnerStage['stage_type'] = stage_type;
        partnerStage['position_order'] = position_order;
        partnerStage['stage_submit'] = stage_submit;
        partnerStage['timestamp'] = currentDate;
        partnerStage['updated_on'] = currentDate;
        partnerStage['added_by'] = userId;
        partnerStage['status'] = partner_stage_status;
        partner_stage_id = await TeamStages.addTeamStage(partnerStage)
      }
      else {
        partnerStage['updated_on'] = currentDate;
        partnerStage['stage_submit'] = stage_submit;
        partnerStage['status'] = partner_stage_status;
        await TeamStages.updateTeamstage(partner_stage_id, partnerStage)
      }

      if (partner_stage_status == 0 && stage_submit == 1) {
        let stageData = await Onboard.getTeamStagebyId(partner_stage_id)
        let adminEmails = await Admin.getAllAdminEmails()
        let adminSubject = portalName + `- .${stageData['name']}. Approval`
        let name = 'Hello! Admin,'
        let content = `${data['partner']['first_name']} ${''} ${data['partner']['last_name']}. has completed the stage <strong>. ${stageData['name']}.</strong> and waiting for your approval.`
        let adminMessage = activateProfile();
        adminMessage = adminMessage.replace(
          "[emailContent]",
          admin_email_content
        );
        adminMessage = adminMessage.replace("[CONTENT]", adminWelcome);
        // adminMessage = adminMessage.replace("[NAME]", user["username"]);
        // adminMessage = adminMessage.replace("[PASSWORD]", values.password);
        adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
        for (const row of adminEmails) {
          console.log("$$$$$$$$$$$$$$$nush", row);
          // const msg = {
          //   to: row,
          //   from: "nushara@skyniche.com",
          //   subject: adminSubject,
          //   text: adminSubject,
          //   html: adminMessage,
          // };
          // sgMail
          //   .send(msg)
          //   .then(() => {
          //     console.log("Email sent");
          //   })
          //   .catch((error) => {
          //     console.error(error);
          //   });

          const mailOptions = {
            to: row,
            from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
            subject: adminSubject,
            text: adminSubject,
            html: adminMessage,
          }
          try {
            if(SEND_EMAIL){
            await transporter.sendMail(mailOptions);
            console.log('Email sent');
            }
          } catch (error) {
            console.error('##########Err', error);
           
          }
        }
        //notification
        let notificationUrl = "process"
        let notificationMsg = admin_email_content
        let adminId = await Admin.getAllAdminIds();
        for (let eachAdminId of adminId) {
          Admin.incrementField(eachAdminId, "noti_count", 1);
          Admin.addNotification({
            user_id: eachAdminId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          });
        }

      }
      if (partner_stage_status == 1 && stage_submit == 1) {
        let nextStage = await OnboardWorkFlowStages.getnextStage(teamId, workflow_id, 0, 1)
        let nextPartnerStage = {}
        if (!empty(nextStage)) {
          if (nextStage['stage_type'] == 7) {
            nextPartnerStage['team_id'] = teamId;
            nextPartnerStage['workflow_id'] = workflow_id;
            nextPartnerStage['stage_id'] = nextStage['id'];
            nextPartnerStage['stage_type'] = nextStage['stage_type'];
            nextPartnerStage['position_order'] = nextStage['position_order'];
            nextPartnerStage['stage_submit'] = 0;
            nextPartnerStage['timestamp'] = currentDate;
            nextPartnerStage['updated_on'] = currentDate;
            nextPartnerStage['added_by'] = userId;
            nextPartnerStage['status'] = 0;
            let nextPartnerStageId = await TeamStages.addTeamStage(nextPartnerStage)
          }
        }
      }
      let stage = await OnboardWorkFlowStages.getnextStage(teamId, workflow_id, stage_id, 1)
      if (stage['stage_type'] == 1) {
    
       
        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPP");
        let field_template_i = 0;
        const partner_fields = [];
        let fieldTemplates = values.fieldTemplates
        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPP", fieldTemplates);
        let partnerFields = []
        let partnerField = {}
        const field_value_pairs = [];
        let valueData = removeNull(fieldTemplates)
        for (const [key, value] of Object.entries(valueData)) {
          if(!empty(value)){
           
          if (value && typeof value === 'object' && "value" in value) {
            field_value_pairs.push({ "field_id": value.field_id, "value": value.value,team_id: teamId,updated_on: moment().unix(),added_by: userId, status: 1,});
          } else if (value && Array.isArray(value) && value.every(item => typeof item === 'object' && "value" in item)) {
            for (const item of value) {
              if(!empty(item.value)){
              field_value_pairs.push({ "field_id": item.field_id, "value": item.value,team_id: teamId,updated_on: moment().unix(),added_by: userId, status: 1,});
              }
            }
          }
        }
        }
        console.log("XXXXXXXXXXXXXXXXXX", field_value_pairs);
        if (!empty(field_value_pairs)) {
          await Onboard.updateBatchData("team_custom_fields", field_value_pairs);
        }
        let requested_document_i = 0;
        const partner_requested_documents = [];

        if (stage.requested_documents && stage.requested_documents.length > 0) {
          for (const requested_document of stage.requested_documents) {
            // if(!empty(req.body.requested_document_hidden_+${requested_document.id})){
            //     const requested_document_hidden_value = req.body.`requested_document_hidden_${requested_document.id}`;
            // }

            partner_requested_documents[requested_document_i] = {
              id:
                requested_document_hidden_value ||
                requested_document.partner_document_id ||
                null,
              partner_id: partnerId,
              document_id: requested_document.id,
              document_type: 1,
              onboarding: 1,
              issue_date: moment(
                this.input.post(
                  `requested_document_issue_date_${requested_document.id}`
                )
              ).unix(),
              expiry_date: moment(
                this.input.post(
                  `requested_document_expiry_date_${requested_document.id}`
                )
              ).unix(),
              updated_on: moment().unix(),
              added_by: userId,
              status: 1,
            };

            const files =
              this.input.files[`requested_document_${requested_document.id}`];
            if (
              files &&
              files.name &&
              files.name.length > 0 &&
              files.name[0] !== ""
            ) {
              const uploaded = await onboardModel.doUpload(
                `requested_document_${requested_document.id}`,
                "partners"
              );

              if (uploaded.error) {
                this.session.flash("error_msg", uploaded.error);
                this.redirect("admin/onboard/process");
                return;
              } else if (uploaded.file_name !== "") {
                partner_requested_documents[requested_document_i].file_name =
                  uploaded.file_name;
              }
            } else {
              partner_requested_documents[requested_document_i].file_name =
                null;
            }

            requested_document_i++;
          }
        }

        if (partner_requested_documents.length > 0) {
          await onboardModel.updateBatchData(
            "partner_documents",
            partner_requested_documents
          );
        }

        //
      }

      else if (stage['stage_type'] == 5) {

        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPP");
        let field_template_i = 0;
        const partner_fields = [];
        let fieldTemplates = values.fieldTemplates
        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPP", fieldTemplates);
        let partnerFields = []
        let partnerField = {}
        const field_value_pairs = [];
        let valueData = removeNull(fieldTemplates)
        for (const [key, value] of Object.entries(valueData)) {
          if(!empty(value)){
            if (value && typeof value === 'object' && "value" in value) {
              field_value_pairs.push({ "field_id": value.field_id, "value": value.value,team_id: teamId,updated_on: moment().unix(),added_by: userId, status: 1,});
            } else if (value && Array.isArray(value) && value.every(item => typeof item === 'object' && "value" in item)) {
              for (const item of value) {
                if(!empty(item.value)){
                field_value_pairs.push({ "field_id": item.field_id, "value": item.value,team_id: teamId,updated_on: moment().unix(),added_by: userId, status: 1,});
                }
              }
            }
          }
          
        }
        console.log("XXXXXXXXXXXXXXXXXX", field_value_pairs);
        if (field_value_pairs.length > 0) {
          await Onboard.updateBatchData(
            "team_questionnaires",
            field_value_pairs
          );
        }
      }


    }
    console.log("%%%%%%%%%%%%%%Nushhhhhh", data["workflows"]);
    if (!empty(data["workflows"])) {
      console.log("%%%%%%%%%%%%%%Nushhhhhh", data["workflows"]);
      for (let eachworkflow of data["workflows"]) {
        data["stage"] = await OnboardWorkFlowStages.getnextStage(
          teamId,
          eachworkflow["id"],0,1
        );
        console.log("stage$$$$$$$$$$$$", data["stage"]);
        if (!empty(data["stage"])) {

          break;
        }
      }
    }
    data["states"] = await Admin.getAllStates();
    if (!empty(stage) && !empty(stage["message"]) && !empty(partner_stage_status) && stage["stage_submit"] == 1) {
      data["stage_submit"] = stage["stage_submit"];
      data["stage"] = stage;
      //   $this->load->view('admin/onboard/onboard-views/auto-onboarding',$data);
      return;
    }
    console.log("$$$$$$$$$$$$$$$$$$", data['stage']);
    if (!empty(data['stage'])) {
      if (!empty(data['stage']['partner_stage_id'])) {
        console.log("Anavia riyassssssssssssss", data['stage']['partner_stage_id']);
        let stagedata = await Onboard.getTeamStagebyId(data['stage']['partner_stage_id'])
        console.log("Anavia riyassssssssssssss", stagedata);
        if (stagedata[0]['stage_submit'] == 1) {
          data['stage_submit'] = stagedata[0]['stage_submit']
          //       $this->load->view('admin/onboard/onboard-views/no-onboarding',$data);
          console.log("Anavia riyassssssssssssss ohhhhhhhhhhh");
          res.send({ manual: 1, data, status: 1 });
          return
        }
      }

      let currentProcessingStageData = data["stage"];
      let currentProcessingPartnerId = teamId;

      res.send({ stage: data["stage"]["stage_type"], data, status: 1 });
    } 
    else if (await Onboard.isTeamStages(teamId)) {
      console.log("$$$$$$$$$$$$$$$$Nushhhhhhhhhhhhhh");
      res.send({ onboardCompleted: 1, data, status: 1 });
    
      // redirect('admin/onboard/process');
    } else {
      // $this->load->view('admin/onboard/onboard-views/no-onboarding',$data);
    }
  } catch (error) {
    console.log(error, "error in team process");
    res.status(500).send("error in team process" + error)
  }
};
const reviewTeam = async (req, res) => {
  try {
    const {
      userId,
      partnerStage_id,
      workflowId,
      stageId,
      stageType,
      positionOrder,
      partnerId,
      stage_submit
    } = req.body;
    console.log("###Nushhhhhhhhhhhhhhh", stage_submit);
    if (!empty(stage_submit)) {
      console.log("###Nushhhhhhhhhhhhhhh");
      let currentDate = Math.round(moment().valueOf() / 1000);
      let partnerStage = {};
      partnerStage["approved_by"] = userId
      partnerStage["approved_on"] = currentDate,
        partnerStage["status"] = 1,
        await PartnerStage.updateTeamstage(partnerStage_id, partnerStage);



      //notification
      let stage = await Onboard.getpartnerStageByid(partnerStage_id);
      let partner = await Team(partnerId);
      let notificationmsg = `The Onboarding stage ${stage["name"]} of <strong> ${partner["name"]} </strong> hsa been approved.`;
      let notificationUrl = `onboard/view/${workflowId}`;

      // Alert assigned user of updation
      Admin.incrementField(partner["user_id"], "noti_count", 1);
      Admin.addNotification({
        user_id: partner["user_id"],
        url: notificationUrl,
        timestamp: currentDate,
        message: notificationmsg,
        status: 1,
        from_id: userId,
      });
      let relationManagerids = await Admin.getAllRelationManagerId(partnerId);
      // Alert assigned user of updation
      for (let eachid of relationManagerids) {
        await Admin.incrementField(eachid, "noti_count", 1);
        await Admin.addNotification({
          user_id: eachid,
          url: notificationUrl,
          timestamp: currentDate,
          message: notificationmsg,
          status: 1,
          from_id: userId,
        });
      }
      let adminIds = await Admin.getAllAdminIds();
      for (let adminId of adminIds) {
        await Admin.incrementField(adminId, "noti_count", 1);
        await Admin.addNotification({
          user_id: adminId,
          url: notificationUrl,
          message: notificationmsg,
          from_id: userId,
          timestamp: currentDate,
          status: 1,
        });
      }
      let adminEmails = await Admin.getAllAdminEmails();
      let adminSubject = portalName + " -  Onboarding completed";
      let adminWelcome = "Hello ! Admin" + ",";
      let admin_email_content = `${data["partner"]["name"]}." has completed the onboarding.`;
      let adminMessage = activateProfile();
      adminMessage = adminMessage.replace("[emailContent]", admin_email_content);
      adminMessage = adminMessage.replace("[CONTENT]", adminWelcome);
      adminMessage = adminMessage.replace("[NAME]", user["username"]);
      adminMessage = adminMessage.replace("[PASSWORD]", values.password);
      adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
      for (const row of adminEmails) {
        console.log("$$$$$$$$$$$$$$$nush", row);
        // const msg = {
        //   to: row,
        //   from: "nushara@skyniche.com",
        //   subject: adminSubject,
        //   text: adminSubject,
        //   html: adminMessage,
        // };
        // sgMail
        //   .send(msg)
        //   .then(() => {
        //     console.log("Email sent");
        //   })
        //   .catch((error) => {
        //     console.error(error);
        //   });

        const mailOptions = {
          to: row,
          from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
          subject: adminSubject,
          text: adminSubject,
          html: adminMessage,
        }
        try {
          if(SEND_EMAIL){
          await transporter.sendMail(mailOptions);
          console.log('Email sent');
          }
        } catch (error) {
          console.error('##########Err', error);
         
        }
      }

      let Subject =
        portalName + `Your onboarding stage  ${stage["name"]} has been approved `;
      let Welcome = "Hello ! " + partner["name"] + ",";
      let relation_email_content =
        " The verification of the onboarding stage " +
        stage["name"] +
        " has been completed. Please check your dashboard to proceed with the next stage.";
      let relationMessage = activateProfile();
      adminMessage = adminMessage.replace(
        "[emailContent]",
        relation_email_content
      );
      adminMessage = adminMessage.replace("[CONTENT]", Welcome);
      adminMessage = adminMessage.replace("[NAME]", user["username"]);
      adminMessage = adminMessage.replace("[PASSWORD]", values.password);
      adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
      // const msg = {
      //   to: row,
      //   from: "nushara@skyniche.com",
      //   subject: Subject,
      //   text: Subject,
      //   html: Welcome,
      // };
      // sgMail
      //   .send(msg)
      //   .then(() => {
      //     console.log("Email sent");
      //   })
      //   .catch((error) => {
      //     console.error(error);
      //   });

      const mailOptions = {
        to: row,
        from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
        subject: Subject,
        text: Subject,
        html: Welcome,
      }
      try {
        if(SEND_EMAIL){
        await transporter.sendMail(mailOptions);
        console.log('Email sent');
        }
      } catch (error) {
        console.error('##########Err', error);
       
      }
      // next stage
      let nextStage = await OnboardWorkFlowStages.getnextStage(
        partnerId,
        workflowId,
        
      );
      if (!empty(nextStage)) {
        let nextpartnerStage = {};
        if (nextStage["stage_type"] != 7) {
          nextpartnerStage["partner_id"] = partnerId;
          nextpartnerStage["workflow_id"] = workflowId;
          nextpartnerStage["stage_id"] = nextStage["id"];
          nextpartnerStage["stage_type"] = nextStage["stage_type"];
          nextpartnerStage["stage_submit"] = 0;
          nextpartnerStage["position_order"] = nextStage["position_order"];
          nextpartnerStage["timestamp"] = currentDate;
          nextpartnerStage["updated_on"] = currentDate;
          nextpartnerStage["added_by"] = userId;
          nextpartnerStage["status"] = 0;
          let nextpartnerStageId = await PartnerStage.addPartnerstage(
            nextpartnerStage
          );
        }
        else {
          while (nextStage["stage_type"] == 7) {
            if (!empty($nextStage["partner_type"])) {
              await Clients.updateClient(
                partnerId,
                (partner_type = nextStage["partner_type"])
              );
            }
            if (!empty($nextStage["group_ids"])) {
              let partnerGroup = [];
              if (!empty(nextStage["group_ids"])) {
                for (let groupid of nextStage["group_ids"]) {
                  if (!(await Onboard.ispartnerStages(partnerId, groupid))) {
                    let group = {};
                    group["partner_id"] = partnerId;
                    group["group_id"] = groupid;
                    group["timestamp"] = currentDate;
                    group["added_by"] = userId;
                    group["status"] = 1;
                    partnerGroup = group;
                  }
                  let partnerGrpid = await ParrtnerGroup.batchInsertpartnergroup(
                    partnerGroup
                  );
                }
              }
            }
            if (!empty(nextStage["relationship_managers"])) {
              let partnerTeamMember = [];
              if (!empty(nextStage["relationship_managers"])) {
                for (let teamId of nextStage["relationship_managers"]) {
                  if (
                    !(await Onboard.ispartnerteamMemberExist(partnerId, stageId))
                  ) {
                    let teamMember = {};
                    teamMember["partner_id"] = partnerId;
                    teamMember["team_id"] = teamId;
                    teamMember["timestamp"] = currentDate;
                    teamMember["added_by"] = userId;
                    teamMember["status"] = 1;
                    partnerTeamMember = teamMember;
                  }
                  //in this batch_insert_partner_team is not created
                  let partnerteamId = await ParrtnerGroup.batchInsertpartnergroup(
                    partnerTeamMember
                  );
                }
              }
            }
            nextpartnerStage["partner_id"] = partnerId;
            nextpartnerStage["workflow_id"] = workflowId;
            nextpartnerStage["stage_id"] = nextStage["id"];
            nextpartnerStage["stage_type"] = nextStage["stage_type"];
            nextpartnerStage["position_order"] = nextStage["position_order"];
            nextpartnerStage["timestamp"] = currentDate;
            nextpartnerStage["updated_on"] = currentDate;
            nextpartnerStage["added_by"] = userId;
            nextpartnerStage["status"] = 1;
            nextpartnerStageId = await PartnerStage.addPartnerstage(
              nextpartnerStage
            );
            nextStage = await OnboardWorkFlowStages.getnextStage(
              partnerId,
              workflowId
            );
          }
          if (nextStage['stage_type'] != 7 && !empty(nextStage['id'])) {
            nextpartnerStage['partner_id'] = partnerId;
            nextpartnerStage['workflow_id'] = workflowId;
            nextpartnerStage['stage_id'] = nextStage['id'];
            nextpartnerStagee['stage_type'] = nextStage['stage_type'];
            nextpartnerStage['stage_submit'] = 0;
            nextpartnerStage['position_order'] = nextStage['position_order'];
            nextpartnerStage['timestamp'] = currentDate
            nextpartnerStage['updated_on'] = currentDate
            nextpartnerStage['added_by'] = userId
            nextpartnerStage['status'] = 0;
            nextpartnerStageId = await PartnerStage.addPartnerstage(
              nextpartnerStage
            );
          }
        }
      }
      // return
      res.send({
        data,
        msg: "data submitted successfully"
      })
    }
    else {

      let data = {}
      let teamStage = await Onboard.getTeamStagebyId(partnerStage_id);

      data['partnerstage'] = teamStage
      data['states'] = await Admin.getAllStates();
      data['process_url'] = 'review';
      data['stage'] = await OnboardWorkFlowStages.getnextStage(teamStage[0]['partner_id'], teamStage[0]['workflow_id'], teamStage[0]['stage_id']);
      if (data['stage']) {
        res.send({
          data,
          msg: "data"
        })
      }
    }

  } catch (error) {
    console.log("server error" + error);
  }
};
const rfqOnboardProcess = async (req, res) => {
  try {
    let { userId, userType, currentStageId, currentPartnerId, values,requestId } =
      req.body;
    let currentDate = Math.round(moment().valueOf() / 1000);
    let data = {};
    data["partner"] = await Admin.getPartnerByUserId(userId);
    let rfqDetails = await Request.getAllRequests(requestId, userId, userType)
    
    if (empty(data["partner"])) {
      return;
    }
   
    data["completed"] = 0;
    data["process_url"] = "process";
    let partnerId = data["partner"]["id"];
    data["workflows"] = await Onboard.getOnboardingWorkflows(
      partnerId,
      rfqDetails?.data[0]["workflows"],0,1,requestId
    );

    if (empty(data["partner"]["workflows"])) {
      // $this->load->view('admin/onboard/onboard-views/no-onboarding',$data);
      res.send({ status: 4, msg: "No onboarding", data });
    }
    let partnerStageRes = await Onboard.isRfqStages(requestId);
    console.log("###########nnnn", partnerStageRes);
    console.log("###########nnnn",  rfqDetails?.data[0]["workflows"]);
  
    console.log("###########nnnn", data["workflows"]);
    let stage = [];
    
    if (empty(data["workflows"]) && partnerStageRes) {
      console.log("NNNNNNNNNNNNNNN");
      
      data["completed"] = 1;
      let isOnboardComplete = await Admin.isOnboardComplete(
        requestId,
        "requests"
      );
      console.log("############Onboard",isOnboardComplete);
      if (!isOnboardComplete) {
        console.log("############Onboarding111111",partnerId);
        let updatedpartner = await Request.updateRequets( requestId,{ onboard_complete: 1 });

        let adminEmails = await Admin.getAllAdminEmails();
        let adminSubject = portalName + " -  Onboarding completed";
        let adminWelcome = "Hello ! Admin" + ",";
        let admin_email_content = `${data["partner"]["name"]} has been completed the RFQ onboarding.`;
        let adminEmailContentNext="All required documents and necessary requirements have been submitted and processed."
        let adminMessage = onboardTemplate();
        adminMessage = adminMessage.replace("[emailContent]",admin_email_content);
        adminMessage = adminMessage.replace("[emailContentNext]",adminEmailContentNext);
        adminMessage = adminMessage.replace("[CONTENT]", adminWelcome);
       

        adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
        for (const row of adminEmails) {
          console.log("$$$$$$$$$$$$$$$nush", row);
          // const msg = {
          //   to: row,
          //   from: "nushara@skyniche.com",
          //   subject: adminSubject,
          //   text: adminSubject,
          //   html: adminMessage,
          // };
          // sgMail
          //   .send(msg)
          //   .then(() => {
          //     console.log("Email sent");
          //   })
          //   .catch((error) => {
          //     console.error(error);
          //   });

          const mailOptions = {
            to: row,
            from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
            subject: adminSubject,
            text: adminSubject,
            html: adminMessage,
          }
          try {
            if(SEND_EMAIL){
            await transporter.sendMail(mailOptions);
            console.log('Email sent');
            }
          } catch (error) {
            console.error('##########Err', error);
           
          }
        }
        let clientMessage = onboardTemplate();
        let subject="Congratulations! You're Onboarded 🚀"
        let welcomeMsg = "Hello ! " +data["partner"]['name']+",";
        let email_content = `We're happy to inform you that you have successfully completed the onboarding process! 🎉`;
        let emailContentNext=  `Thank you for choosing ${portalName}. We look forward to a successful collaboration.`
        clientMessage = clientMessage.replace("[emailContent]",email_content);
        clientMessage = clientMessage.replace("[emailContentNext]",emailContentNext);
        clientMessage = clientMessage.replace("[CONTENT]", welcomeMsg);
        

        clientMessage = clientMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
        
          
          // const msg = {
          //   to: data['partner']['email'],
          //   from: "nushara@skyniche.com",
          //   subject: subject,
          //   text: adminSubject,
          //   html: clientMessage,
          // };
          // sgMail
          //   .send(msg)
          //   .then(() => {
          //     console.log("Email sent");
          //   })
          //   .catch((error) => {
          //     console.error(error);
          //   });

          const mailOptions = {
            to: data['partner']['email'],
            from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
            subject: subject,
            text: adminSubject,
            html: clientMessage,
          }
          try {
            if(SEND_EMAIL){
            await transporter.sendMail(mailOptions);
            console.log('Email sent');
            }
          } catch (error) {
            console.error('##########Err', error);
           
          }
        
        let relationshipManagerdata = await Admin.getAllRelationshipManagerdata(partnerId);
        console.log("$$$$$$$$$$$$$$$$$$$$$$", relationshipManagerdata);
        if(!empty(relationshipManagerdata)){
          let realtionSubject = portalName + " -  Onboarding completed";
          let relationWelcome = "Hello ! Admin" + ",";
          let relation_email_content = `${relationshipManagerdata["partner"]["name"]}." has completed the onboarding.`;
          let relationMessage = activateProfile();
          adminMessage = adminMessage.replace(
            "[emailContent]",
            relation_email_content
          );
          adminMessage = adminMessage.replace("[CONTENT]", relationWelcome);
          adminMessage = adminMessage.replace("[NAME]", data["partner"]["name"]);
          // adminMessage = adminMessage.replace("[PASSWORD]", values.password);
          adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
          for (const row of relationshipManagerdata) {
            console.log("$$$$$$$$$$$$$$$nush", row);
            // const msg = {
            //   to: row,
            //   from: "nushara@skyniche.com",
            //   subject: realtionSubject,
            //   text: realtionSubject,
            //   html: relationMessage,
            // };
            // sgMail
            //   .send(msg)
            //   .then(() => {
            //     console.log("Email sent");
            //   })
            //   .catch((error) => {
            //     console.error(error);
            //   });

            const mailOptions = {
              to: row,
              from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
              subject: realtionSubject,
              text: realtionSubject,
              html: relationMessage,
            }
            try {
              if(SEND_EMAIL){
              await transporter.sendMail(mailOptions);
              console.log('Email sent');
              }
            } catch (error) {
              console.error('##########Err', error);
             
            }
          }
        }
       
      }
    }
    let partnerStageStatus = req.body.partnerStageStatus
   
    if (!empty(values)) {
      let partnerStageId = req.body.partnerStage_id
      let workflowId = req.body.workflow_id
      let stageId = req.body.stage_id
      let stageType = req.body.stage_type
      let position_order = req.body.position_order
      let stage_submit = req.body.stage_submit
      // let partnerStageStatus = req.body.partnerStageStatus
      let isPartnerExist = await Onboard.isRfqStageExistthenid(partnerId, stageId)
      console.log("$$$$$$$$$$nushannus", isPartnerExist);
      if (empty(partnerStageId) && !isPartnerExist) {
        isPartnerExist;
      }
      if (!empty(partnerStageId)) {
        let currentPartnerStage = await Onboard.getRfqStageByid(
          partnerStageId
        );
        console.log("$$$$$$$$$$nushannus", currentPartnerStage);
        if (!empty(currentPartnerStage)) {
          if (
            currentPartnerStage["status"] == 1 &&
            currentPartnerStage["stage_submit"] == 1
          ) {
            // return
            // redirect('admin/onboard/process');
            res.send({ status: 1, msg: "onboard process", data });
          }
        }
      }
      let partner_stage = {};
      console.log("Hiiiii3", partnerStageId);
      console.log("Hiiiii3", empty(partnerStageId));
      if (empty(partnerStageId)) {
        console.log("####################Manual", stage_submit);
        partner_stage['request_id'] = requestId
        partner_stage['partner_id'] = partnerId
        partner_stage['workflow_id'] = workflowId
        partner_stage['stage_id'] = stageId
        partner_stage['stage_type'] = stageType
        partner_stage['position_order'] = position_order
        partner_stage['stage_submit'] = stage_submit
        partner_stage['timestamp'] = currentDate
        partner_stage['updated_on'] = currentDate
        partner_stage['added_by'] = userId
        partner_stage['status'] = partnerStageStatus
        console.log("####################Manual", partner_stage);
        partnerStageId = await PartnerStage.addRfqStage(partner_stage)
      }
      else {
        console.log("####################Manualup");
        partner_stage['updated_on'] = currentDate
        partner_stage['stage_submit'] = stage_submit
        partner_stage['status'] = partnerStageStatus
        await PartnerStage.updateRfqStage(partnerStageId, partner_stage)
      }
      if (partnerStageStatus == 0 && stage_submit == 1) {
        let stageData = await Onboard.getpartnerStageByid(partnerStageId)
        console.log("####################Manualup", stageData);
        let adminEmails = await Admin.getAllAdminEmails();
        let adminSubject = portalName + " -" + stageData["name"] + "Approval.";
        let adminWelcome = "Hello ! Admin" + ",";
        let admin_email_content = `${data["partner"]["name"]}." has completed the RFQ stage <strong>.${stageData['name']}."</strong> and waiting for your approval`;
        let adminMessage = activateProfile();
        adminMessage = adminMessage.replace(
          "[emailContent]",
          admin_email_content
        );
        adminMessage = adminMessage.replace("[CONTENT]", adminWelcome);
        // adminMessage = adminMessage.replace("[NAME]", user["username"]);
        // adminMessage = adminMessage.replace("[PASSWORD]", values.password);
        adminMessage = adminMessage.replace("[LOGIN_URL]", `${BASE_URL}`);
        for (const row of adminEmails) {
          console.log("$$$$$$$$$$$$$$$nush", row);
          // const msg = {
          //   to: row,
          //   from: "nushara@skyniche.com",
          //   subject: adminSubject,
          //   text: adminSubject,
          //   html: adminMessage,
          // };
          // sgMail
          //   .send(msg)
          //   .then(() => {
          //     console.log("Email sent");
          //   })
          //   .catch((error) => {
          //     console.error(error);
          //   });

          const mailOptions = {
            to: row,
            from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
            subject: adminSubject,
            text: adminSubject,
            html: adminMessage,
          }
          try {
            if(SEND_EMAIL){
            await transporter.sendMail(mailOptions);
            console.log('Email sent');
            }
          } catch (error) {
            console.error('##########Err', error);
           
          }
        }
        //notification
        let notificationUrl = "process"
        let notificationMsg = admin_email_content
        let adminId = await Admin.getAllAdminIds();
        for (let eachAdminId of adminId) {
          Admin.incrementField(eachAdminId, "noti_count", 1);
          Admin.addNotification({
            user_id: eachAdminId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          });
        }
      }
      console.log("partnerStageStatus", partnerStageStatus);
      if (partnerStageStatus == 1 && stage_submit == 1) {
        let nextStage = await OnboardWorkFlowStages.getnextStage(partnerId, workflowId,0,0,1)
       
        if (!empty(nextStage)) {
          let next_partner_stage = {};
          if (nextStage["stage_type"] != 7 && !empty(nextStage["id"])) {
            partner_stage['request_id'] = requestId
            next_partner_stage["partner_id"] = partnerId;
            next_partner_stage["workflow_id"] = workflowId;
            next_partner_stage["stage_id"] = nextStage["id"];
            next_partner_stage["stage_type"] = nextStage["stage_type"];
            next_partner_stage["position_order"] = nextStage["position_order"];
            next_partner_stage["stage_submit"] = 0;
            next_partner_stage["timestamp"] = currentDate;
            next_partner_stage["updated_on"] = currentDate;
            next_partner_stage["added_by"] = userId;
            next_partner_stage["status"] = 0;
            next_partner_stage_id =
              PartnerStage.addRfqStage(next_partner_stage);
          } else {
            while (nextStage["stage_type"] == 7) {
              if (!empty(nextStage["partner_type"])) {
                await Clients.updateClient(
                  nextStage["partner_type"],
                  partnerId
                );
              }

              let partnerGroups = [];
              if (!empty(nextStage["group_ids"])) {
                nextStage.group_ids.forEach(async (group_id) => {
                  if (
                    !(await onboardModel.isPartnerGroupExist(
                      partnerId,
                      group_id
                    ))
                  ) {
                    const group = {
                      partner_id: partnerId,
                      group_id: group_id,
                      timestamp: Math.floor(new Date().getTime() / 1000),
                      added_by: userId, // Assuming 'session' is an object with 'userData' property
                      status: 1,
                    };
                    partnerGroups.push(group);
                    let partnerGroupId = await Group.addPartnerGroup(group);
                  }
                });
              }

              if (nextStage.relationship_managers.length > 0) {
                const partner_team_members = {};

                for (const teamId of nextStage.relationship_managers) {
                  if (
                    !(await onboardModel.isPartnerTeamMemberExist(
                      partnerId,
                      teamId
                    ))
                  ) {
                    const teamMember = {
                      partner_id: partnerId,
                      team_id: teamId,
                      timestamp: Math.floor(new Date().getTime() / 1000),
                      added_by: userId, // Assuming 'session' is an object with 'userData' property
                      status: 1,
                    };
                    partner_team_members.push(teamMember);
                    const partner_team_id = await PartnerStage.addPartnerTeam(
                      teamMember
                    );
                  }
                }
              }
              next_partner_stage["partner_id"] = partnerId;
              next_partner_stage["workflow_id"] = workflowId;
              next_partner_stage["stage_id"] = nextStage["id"];
              next_partner_stage["stage_type"] = nextStage["stage_type"];
              next_partner_stage["position_order"] =
                nextStage["position_order"];
              next_partner_stage["timestamp"] = moment().unix();
              next_partner_stage["updated_on"] == moment().unix();
              next_partner_stage["added_by"] = userId;
              next_partner_stage["status"] = 1;
              let next_partner_stage_id = await PartnerStage.addPartnerstage(
                next_partner_stage
              );
              nextStage = await OnboardWorkFlowStages.getnextStage(
                partnerId,
                workflowId
              );
            }
            if (nextStage['stage_type'] != 7 && !empty(nextStage['id'])) {
              next_partner_stage['partner_id'] = partnerId;
              next_partner_stage['workflow_id'] = workflowId;
              next_partner_stage['stage_id'] = nextStage['id'];
              next_partner_stage['stage_type'] = nextStage['stage_type'];
              next_partner_stage['position_order'] = nextStage['position_order'];
              next_partner_stage['stage_submit'] = 0;
              next_partner_stage['timestamp'] = moment().unix();
              next_partner_stage['updated_on'] = moment().unix();
              next_partner_stage['added_by'] = userId;
              next_partner_stage['status'] = 0;
              next_partner_stage_id = await OnboardWorkFlowStages.getnextStage(partnerId, workflowId,0,0,1,requestId)
            }
          }

        }

      }

      stage = await OnboardWorkFlowStages.getnextStage(partnerId, workflowId, stageId,0,1,requestId);

      if (stage.stage_type === 1) {
        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPP");
        let field_template_i = 0;
        const partner_fields = [];
        let fieldTemplates = values.fieldTemplates
        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPP", fieldTemplates);
        let partnerFields = []
        let partnerField = {}
        const field_value_pairs = [];
        let valueData = removeNull(fieldTemplates)
        for (const [key, value] of Object.entries(valueData)) {  
          console.log("key$$$$$$$$$$$$$$$$",key)
          if (value && typeof value === 'object' && "value" in value) {
            field_value_pairs.push({ "field_id": value.field_id,"field_name":key, "value": value.value,partner_id: partnerId,updated_on: moment().unix(),added_by: userId, request_id: requestId, status: 1,});
          } else if (value && Array.isArray(value) && value.every(item => typeof item === 'object' && "value" in item)) {
            for (const item of value) {
              field_value_pairs.push({ "field_id": item.field_id, "field_name":key,"value": item.value,partner_id: partnerId,updated_on: moment().unix(),added_by: userId, request_id: requestId, status: 1,});
            }
          }
        }
        console.log("XXXXXXXXXXXXXXXXXX", field_value_pairs);
        // if (!empty(fieldTemplates.text)) {
        //   partnerField = {

        //     partner_id: partnerId,
        //     field_id: fieldTemplates.text.field_id,
        //     value: fieldTemplates.text.value,
        //     value: fieldTemplates.text.value,
        //     updated_on: moment().unix(),
        //     added_by: userId,
        //     status: 1,
        //   };
        //   partnerFields.push(partnerField);
        // }
        // if (!empty(fieldTemplates.coverImage)) {
        //   partnerField = {

        //     partner_id: partnerId,
        //     field_id: fieldTemplates.coverImage.field_id,
        //     value: fieldTemplates.coverImage.value,
        //     value: fieldTemplates.coverImage.value,
        //     updated_on: moment().unix(),
        //     added_by: userId,
        //     status: 1,
        //   };
        //   partnerFields.push(partnerField);
        // }
        // if (!empty(fieldTemplates.textarea)) {
        //   partnerField = {

        //     partner_id: partnerId,
        //     field_id: fieldTemplates.textarea.field_id,
        //     value: fieldTemplates.textarea.value,
        //     value: fieldTemplates.textarea.value,
        //     updated_on: moment().unix(),
        //     added_by: userId,
        //     status: 1,
        //   };
        //   partnerFields.push(partnerField);
        // }
        // if (!empty(fieldTemplates.number)) {
        //   partnerField = {

        //     partner_id: partnerId,
        //     field_id: fieldTemplates.number.field_id,
        //     value: fieldTemplates.number.value,
        //     value: fieldTemplates.number.value,
        //     updated_on: moment().unix(),
        //     added_by: userId,
        //     status: 1,
        //   };
        //   partnerFields.push(partnerField);
        // }
        // if (!empty(fieldTemplates.date)) {
        //   partnerField = {

        //     partner_id: partnerId,
        //     field_id: fieldTemplates.date.field_id,
        //     value: fieldTemplates.date.value,

        //     updated_on: moment().unix(),
        //     added_by: userId,
        //     status: 1,
        //   };
        //   partnerFields.push(partnerField);
        // }
        // if (!empty(fieldTemplates.select)) {
        //   partnerField = {

        //     partner_id: partnerId,
        //     field_id: fieldTemplates.select.field_id,
        //     value: fieldTemplates.select.value,
        //     value: fieldTemplates.select.value,
        //     updated_on: moment().unix(),
        //     added_by: userId,
        //     status: 1,
        //   };
        //   partnerFields.push(partnerField);
        // }
        // if (!empty(fieldTemplates.coverImage)) {
        //   partnerField = {

        //     partner_id: partnerId,
        //     field_id: fieldTemplates.coverImage.field_id,
        //     value: fieldTemplates.coverImage.value,
        //     value: fieldTemplates.coverImage.value,
        //     updated_on: moment().unix(),
        //     added_by: userId,
        //     status: 1,
        //   };
        //   partnerFields.push(partnerField);
        // }
        // if (!empty(fieldTemplates.autocomplete)) {
        //   partnerField = {

        //     partner_id: partnerId,
        //     field_id: fieldTemplates.autocomplete.field_id,
        //     value: fieldTemplates.autocomplete.newValue.value,
        //     value: fieldTemplates.autocomplete.newValue.value,
        //     updated_on: moment().unix(),
        //     added_by: userId,
        //     status: 1,
        //   };
        //   partnerFields.push(partnerField);
        // }
        // if (!empty(fieldTemplates.radiogroup)) {
        //   partnerField = {

        //     partner_id: partnerId,
        //     field_id: fieldTemplates.radiogroup.field_id,
        //     value: fieldTemplates.radiogroup.value,
        //     value: fieldTemplates.radiogroup.value,
        //     updated_on: moment().unix(),
        //     added_by: userId,
        //     status: 1,
        //   };
        //   partnerFields.push(partnerField);
        // }
        // if (!empty(fieldTemplates.checkboxgroup)) {
        //   for (let checkbox of fieldTemplates.checkboxgroup) {
        //     partnerField = {

        //       partner_id: partnerId,
        //       field_id: checkbox.field_id,
        //       value: checkbox.value,
        //       updated_on: moment().unix(),
        //       added_by: userId,
        //       status: 1,
        //     };
        //     partnerFields.push(partnerField)
        //   }
        // }
        console.log("############field_value_pairs", partnerFields);
        if (!empty(field_value_pairs)) {
          await Onboard.updateBatchData(
            "rfq_custom_fields",
            field_value_pairs
          );

        }



        let requested_document_i = 0;
        const partner_requested_documents = [];

        if (stage.requested_documents && stage.requested_documents.length > 0) {
          for (const requested_document of stage.requested_documents) {
            // if(!empty(req.body.requested_document_hidden_+${requested_document.id})){
            //     const requested_document_hidden_value = req.body.`requested_document_hidden_${requested_document.id}`;
            // }

            partner_requested_documents[requested_document_i] = {
              id:
                requested_document_hidden_value ||
                requested_document.partner_document_id ||
                null,
              partner_id: partnerId,
              document_id: requested_document.id,
              document_type: 1,
              onboarding: 1,
              issue_date: moment(
                this.input.post(
                  `requested_document_issue_date_${requested_document.id}`
                )
              ).unix(),
              expiry_date: moment(
                this.input.post(
                  `requested_document_expiry_date_${requested_document.id}`
                )
              ).unix(),
              updated_on: moment().unix(),
              added_by: userId,
              status: 1,
            };

            const files =
              this.input.files[`requested_document_${requested_document.id}`];
            if (
              files &&
              files.name &&
              files.name.length > 0 &&
              files.name[0] !== ""
            ) {
              const uploaded = await onboardModel.doUpload(
                `requested_document_${requested_document.id}`,
                "partners"
              );

              if (uploaded.error) {
                this.session.flash("error_msg", uploaded.error);
                this.redirect("admin/onboard/process");
                return;
              } else if (uploaded.file_name !== "") {
                partner_requested_documents[requested_document_i].file_name =
                  uploaded.file_name;
              }
            } else {
              partner_requested_documents[requested_document_i].file_name =
                null;
            }

            requested_document_i++;
          }
        }

        if (partner_requested_documents.length > 0) {
          await onboardModel.updateBatchData(
            "rfq_documents",
            partner_requested_documents
          );
        }
      } else if (stage["stage_type"] == 2) {
        console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%nnnnn");
        const bank_info = [
          {
            // id:values.bank_info_id || null,
            partner_id: partnerId,
            bank_name: values.bank || null,
            name_on_account: values.nameOnAccount || null,
            routing_number: values.routing || null,
            account_number: values.accountno || null,
            account_type: values.account_type?.id || 1,
            swift_code: values.swift || null,
            name_on_card: values.name_on_card || null,
            card_number: values.ccdc || null,
            expiration_date: values.expire_date ? moment(values.expire_date).unix() : null,
            card_cvv: values.card_cvv
              ? this.encrypt.encode(values.card_cvv)
              : null,
            // card_type: values.card_type || null,
            updated_on: moment().unix(),
            added_by: userId,
            status: 1,
          },
        ];
        console.log('Bank&&&&&&&&&&&&&&&&&&', bank_info);
        await Onboard.updateBatchData("partner_bank_info", bank_info);
      } else if (stage["stage_type"] == 3) {
        const tax_info = [
          {
            // id: req.body.tax_info_id|| null,
            partner_id: partnerId,
            business_type: values.approach=="individual"?2:1 || null,
            social_security_number: values.tax_num || null,
            first_name: values.first_name || null,
            middle_name: values.middle_name || null,
            last_name: values.last_name || null,
            address: values.address || null,
            city: values.city || null,
            state_id: values.states.id || null,
            zipcode: values.zip_code || null,
            is_business_name: values.business_name || 2,
            business_name: values.business_name_value || "",
            tax_classification: values.tax_clarify===false?0:1 || 0,
            updated_on: moment().unix(),
            added_by: userId,
            status: 1,
          },
        ];
        console.log("Tax=================");
        await Onboard.updateBatchData("partner_tax_info", tax_info);
      } else if (stage["stage_type"] == 4) {
        let titles = [];
        titles.push(values.title);
        let descriptions = [];
        descriptions.push(values.description);
        let files = [];
        files.push(values.avatarUrl);
        let i = 0;
        while (values.hasOwnProperty(`title${i}`)) {
          titles.push(req.body.values[`title${i}`]);
          i++;
        }

        i = 0;
        while (values.hasOwnProperty(`description${i}`)) {
          descriptions.push(values[`description${i}`]);
          i++;
        }
        i = 0;
        while (values.hasOwnProperty(`avatarUrl${i}`)) {
          files.push(values[`avatarUrl${i}`]);
          i++;
        }

        const portfolio_ids = req.body.portfolio_id;

        const portfolio_file_fields = req.body.portfolio_file_field;
        let portfolios = [];
        for (let i = 0; i < titles.length; i++) {
          const portfolio = {
            // id: portfolio_ids[key] || null,
            request_id: requestId,
            partner_id: partnerId,
            title: titles[i],
            description: descriptions[i],
            updated_on: moment().unix(),
            file_name: files[i],
            added_by: userId,
            status: 1,
          };
          portfolios.push(portfolio);
        }
        console.log("##############", portfolios);
        

        if (portfolios.length > 0) {
          await Onboard.updateBatchData("rfq_portfolio", portfolios);
        }
      }
      else if (stage['stage_type'] == 5) {
        
        let field_template_i = 0;
        const partner_fields = [];
        let fieldTemplates = values.fieldTemplates
        console.log("PPPPPPPPPPPPPPPPPPPPPPPPPPqqqqqqqqq", fieldTemplates);
        let partnerFields = []
        let partnerField = {}
        let valueData = removeNull(fieldTemplates)
        console.log("XXXXXXXXXXXXXXXXXX", partnerFields);

          const field_value_pairs = [];

        for (const [key, value] of Object.entries(valueData)) {
          if (value && typeof value === 'object' && "value" in value) {
            field_value_pairs.push({ "field_id": value.field_id, "value": value.value,partner_id: partnerId,updated_on: moment().unix(),added_by: userId, request_id: requestId, status: 1,});
          } else if (value && Array.isArray(value) && value.every(item => typeof item === 'object' && "value" in item)) {
            for (const item of value) {
              field_value_pairs.push({ "field_id": item.field_id, "value": item.value,partner_id: partnerId,updated_on: moment().unix(),added_by: userId, request_id: requestId, status: 1,});
            }
          }
        }
        console.log("XXXXXXXXXXXXXXXXXX", field_value_pairs);
        if (field_value_pairs.length > 0) {
          await Onboard.updateBatchData("rfq_questionnaires",
           field_value_pairs

          );
        }
      }
      else if (stage["stage_type"] === 6) {
        console.log("###########Agrements");
      
        const agreements =  [];
      for(let i=0;i<req.body.sign_agrement.length;i++){
        const agreementdata = {
          // id: this.input.post(`sign_agreement_id_hidden_${sign_agreement.id}`) || null,
          request_id: requestId,
          partner_id: partnerId,
          document_id: req.body.sign_agrement[i],
          file_name: values.sign_attach,
          document_type: 2,
          onboarding: 1,
          updated_on: moment().unix(),
          added_by: userId,
          status: 1
        }
        agreements.push(agreementdata);
      }
       
        console.log("$$$%%%%%%%%%", agreements);
        await Onboard.updateBatchData('rfq_documents', agreements);
      
      }
    }

    if (!empty(data["workflows"])) {
      
      for (let eachworkflow of data["workflows"]) {
        data["stage"] = await OnboardWorkFlowStages.getnextStage(partnerId,eachworkflow["id"],0,0,1,requestId);
        if (!empty(data["stage"])) {
          workflowId = eachworkflow["id"];
          break;
        }
      }
    }
    data["states"] = await Admin.getAllStates();
    if (
      !empty(stage) &&
      !empty(stage["message"]) &&
      !empty(partnerStageStatus) &&
      stage["stage_submit"] == 1
    ) {
      data["stage_submit"] = stage["stage_submit"];
      data["stage"] = stage;
      res.send({ manual: 1, data, status: 1, });
      return;
    }

    console.log("###############Data stage",data['stage']);
    if (!empty(data['stage'])) {
      if (!empty(data['stage']['partner_stage_id'])) {
        console.log("Anavia riyassssssssssssss", data['stage']['partner_stage_id']);
        let stagedata = await Onboard.getRfqStageByid(data['stage']['partner_stage_id'])
        console.log("Anavia riyassssssssssssss", stagedata);
        if (stagedata[0]['stage_submit'] == 1) {
          data['stage_submit'] = stagedata[0]['stage_submit']
          //       $this->load->view('admin/onboard/onboard-views/no-onboarding',$data);
          console.log("Anavia riyassssssssssssss ohhhhhhhhhhh");
          res.send({ manual: 1, data, status: 1 });
          return
        }
      }

      let currentProcessingStageData = data["stage"];
      let currentProcessingPartnerId = partnerId;
      

  
      res.send({ stage: data["stage"]["stage_type"], data, status: 1 });
    }
     else if (await Onboard.isRfqStages(requestId)) {
      console.log("$$$$$$$$$$$$$$$$Nushhhhhhhhhhhhhh");
      res.send({ onboardCompleted: 1, data, status: 1 });

      // redirect('admin/onboard/process');
    }
     else {
      console.log("hiffffffffffffffffff");
      // $this->load->view('admin/onboard/onboard-views/no-onboarding',$data);
    }
  } catch (error) {
    res.status(500).send("error in process" + error)
    console.log(error, "error in process");
  }
}
const clientOnboardFormUpdate = async (req, res) => {
  let { userId, updatedValues, stageType, clientId } = req.body;
  if (stageType === 1) {
    let field_value_pairs = [];
    for (const [key, value] of Object.entries(updatedValues)) {
      if (!empty(value.field_id)) {
        let processedValue;
        if (Array.isArray(value.value)) {
          processedValue = value.value.join(",");
        } else {
          processedValue = value.value;
        }
        if (processedValue) {
          field_value_pairs.push({
            field_id: value.field_id,
            value: processedValue,
            partner_id: clientId,
            updated_on: moment().unix(),
            added_by: userId,
            status: 1,
          });
        }

        let deleted = await Onboard.deleteBatchUpdate(
          "partner_custom_fields",
          value.field_id
        );
      }
   
    }
      await Onboard.updateBatchData("partner_custom_fields", field_value_pairs);
      res.send({
        status:1,message:'Updated Successfully !'
      })
    
  } else if (stageType === 5) {
    let field_value_pairs = [];
    for (const [key, value] of Object.entries(updatedValues)) {
     
      if (!empty(value.field_id)) {
        let processedValue;
        if (Array.isArray(value.value)) {
          processedValue = value.value.join(",");
        } else {
          processedValue = value.value;
        }
        if (processedValue) {
          field_value_pairs.push({
            field_id: value.field_id,
            value: processedValue,
            partner_id: clientId,
            updated_on: moment().unix(),
            added_by: userId,
            status: 1,
          });
        }
        let deleted = await Onboard.deleteBatchUpdate(
          "partner_questionnaires",
          value.field_id
        );
      }
    }
   
    await Onboard.updateBatchData("partner_questionnaires", field_value_pairs);
    res.send({
      status:1,message:'Updated Successfully !'
    })
  }else if(stageType===4){
    if(!empty(updatedValues)){
      await Onboard.deletePortFolio('partner_portfolio',updatedValues.id)
      let portfolio={
      partner_id: clientId,
      title: updatedValues.portfolio_title,
      description:updatedValues.portfolio_description,
      updated_on: moment().unix(),
      file_name: updatedValues.portfolio_image,
      added_by: userId,
      status: 1,
      }
      await Onboard.updateBatchData("partner_portfolio", [portfolio])
      res.send({
        status:1,message:'Updated successfully'
      })
    }
  }
};
const TeamOnboardFormUpdate = async (req, res) => {
  let { userId, updatedValues, stageType, teamId } = req.body;
  if (stageType === 1) {
    let field_value_pairs = [];
    for (const [key, value] of Object.entries(updatedValues)) {
      if (!empty(value.field_id)) {
        let processedValue;
        if (Array.isArray(value.value)) {
          processedValue = value.value.join(",");
        } else {
          processedValue = value.value;
        }
        if (processedValue) {
          field_value_pairs.push({
            field_id: value.field_id,
            value: processedValue,
            team_id: teamId,
            updated_on: moment().unix(),
            added_by: userId,
            status: 1,
          });
        }

        let deleted = await Onboard.deleteBatchUpdate(
          "team_custom_fields",
          value.field_id
        );
      }
   
    }
      await Onboard.updateBatchData("team_custom_fields", field_value_pairs);
      res.send({
        status:1,message:'Updated Successfully !'
      })
    
  } else if (stageType === 5) {
    let field_value_pairs = [];
    for (const [key, value] of Object.entries(updatedValues)) {
     
      if (!empty(value.field_id)) {
        let processedValue;
        if (Array.isArray(value.value)) {
          processedValue = value.value.join(",");
        } else {
          processedValue = value.value;
        }
        if (processedValue) {
          field_value_pairs.push({
            field_id: value.field_id,
            value: processedValue,
            team_id: teamId,
            updated_on: moment().unix(),
            added_by: userId,
            status: 1,
          });
        }
        let deleted = await Onboard.deleteBatchUpdate(
          "team_questionnaires",
          value.field_id
        );
      }
    }
   
    await Onboard.updateBatchData("team_questionnaires", field_value_pairs);
    res.send({
      status:1,message:'Updated Successfully !'
    })
  }else if(stageType===4){
    if(!empty(updatedValues)){
      await Onboard.deletePortFolio('partner_portfolio',updatedValues.id)
      let portfolio={
        team_id: teamId,
      title: updatedValues.portfolio_title,
      description:updatedValues.portfolio_description,
      updated_on: moment().unix(),
      file_name: updatedValues.portfolio_image,
      added_by: userId,
      status: 1,
      }
      await Onboard.updateBatchData("partner_portfolio", [portfolio])
      res.send({
        status:1,message:'Updated successfully'
      })
    }
  }
};
const requestOnboardFormUpdate=async(req,res)=>{
  try {
    let { userId, updatedValues, stageType, requestId } = req.body;
    if (stageType === 1) {
      let field_value_pairs = [];
      for (const [key, value] of Object.entries(updatedValues)) {
        if (!empty(value.field_id)) {
          let processedValue;
          if (Array.isArray(value.value)) {
            processedValue = value.value.join(",");
          } else {
            processedValue = value.value;
          }
          if (processedValue) {
            field_value_pairs.push({
              field_id: value.field_id,
              value: processedValue,
              partner_id: value.partner_id||0,
              updated_on: moment().unix(),
              added_by: userId,
              request_id: requestId,
              status: 1,
            });
          }
        
          let deleted = await Onboard.deleteRFQBatchUpdate(
            "rfq_custom_fields",
           requestId, value.field_id
          );
        }
     
      }
        await Onboard.updateBatchData("rfq_custom_fields", field_value_pairs);
        res.send({
          status:1,message:'Updated Successfully !'
        })
      
    } else if (stageType === 5) {
      let field_value_pairs = [];
      for (const [key, value] of Object.entries(updatedValues)) {
       
        if (!empty(value.field_id)) {
          let processedValue;
          if (Array.isArray(value.value)) {
            processedValue = value.value.join(",");
          } else {
            processedValue = value.value;
          }
          if (processedValue) {
            field_value_pairs.push({
              field_id: value.field_id,
              value: processedValue,
              partner_id: value.partner_id,
              updated_on: moment().unix(),
              request_id: requestId,
              added_by: userId,
              status: 1,
            });
          }
          let deleted = await Onboard.deleteRFQBatchUpdate(
            "rfq_questionnaires",
            requestId, value.field_id
          );
        }
      }
     
      await Onboard.updateBatchData("rfq_questionnaires", field_value_pairs);
      res.send({
        status:1,message:'Updated Successfully !'
      })
    }else if(stageType===4){
      if(!empty(updatedValues)){
        await Onboard.deletePortFolio('rfq_portfolio',updatedValues.id)
        let portfolio={
        partner_id: updatedValues.partner_id,
        title: updatedValues.portfolio_title,
        description:updatedValues.portfolio_description,
        updated_on: moment().unix(),
        request_id:requestId,
        file_name: updatedValues.portfolio_image,
        added_by: userId,
        status: 1,
        }
        await Onboard.updateBatchData("rfq_portfolio", [portfolio])
        res.send({
          status:1,message:'Updated successfully'
        })
      }
    }
  } catch (error) {
    console.log(error)
  }
}

const ViewOnboardStageData=async(req,res)=>{
  try {
    const {stageId} = req.body
    let templatesData=[]
    let resultData=''
    let field_template_ids = await OnboardWorkFlowFields.getfieldTemplatesbyStageId(stageId);
    if (field_template_ids.length !== 0) {
      templatesData = await OnboardWorkFlowStages.getTemplateFormDataById(field_template_ids, 0);
      resultData='template'
    }

    let questionnaireIds = await OnboardWorkFlowQuestionnaires.getQuestionairebyStageId(stageId);
    if (questionnaireIds.length !== 0) {
      templatesData = await OnboardWorkFlowStages.get_qns_formData_by_id(questionnaireIds, 0);
      resultData='template'
    }
     let aggrememtData = await  OnboardWorkFlowDocuments.getDocumentsData(stageId)
     if(!empty(aggrememtData)){
        templatesData=aggrememtData
        resultData='aggrement'
     }
    

     if(!empty(templatesData)){
      res.send({
        status:1,templatesData,resultData
      })
     }else{
      res.send({
        status:0,
      })
     }
    } catch (error) {
    console.log(error)
  }
}

module.exports = {
  getAllWorkflows,
  ViewOnboardWorkflow,
  addWorkFlow,
  loadSidePanelForAddWorkFlow,
  createDocumentRequest,
  createSignAgreement,
  saveStages,
  deletWorkFlow,
  editWorkFlow,
  fetchWorkFlowById,
  onboardProcess,
  reviewOnboard,
  teamProcess,
  clientOnboardFormUpdate,
  rfqOnboardProcess,
  requestOnboardFormUpdate,
  TeamOnboardFormUpdate,
  ViewOnboardStageData,
  getAllClientFacingWorkflows,
  duplicateWorkFlow,
  getAllProductionWorkflows,
  getAllServicesWorkflows,
  getAllServiceWorkflows,
  getAllProductWorkflows

};
