const sequelize = require("../config/dbconnection");
const Teams = require("../models/teams");
const Admin = require("../models/admin");
const moment = require("moment");
const Password = require("node-php-password");
const { empty, generateUniquePin } = require("../Helpers/Common");
const Driver = require('../models/driver')

const { inviteLinkTemplate } = require("../libraries/emailTemplates");
const { MAIL_SENDER, TWILIO_PHONE, TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, SEND_EMAIL } = require("../constants/constant");
const { baseUrl } = require("../constants/constant");
// const { transporter } = require("../constants/common");
const OnboardWorkFlowFields=require("../models/onboardWorkflowFields")
const OnboardWorkFlowStages=require("../models/onboardWorkFlowStages")
const ContactTags = require('../models/contactTag')
const OnboardWorkFlowQuestionnaires=require("../models/onboardWorkflowQuestionnaires")
const sgMail = require('@sendgrid/mail')
const { SENDGRID_API_KEY, BASE_URL, portalName } = require("../constants/constant")
const { sendPartnerMail, activateProfile } = require("../constants/emailTemplates");
let Onboard=require("../models/onboard")
const nodemailer = require('nodemailer');
const client = require("twilio")(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);



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


const getAllTeamsData = async (request, reply) => {
  let { usersId, usersType, isClient, orderBy, order } = request.body;
  let page = request.body.page
  let search = request.body.search
  let rowPerpage = request.body.rowsPerPage

  let teamData = [];
  if (usersType !== 1 && usersType !== 3) {
    teamData = await Admin.getTeamByUserId(usersId);
  }
  let team_members = await Teams.getAllTeams(
    true,
    "",
    usersId,
    usersType,
    teamData,
    page,
    rowPerpage,
    search,
    isClient,
    orderBy || 'name',
    order || 'asc'
  );
  let states = await Teams.getAllStates("ASC");
  let services = await Teams.getAllServices("ASC");
  let availabilities = await Teams.getAllAvailabilities();
  // let workflows = await Teams.getAllWorkflows();
  let workflows=await Onboard.getAllTeamFacingWorkflow()

 console.log(team_members,'-----------team_members')
  reply.send({
    status: 1,
    message: "Team data fetched successfully",
    team_members: team_members,
    states: states,
    services: services,
    availabilities: availabilities,
    workflows: workflows,
    teamData: teamData,
  });
};
const getAllTeamsDataCollaborators = async (request, reply) => {
  try {
    const { page, search, rowsPerPage } = request.body;
    const { usersId, usersType, isClient, orderBy, order } = request.body;


    // Fetch team members based on the new, simplified function
    const team_members = await Teams.getTeamMembersForCollaborators(
      page,
      rowsPerPage,
      search,
      isClient,
      orderBy || 'name',
      order || 'asc'
    );

    
    // Send the response with the required data
    reply.send({
      status: 1,
      message: 'Team data fetched successfully',
      team_members,
    });
  } catch (error) {
    console.log("Error in getAllTeamsDataSimplified:", error);
    reply.send({
      status: 0,
      message: 'Error fetching team data',
    });
  }
};

const getAllSalesRepsData = async (request, reply) => {
  let { usersId, usersType, isClient } = request.body;
  let page = request.body.page
  let search = request.body.search
  let rowPerpage = request.body.rowsPerPage

  let teamData = [];
  if (usersType !== 1 && usersType !== 3) {
    teamData = await Admin.getTeamByUserId(usersId);
  }
  let team_members = await Teams.getAllSalesRepsMembers(
    true,
    "",
    usersId,
    usersType,
    teamData,
    page,
    rowPerpage,
    search,
    isClient
  );
  if (team_members && team_members.data && team_members.data.length > 0) {
    const userId = parseInt(usersId);
    const sortedData = team_members.data.sort((a, b) => {
      const aIsLoggedIn = a.id === userId || a.user_id === userId;
      const bIsLoggedIn = b.id === userId || b.user_id === userId;
      if (aIsLoggedIn && !bIsLoggedIn) return -1;
      if (!aIsLoggedIn && bIsLoggedIn) return 1;
      return 0;
    });
    team_members.data = sortedData;
  }
  let states = await Teams.getAllStates("ASC");
  let services = await Teams.getAllServices("ASC");
  let availabilities = await Teams.getAllAvailabilities();
  // let workflows = await Teams.getAllWorkflows();
  let workflows=await Onboard.getAllTeamFacingWorkflow()

 console.log(team_members,'-----------team_members')
  reply.send({
    status: 1,
    message: "Team data fetched successfully",
    team_members: team_members,
    states: states,
    services: services,
    availabilities: availabilities,
    workflows: workflows,
    teamData: teamData,
  });
};
const getAllTeamsDataForChat = async (request, reply) => {
  let { usersId } = request.body;
  let { usersType } = request.body;
  let page = request.body.page
  let search = request.body.search
  let rowPerpage = request.body.rowsPerPage

  let teamData = [];
  if (usersType !== 1 && usersType !== 3) {
    teamData = await Admin.getTeamByUserId(usersId);
  }
  let team_members = await Teams.getAllTeams(
    true,
    "",
    usersId,
    usersType,
    teamData,
    page,
    rowPerpage,
    search
  );
  let states = await Teams.getAllStates("ASC");
  let services = await Teams.getAllServices("ASC");
  let availabilities = await Teams.getAllAvailabilities();
  // let workflows = await Teams.getAllWorkflows();
  let workflows=await Onboard.getAllTeamFacingWorkflow()

 console.log(team_members,'-----------team_members')
  reply.send({
    status: 1,
    message: "Team data fetched successfully",
    team_members: team_members,
    states: states,
    services: services,
    availabilities: availabilities,
    workflows: workflows,
    teamData: teamData,
  });
};

const getTeamById = async (request, reply) => {
  let teamId = JSON.parse(JSON.stringify(request.query.id));
  console.log("teamId : ", teamId);
  let teamDataByID = await Teams.getTeamById(teamId);
  let userRoles = await Teams.getAllUserRoles();
  let contact_tags = await ContactTags.getAllContactTags()
  let states = await Teams.getAllStates("ASC");
  let departments = await Teams.getAllDepartments("ASC");
  let services = await Teams.getAllServices("ASC");
  if (teamDataByID) {
    reply.send({
      status: 1,
      message: "Fetched team data by ID successfully",
      teamData: teamDataByID,
      userRoles: userRoles,
      states: states,
      departments: departments,
      services: services,
      contact_tags:contact_tags
    });
  } else {
    reply.send({ status: 0, message: "Error in fetching team data by ID" });
  }
};

const updateTeam = async (request, reply) => {
  let { editId, team } = request.body;
  console.log('editId', editId)
  // Get the user_id to update the Admin table
  const teamData = await Teams.getTeamById(editId);
  const userId = teamData?.user_id;
  let driver = {}
  const timestamp = Math.round(moment().valueOf() / 1000);

  // Normalize email
  team.email = (!team.email || team.email === '') ? null : team.email;

  // Check for duplicate email
  if (team.email) {
    const existingTeam = await Teams.getTeamByEmail(team.email);
    console.log('existingTeam', existingTeam)
    if (existingTeam && Number(existingTeam.id) !== Number(editId)) {
      return reply.send({
        status: 0,
        message: "Email ID already exists for another team member"
      });
    }
    const getUserByEmailData = await Admin.getUserByEmail(team.email);
    if (getUserByEmailData && Number(getUserByEmailData.id) !== Number(userId)) {
      return reply.send({
        status: 0,
        message: "Email ID already exists for another user",
      });
    }
  }

  // Check for duplicate phone
  if (team.phone) {
    // const existingTeamByPhone = await Teams.getTeamByPhoneNum(team.phone);
    const existingTeamByPhone = await Teams.getTeamByPhoneNumAndPassword(team.phone,team.password,editId);
    console.log('existingTeamByPhone', existingTeamByPhone)
    if (existingTeamByPhone && Number(existingTeamByPhone.id) !== Number(editId)) {
      return reply.send({
        status: 0,
        message: "This Combination of Phone Number and Password is not acceptable"
      });
    }
  }

  // Update team table
  const updateTeamResult = await Teams.updateTeam(editId, team);

  if (updateTeamResult) {
    // Update Admin email and username if user exists

    if(team.password){
      const admin_password = team.password;
      const hashedPassword = Password.hash(admin_password);
      await Admin.updateUser(userId, {
        password: hashedPassword,
        admin_password: admin_password
      });
    }
    if (userId && team.email) {
      await Admin.updateUser(userId, {
        email: team.email,
        username: team.email // assuming username = email
      });
    }

    // Update driver table details
    const getDriverByUserId = await Driver.getDriverByuserId(userId)
    const driverId = getDriverByUserId[0]?.id || null
    console.log('getDriverByUserId',getDriverByUserId[0])

      driver['name']= `${team?.first_name || ''} ${team?.last_name || ''}`.trim() || team?.first_name
      driver['email']= team?.email;
      driver['phone']= team?.phone
      // driver['licence_image']= values.licence_image
      driver['hourly_rate']= team?.hourly_rate
      // driver['gender']= values.gender
      driver['status']= 1
      // driver['address'] = values.address
      // driver['profile_photo'] = values.profile_photo
      driver['timestamp']= timestamp
      driver['added_by']= teamData?.added_by 
      driver['verified'] = 1;
      driver['user_id'] = userId;
      driver['team_id'] = teamData?.id;
      
      let driverDetails = '';

    if (getDriverByUserId?.length <= 0) {
      driverDetails = await Driver.addDriver(driver)
      console.log('driverResulttttt added',driverDetails)
    }else{
      driverDetails = await Driver.updateDriver(driver,driverId)
      console.log('driverResulttttt updated',driverDetails)
    }
    console.log('driverDetailssss',driverDetails)

    return reply.send({
      status: 1,
      message: `The details of the team member "${team.first_name} ${team.last_name}" have been updated!`,
    });
  } else {
    return reply.send({ status: 0, message: `Error updating team` });
  }
};

const updateUser = async (request, reply) => {
  let teamUserData = {};
  let currentDate = Math.round(moment().valueOf() / 1000);
  let { userId } = request.query;
  let updateTeamStatus = request.body.statusData.value;
  console.log("update Data : ", request.body);
  let uploaded;
  teamUserData.first_name = request.body.first_name.value;
  teamUserData.last_name = request.body.last_name.value;
  teamUserData.email = (!request.body.email?.value || request.body.email?.value == '') ? null : request.body.email?.value;
  teamUserData.phone = request.body.phone?.value || null;

  const existingUserData = await Admin.getUserById(userId);

  // Only check for duplicates if the email is changing
  if (
    teamUserData.email &&
    teamUserData.email !== existingUserData.email
  ) {
    const getTeamByEmailData = await Teams.getTeamByEmail(teamUserData.email);
    if (getTeamByEmailData && Number(getTeamByEmailData.user_id) !== Number(userId)) {
      return reply.send({
        status: 0,
        message: "Email ID already exists for another team member",
      });
    }
  
    const getUserByEmailData = await Admin.getUserByEmail(teamUserData.email);
    if (getUserByEmailData && Number(getUserByEmailData.id) !== Number(userId)) {
      return reply.send({
        status: 0,
        message: "Email ID already exists for another user",
      });
    }

    // It's a new email, so update username
    teamUserData.username = teamUserData.email;
  }
  
  if(request.body?.password?.value){
    const hashedNewPassword = Password.hash(request.body.password.value);
    teamUserData.password = hashedNewPassword;
    teamUserData.admin_password = request.body.password.value;
  }
  teamUserData.user_type = request.body.user_type.value;
  teamUserData.department_id = request.body.department_id.value;
  teamUserData.profile_pic = request.body.profile_pic.value;
  teamUserData.company_logo = request.body.company_logo.value;
  let loggedInUserId = request.body.loggedInUserId.value;
  let loggedInUserType = request.body.loggedInUserType.value;
  console.log("loggedInUserId : ", loggedInUserId);
  console.log("loggedInUserType : ", loggedInUserType);

  // const fullfilename = request.body.profile_pic.filename; //get selected filename
  // if (fullfilename) {
  //   const extension = fullfilename.substring(
  //     fullfilename.lastIndexOf(".") + 1,
  //     fullfilename.length
  //   ); //extract the extension from the file name
  //   console.log("fullfilename : ", fullfilename, "- extension : ", extension);
  //   const userName = teamUserData.first_name + "_" + teamUserData.last_name; //joins the user's first name and last name
  //   const newfilename = userName.replace(/[^a-zA-Z0-9]/g, "_"); //replaces special characters with underscore(_) in the joined name
  //   const filename = newfilename + "." + extension; //joins the new name with extracted extension
  //   console.log("filename-- ", filename);
  //   const fileParts = request.body.profile_pic.toBuffer();
  //   if (fileParts) {
  //     let fileNamewithDate = `${currentDate}_${filename}`;
  //     uploaded = await Teams.doUpload(fileParts, fileNamewithDate);
  //     teamUserData.profile_pic = fileNamewithDate;
  //     console.log("uploaded - ", uploaded);
  //   }
  // }
  console.log("userId - ", userId, "teamUserData - ", teamUserData);
  const updateUserResult = await Admin.updateUser(userId, teamUserData);
  console.log("updateUserResult - ", updateUserResult);
  if (updateUserResult !== false) {
    reply.send({
      status: 1,
      message: `The details of the team member "${teamUserData.first_name} ${teamUserData.last_name}" has been updated!`,
    });
  } else {
    reply.send({ status: 0, message: `Error updating user` });
  }  

  // Add notification if team or user is updated
  if (updateTeamStatus == 1 || updateUserResult == true) {
    let notificationMsg = `The details of the team member "${teamUserData.first_name} ${teamUserData.last_name}" has been updated.`;
    let notificationUrl = "teams";

    // Alert to user of team member details updation
    const incrementResultUser = await Admin.incrementField(
      loggedInUserId,
      "noti_count",
      1
    );
    console.log("incrementResult--to--user-----------", incrementResultUser);
    let notificationData_user = {
      user_id: loggedInUserId,
      url: notificationUrl,
      timestamp: currentDate,
      message: notificationMsg,
      status: 1,
      from_id: loggedInUserId,
    };
    console.log("notificationData--user------------", notificationData_user);
    const addNotificationResult_user = await Admin.addNotification(
      notificationData_user
    );
    console.log(
      "addNotificationResult--user-------",
      addNotificationResult_user
    );

    // Alert to all admins (except current logged in user) of team member details updation

    let adminIds = await Admin.getAllAdminIds();
    let notificationData = {};
    console.log("adminIds====", adminIds);
    for (const adminId of adminIds) {
      console.log("adminId----------", adminId);
      if (adminId != loggedInUserId) {
        const incrementResult = await Admin.incrementField(
          adminId,
          "noti_count",
          1
        );
        // console.log("incrementResult-------------", incrementResult);
        notificationData = {
          user_id: adminId,
          url: notificationUrl,
          timestamp: currentDate,
          message: notificationMsg,
          status: 1,
          from_id: loggedInUserId,
        };
        // console.log("notificationData------------", notificationData);
        const addNotificationResult_admin = await Admin.addNotification(
          notificationData
        );
        console.log(
          "addNotificationResult_admin-------",
          addNotificationResult_admin
        );
      }
    }
  }
};

const updateUserActive = async (request, reply) => {
  let teamUserData = {};
  let currentDate = Math.round(moment().valueOf() / 1000);
  let { user_id, online } = request.body;
  if(online){
    teamUserData.online = 1
  }else{
    teamUserData.online = 0
  }
  console.log('teamUserDatateamUserData',teamUserData )
  const updateUserResult = await Admin.updateUser(user_id, teamUserData);
  console.log("updateUserResult - ", updateUserResult);
  if (updateUserResult !== false) {
    reply.send({
      status: 1,
      message: `Active status has been updated!`,
    });
  } else {
    reply.send({ status: 0, message: `Error updating status` });
  }  
};

const helpDeskUserActive = async (request, reply) => {

  const user_id = 667

  const helpDesk = await Admin.getUserById(user_id);
  if (helpDesk !== false) {
    reply.send({
      status: 1,
      data : helpDesk[0],
      message: `fetched helpdesk data`,
    });
  } else {
    reply.send({ status: 0, message: `Error fetching helpdesk data` });
  }  
};

const getAllUserRoles = async (request, reply) => {
  const isClientUserRole = request?.body?.isClientUserRole
  const getAllUserRolesResult = await Teams.getAllUserRoles(isClientUserRole);
  if (getAllUserRolesResult) {
    // console.log("getAllUserRolesResult", getAllUserRolesResult);
    reply.send({ status: 1, result: getAllUserRolesResult });
  } else {
    reply.send({ status: 0, message: `Error updating user` });
  }
};

const getAllServices = async (request, reply) => {
  const getAllServicesResult = await Teams.getAllServices(order = "ASC");
  if (getAllServicesResult) {
    console.log("getAllServicesResult", getAllServicesResult);
    reply.send({ status: 1, result: getAllServicesResult });
  } else {
    reply.send({ status: 0, message: `Error in getAllServices` });
  }
};

const sendMessageToPhoneNumber = async (phoneNumber,messageContents,phone_country_code) => {
  console.log('phoneNumberrrrrrr',phoneNumber)
  console.log('phone_country_codeeee',phone_country_code)
  console.log('messageContentssssss',messageContents)
  try {
    if (!phoneNumber || !messageContents) {
      throw new Error("Phone number and message content are required.");
    }

    const toNumber = phone_country_code && phone_country_code.trim()
  ? `+${phone_country_code.trim()}${phoneNumber}`
  : `+91${phoneNumber}`;

  console.log('toNumberrrrr',toNumber)
    const message = await client.messages.create({
      body: messageContents,
      // to: `+91${phoneNumber}`,
      to: toNumber,
      from: TWILIO_PHONE,
    })
console.log('sendMessagesendMessagesendMessage',message)
    return message.sid;
  } catch (error) {
    console.error("Error sending message", error);
    throw new Error("Failed to send message");
  }
};


const addTeamMembers = async (request, reply) => {
  try {
    const first_name = request.body.first_name;
    const last_name = request.body.last_name;
    const email = (request.body.email_id && request.body.email_id != "") ? request.body.email_id : null;
    const password = request.body.password;
    const phone = request.body.phone;
    const phone_country_code = request.body.phone_country_code;
    const forward_no = request.body.forward_no;
    const forward_country_code = request.body.forward_country_code;
    const hourly_rate = request.body.hourly_rate;
    const workflows = request.body.workflowIds;
    const contact_tags = request.body.contact_tagIds;
    const services = request.body.serviceIds;
    const userType = request.body.roleid;
    const departmentId = request.body.departmentId;
    const stateId = request.body.stateId;
    const city = request.body.city;
    const avatarUrl = request.body.avatarUrl;
    const profile_pic = request.body.profile_pic;
    const added_by = request.body.userId;
    const timestamp = Math.round(moment().valueOf() / 1000);
    const sessionUserType = request.body.sessionUserType;
    const isClient = request.body.isClient;
    // const email_team=request.body.email_team;// A
    // if(request.body.custom_message){
    //     const subject=request.body.subject; // An optional email subject
    //     const email_content=request.body.email_content; // an optional email content / matter of email
    // }else{
    //     const subject="";
    //     const email_content="";
    // }

    // const emailError = {};
    const dataForDb = {};
    const user = {};
    const driver = {};
    let hashedPassword;
    let team = {};
    let getTeamByEmailData = false;
    let getUserByEmailResult = false;
    let getTeamByPhoneNum = false
    let getUserByPhoneNumResult = false;

    if (!empty(email) && email != '' && email != null){
      getTeamByEmailData = await Teams.getTeamByEmail(email);
    }
    if(phone){
      // getTeamByPhoneNum = await Teams.getTeamByPhoneNum(phone)
      getTeamByPhoneNum = await Teams.getTeamByPhoneNumAndPassword(phone, password,false)
    }
    console.log("getTeamByEmailData - ", getTeamByEmailData);
    console.log("getTeamByPhoneNum - ", getTeamByPhoneNum);
    if (!getTeamByEmailData && !getTeamByPhoneNum) {
      dataForDb["first_name"] = first_name;
      dataForDb["last_name"] = last_name;
      dataForDb["email"] = email;
      dataForDb["phone"] = phone;
      dataForDb["phone_country_code"] = phone_country_code;
      dataForDb["forward_no"] = forward_no;
      dataForDb["forward_country_code"] = forward_country_code;
      dataForDb["hourly_rate"] = hourly_rate;
      dataForDb["workflows"] = workflows;
      dataForDb["state_id"] = stateId;
      dataForDb["city"] = city;
      dataForDb["avatarUrl"] = avatarUrl;
      dataForDb["profile_pic"] = profile_pic;
      dataForDb["contact_tags"] = contact_tags;
      dataForDb["services"] = services;
      dataForDb["added_by"] = added_by;
      dataForDb["timestamp"] = timestamp;
      dataForDb["status"] = 1;
      dataForDb["permissions"] = "";
      hashedPassword = Password.hash(password);
      // console.log("password : ", password, "hashedPassword : ", hashedPassword);
      const addTeam = await Teams.addTeam(dataForDb);
      const teamId = addTeam.dataValues.id;
      console.log("teamId - ", teamId);
      if (teamId) {
        const createStatus = true;
        user["first_name"] = dataForDb["first_name"];
        user["last_name"] = dataForDb["last_name"];
        user["company_name"] = portalName;
        user["email"] = dataForDb["email"];
        user["terms_and_policy"] = 1;
        user["username"] =dataForDb["phone"]
        // user["username"] = user["email"]?user["email"] : dataForDb["phone"] 
        user["password"] = hashedPassword;
        user['admin_password']=password
        user["profile_pic"] = profile_pic;
        user["company_logo"] = avatarUrl || "default_logo.png";
        user["status"] = 1;
        user["user_type"] = userType;
        user["state_id"] = stateId;
        user["city"] = city;
        user["department_id"] = departmentId;
        if (!empty(user.email) && user.email != '' && user.email != null){
          getUserByEmailResult = await Admin.getUserByEmail(user.email);
        }
        
        if(sessionUserType ==3 || isClient){
          user["added_by_client"] = 1;
          user["parent_id"] = added_by;
          user["parent_user_type"] = sessionUserType;
        }
        // Generate unique PIN for user
        user['user_pin_unique'] = await generateUniquePin(sequelize);
        console.log("getUserByEmailResult - ", getUserByEmailResult);
        if (!getUserByEmailResult) {
          const addUserId = await Admin.addUser(user);
          console.log("addUserId - ", addUserId);
          if (addUserId) {
            team["user_id"] = addUserId;
            team["status"] = 1;
            const updateTeamResult = await Teams.updateTeam(teamId, team);
            // console.log("updateTeamResult - ", updateTeamResult);

            driver['name']= `${dataForDb["first_name"] || ''} ${dataForDb["last_name"] || ''}`.trim();
            driver['email']= dataForDb["email"];
            driver['phone']= dataForDb["phone"]
            // driver['licence_image']= values.licence_image
            driver['hourly_rate']= dataForDb["hourly_rate"]
            // driver['gender']= values.gender
            driver['status']= 1
            // driver['address'] = values.address
            // driver['profile_photo'] = values.profile_photo
            driver['timestamp']= timestamp
            driver['added_by']= added_by
            driver['verified'] = 1;
            driver['user_id'] = addUserId;
            driver['team_id'] = teamId;

            const driverResult = await Driver.addDriver(driver)
            console.log('driverResultttttt',driverResult)
            if (updateTeamResult) {
              reply.send({
                status: 1,
                message: `Team member ${user["first_name"]} ${user["last_name"]} added successfully`,
              });

              // Add notification if team member is added
              let notificationMsg = `Team members has been added to ${portalName}`;
              let notificationUrl = "teams";

              // Alert to user of team member details updation
              const incrementResultUser = await Admin.incrementField(
                added_by,
                "noti_count",
                1
              );
              console.log(
                "incrementResult--to--user-----------",
                incrementResultUser
              );
              let notificationData_user = {
                user_id: added_by,
                url: notificationUrl,
                timestamp: timestamp,
                message: notificationMsg,
                status: 1,
                from_id: added_by,
              };
              console.log(
                "notificationData--user------------",
                notificationData_user
              );
              const addNotificationResult_user = await Admin.addNotification(
                notificationData_user
              );
              console.log(
                "addNotificationResult--user-------",
                addNotificationResult_user
              );

              // Alert to all admins (except current logged in user) of team member details updation

              let adminIds = await Admin.getAllAdminIds();
              let notificationData = {};
              console.log("adminIds====", adminIds);
              for (const adminId of adminIds) {
                console.log("adminId----------", adminId);
                if (adminId != added_by) {
                  const incrementResult = await Admin.incrementField(
                    adminId,
                    "noti_count",
                    1
                  );
                  console.log("incrementResult-------------", incrementResult);
                  notificationData = {
                    user_id: adminId,
                    url: notificationUrl,
                    timestamp: timestamp,
                    message: notificationMsg,
                    status: 1,
                    from_id: added_by,
                  };
                  console.log("notificationData------------", notificationData);
                  const addNotificationResult_admin =
                    await Admin.addNotification(notificationData);
                  console.log(
                    "addNotificationResult_admin-------",
                    addNotificationResult_admin
                  );
                }
              }
              let subject = portalName + " - Your account has been activated";
              let welcome = "Hello " + user["first_name"]  + ","
              let email_content = `Your account has been activated  . Your username (email address) and password is included for reference below.`;
              sgMail.setApiKey(SENDGRID_API_KEY)
              let message = activateProfile()
              console.log("$$$$$$$$$$$$",user['username']);
              message = message.replace('[emailContent]', email_content)
              message = message.replace('[CONTENT]', welcome)
              message = message.replace('[NAME]', user['username'])
              message = message.replace('[PASSWORD]', password)
              message = message.replace('[LOGIN_URL]', `${BASE_URL}`)
              const msg = {
                to: user.email, // Change to your recipient
                from: 'nushara@skyniche.com', // Change to your verified sender
                subject: subject,
                text: subject,
                html: message,
              }
              // sgMail
              //   .send(msg)
              //   .then(() => {
              //     console.log('Email sent')
              //   })
              //   .catch((error) => {
              //     console.error(error)
              //   })

if(user.email){

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

              const messageContents = `SignWise Solutions-
Hello ${first_name} ${last_name},
Your account has been activated. Your username and password are included for reference below.
USER NAME:  ${user["username"]}
PASSWORD: ${password}`;

if(phone){
  console.log('messageeeeeeeeeeeeeeee')
  let sendMessage= await sendMessageToPhoneNumber(phone,messageContents,phone_country_code)
}

           console.log('sendMessagesendMessagesendMessage',sendMessage)

              let adminEmails = await Admin.getAllAdminEmails();
              let adminSubject = portalName + " - A new Team Member has been registered";
              let adminWelcome = "Hello ! Admin" + ","
              let admin_email_content = `A new   Team Member has been registered`;
              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]', password)
              adminMessage = adminMessage.replace('[LOGIN_URL]', `${BASE_URL}`)
              for (const row of adminEmails) {
                console.log("$$$$$$$$$$$$$$$nush",row);
                const msg = {
                  to: row, // Change to your recipient
                  from: 'nushara@skyniche.com', // Change to your verified sender
                  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);
                 
                }
              }
            } else {
              reply.send({ status: 0, message: `Error adding Team member` });
            }
          }
        }
      }
    }
    if (getTeamByEmailData || getUserByEmailResult) {
      reply.send({
        status: 0,
        // message: `Failed to add Team member as Email ID or Phone Number already exists`,
        message: `Failed to add Team member as Email ID already exists`,
        getUserByEmailResult:getUserByEmailResult || '',
        getTeamByEmailData:getTeamByEmailData || ''
      });
    }else if(getTeamByPhoneNum){
      reply.send({
        status: 0,
        // message: `Failed to add Team member as Email ID or Phone Number already exists`,
        message: `This password cannot be used, Please choose a different one.`,
        getTeamByPhoneNum:getTeamByPhoneNum || '',
      });
    }
  } catch (error) {
    console.log("Team adding error ", error);
    reply.send({ status: 0, message: `Server error`+error });
  }
};



const deleteTeam = async (request, reply) => {
  const { teamId, status, userId } = request.body;
  let team = {};
  team["status"] = status;
  let currentDate = Math.round(moment().valueOf() / 1000);
  console.log(
    "-------$$$$$$$$$--------",
    teamId,
    status,
    userId,
    team,
    currentDate
  );
  if (teamId != "") {
    const data = await Teams.getTeamById(teamId);
    console.log("getTeamById data - ", data);
    if (team["status"] == 2) {
      let deleted;
      if (data["user_id"]) {
        deleted = await Admin.deleteUser(data["user_id"]);
        console.log("deleteUser deleted : ", deleted);
      } else {
        deleted = await Teams.deleteTeam(teamId);
        console.log("deleteTeam deleted : ", deleted);
      }

      if (deleted) {
        reply.send({
          status: 1,
          message: `The team member ${data.first_name} ${data.last_name} has been deleted.`,
        });

        // Notification
        let notificationMsg = `The team member ${data.first_name} ${data.last_name} has been deleted.`;
        let notificationUrl = "teams";

        // Alert to user of team member updation
        const incrementResult_User = await Admin.incrementField(
          userId,
          "noti_count",
          1
        );
        console.log(
          "incrementResult--to--user-----------",
          incrementResult_User
        );
        let notificationData_user = {
          user_id: userId,
          url: notificationUrl,
          timestamp: currentDate,
          message: notificationMsg,
          status: 1,
          from_id: userId,
        };
        console.log(
          "notificationData--user------------",
          notificationData_user
        );
        const addNotificationResult_user = await Admin.addNotification(
          notificationData_user
        );
        console.log(
          "addNotificationResult--user-------",
          addNotificationResult_user
        );

        // Alert to all admins of product updation

        let adminIds = await Admin.getAllAdminIds();
        let notificationData = {};
        console.log("adminIds====", adminIds);
        for (const adminId of adminIds) {
          console.log("adminId----------", adminId);
          if (adminId != userId) {
            const incrementResult = await Admin.incrementField(
              adminId,
              "noti_count",
              1
            );
            console.log("incrementResult-------------", incrementResult);
            notificationData = {
              user_id: adminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            };
            console.log("notificationData------------", notificationData);
            const addNotificationResult = await Admin.addNotification(
              notificationData
            );
            console.log("addNotificationResult-------", addNotificationResult);
          }
        }
      } else {
        reply.send({ status: 0, message: "Unable to delete the team member!" });
      }
    } else if (team["status"] == 1) {
      team["status"] = 0;
      let deleted = await Teams.updateTeam(teamId, team);
      if (deleted) {
        reply.send({
          status: 1,
          message: `The team member ${data.first_name} ${data.last_name} has been made active.`,
        });

        // Notification
        let notificationMsg = `The team member ${data.first_name} ${data.last_name} has been made active.`;
        let notificationUrl = "teams";

        // Alert to user of team member updation
        const incrementResult_User = await Admin.incrementField(
          userId,
          "noti_count",
          1
        );
        console.log(
          "incrementResult--to--user-----------",
          incrementResult_User
        );
        let notificationData_user = {
          user_id: userId,
          url: notificationUrl,
          timestamp: currentDate,
          message: notificationMsg,
          status: 1,
          from_id: userId,
        };
        console.log(
          "notificationData--user------------",
          notificationData_user
        );
        const addNotificationResult_user = await Admin.addNotification(
          notificationData_user
        );
        console.log(
          "addNotificationResult--user-------",
          addNotificationResult_user
        );

        // Alert to all admins of product updation

        let adminIds = await Admin.getAllAdminIds();
        let notificationData = {};
        console.log("adminIds====", adminIds);
        for (const adminId of adminIds) {
          console.log("adminId----------", adminId);
          if (adminId != userId) {
            const incrementResult = await Admin.incrementField(
              adminId,
              "noti_count",
              1
            );
            console.log("incrementResult-------------", incrementResult);
            notificationData = {
              user_id: adminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            };
            console.log("notificationData------------", notificationData);
            const addNotificationResult = await Admin.addNotification(
              notificationData
            );
            console.log("addNotificationResult-------", addNotificationResult);
          }
        }
      } else {
        reply.send({
          status: 0,
          message: "Unable to activate the team member!",
        });
      }
    } else if (team["status"] == 0) {
      team["status"] = 1;
      let deleted = await Teams.updateTeam(teamId, team);
      if (deleted) {
        reply.send({
          status: 1,
          message: `The team member ${data.first_name} ${data.last_name} has been made inactive.`,
        });

        // Notification
        let notificationMsg = `The team member ${data.first_name} ${data.last_name} has been made inactive.`;
        let notificationUrl = "teams";

        // Alert to user of team member updation
        const incrementResult_User = await Admin.incrementField(
          userId,
          "noti_count",
          1
        );
        console.log(
          "incrementResult--to--user-----------",
          incrementResult_User
        );
        let notificationData_user = {
          user_id: userId,
          url: notificationUrl,
          timestamp: currentDate,
          message: notificationMsg,
          status: 1,
          from_id: userId,
        };
        console.log(
          "notificationData--user------------",
          notificationData_user
        );
        const addNotificationResult_user = await Admin.addNotification(
          notificationData_user
        );
        console.log(
          "addNotificationResult--user-------",
          addNotificationResult_user
        );

        // Alert to all admins of product updation

        let adminIds = await Admin.getAllAdminIds();
        let notificationData = {};
        console.log("adminIds====", adminIds);
        for (const adminId of adminIds) {
          console.log("adminId----------", adminId);
          if (adminId != userId) {
            const incrementResult = await Admin.incrementField(
              adminId,
              "noti_count",
              1
            );
            console.log("incrementResult-------------", incrementResult);
            notificationData = {
              user_id: adminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            };
            console.log("notificationData------------", notificationData);
            const addNotificationResult = await Admin.addNotification(
              notificationData
            );
            console.log("addNotificationResult-------", addNotificationResult);
          }
        }
      } else {
        reply.send({
          status: 0,
          message: "Unable to deactivate the team member!",
        });
      }
    }
  }
};

const viewProfile = async (request, reply) => {
  let { userId } = request.body;
  console.log("userId - ", userId);
  let data = {};
  data["team"] = await Teams.getTeamById(userId);
  data['contact_tags'] = await ContactTags.getAllContactTags()
  data["team_services"] = await Teams.getAllTeamServices(userId);
  // data['custom_field_templates'] = $this -> team_model -> get_all_custom_field_data($team_id);
  // $data['question_templates'] = $this -> team_model -> get_all_question_field_data($team_id);

  /* Requests */
  data["requests"] = await Teams.getAllRequests(userId);

  /* Documents */
  // $data['requested_documents'] = $this -> team_model -> get_all_requested_documents($team_id);
  // $data['sign_agreements'] = $this -> team_model -> get_all_sign_agreements($team_id);
  // $data['files'] = $this -> team_model -> get_all_files($team_id);

  data["services"] = await Teams.getAllServices("ASC");
  // data["workflows"] = await Teams.getAllWorkflows();
  data["workflows"]=await Onboard.getAllTeamFacingWorkflow()
  data["states"] = await Teams.getAllStates("ASC");
  let customFieldTemplateId = await Teams.getAllFieldTemplates(userId,1)
 
  let fieldTemplates=[]
    let i=0;
    for (const row of customFieldTemplateId) {
      let field_template_ids = await OnboardWorkFlowFields.getfieldTemplatesbyStageIdView(row.stage_id);
      if (!empty(field_template_ids)) {
        let templateData = await OnboardWorkFlowStages.getTemplateFormDataById(field_template_ids, 0,userId);
        fieldTemplates[i]=templateData;
        i++;
      }
    }
    let fieldTemplatesNew=[]
    let ids = new Set();
    fieldTemplates.forEach(innerArray => {
      let obj = innerArray[0];
      if (!ids.has(obj.id)) {
        fieldTemplatesNew.push(obj);
        ids.add(obj.id);
      }
    });
    console.log("Hiffiiiiiiiiiii");
  let QuestionTemplateId = await Teams.getAllFieldTemplates(userId,5)
    i=0;
    let QuestionTemplates = []
    for (const row of QuestionTemplateId) {
    let questionnairIds = await OnboardWorkFlowQuestionnaires.getQuestionairebyStageId(row.stage_id);
    
      if (!empty(questionnairIds)) {
        let templateData = await OnboardWorkFlowStages.get_qns_formData_by_id(questionnairIds,0,userId);
        QuestionTemplates[i]=templateData;
            i++;
      }
    }
    let QuestionTemplatesNew=[]
 ids = new Set();
  QuestionTemplates.forEach(innerArray => {
  let obj = innerArray[0];
  if (!ids.has(obj.id)) {
    QuestionTemplatesNew.push(obj);
    ids.add(obj.id);
  }
});
  let allDataEmpty=true;
  if(!empty(QuestionTemplates)||!empty(fieldTemplates)){
    allDataEmpty=false
  }
  if (data) {
    reply.send({
      status: 1,
      data: data,
      fieldTemplates:fieldTemplatesNew,
      QuestionTemplates:QuestionTemplatesNew,
      message: "Profile data fetched successfully",
      allDataEmpty
    });
  } else {
    reply.send({ status: 0, message: "No data found" });
  }
};

const addInternalNote = async (request, reply) => {
  let team = {};
  let teamId = request.body.receivedId;
  let userId = request.body.userId;
  team["internal_note"] = request.body.internalNote;
  let currentDate = Math.round(moment().valueOf() / 1000);
  const updated = await Teams.updateTeam(teamId, team);
  if (updated) {
    let data = await Teams.getTeamById(teamId);
    // Notification
    let notificationMsg = `Internal note has been added to the profile of ${data["first_name"]} ${data["last_name"]}`;
    let notificationUrl = `team/view/${teamId}`;

    // Alert to user of internal note updation
    const incrementResult_User = await Admin.incrementField(
      userId,
      "noti_count",
      1
    );
    console.log("incrementResult--to--user-----------", incrementResult_User);
    let notificationData_user = {
      user_id: userId,
      url: notificationUrl,
      timestamp: currentDate,
      message: notificationMsg,
      status: 1,
      from_id: userId,
    };
    console.log("notificationData--user------------", notificationData_user);
    const addNotificationResult_user = await Admin.addNotification(
      notificationData_user
    );
    console.log(
      "addNotificationResult--user-------",
      addNotificationResult_user
    );

    // Alert to all admins of product updation

    let adminIds = await Admin.getAllAdminIds();
    let notificationData = {};
    console.log("adminIds====", adminIds);
    for (const adminId of adminIds) {
      console.log("adminId----------", adminId);
      if (adminId != userId) {
        const incrementResult = await Admin.incrementField(
          adminId,
          "noti_count",
          1
        );
        console.log("incrementResult-------------", incrementResult);
        notificationData = {
          user_id: adminId,
          url: notificationUrl,
          timestamp: currentDate,
          message: notificationMsg,
          status: 1,
          from_id: userId,
        };
        console.log("notificationData------------", notificationData);
        const addNotificationResult = await Admin.addNotification(
          notificationData
        );
        console.log("addNotificationResult-------", addNotificationResult);
      }
    }
    reply.send({
      status: 1,
      message: "Internal note has been added successfully!",
    });
  } else {
    reply.send({ status: 0, message: "Failed to add internal note!" });
  }
};

const manageWorkflows = async (request, reply) => {
  let team = {};
  let teamId = request.body.receivedId;
  let currentDate = Math.round(moment().valueOf() / 1000);
  team["workflows"] = request.body.workflowIds;
  let userId = request.body.userId;
  const updated = await Teams.updateTeam(teamId, team);
  console.log("manageWorkflows update", updated);
  if (updated) {
    team = await Teams.getTeamById(teamId);
    console.log("manageWorkflows team---", team);
    //     let adminEmails = await Admin.getAllAdminEmails();
    //     let MsgBody = inviteLinkTemplate();
    //     // $email_template = $this -> email_templates -> send_mail_template("SCM Login");
    //     MsgBody = MsgBody.replace(/\[SUBJECT\]/g, `${portalName} - New onboarding stages assigned`);
    //     MsgBody = MsgBody.replace(/\[NAME\]/g, `"Hello ${team.first_name} ${team.last_name},`);
    //     MsgBody = MsgBody.replace(
    //         /\[CONTENT\]/g,
    //         `New onboarding stages has been assigned to you. Please login to complete onboarding.`
    //     );
    //     MsgBody = MsgBody.replace(/\[BASE_URL\]/g, baseUrl);

    //     // Send reset email
    //     const mailOptions = {
    //         from: MAIL_SENDER,
    //         to: team.email,
    //         subject: `${portalName} - New onboarding stages assigned`,
    //         html: MsgBody,
    //     };

    //     transporter.sendMail(mailOptions, (error, info) => {
    //         if (error) {
    //             console.error("Mail sending error -",error);
    //             reply.status(500).send({ message: "Error sending email" });
    //         } else {
    //             console.log("Email sent: " + info.response);
    //             reply.send({ status: 1, message: "Email sent successfully" });
    //         }
    //     });
    if (team.user_id) {
      // Notification
      let notificationMsg = `The workflows has been updated for the profile ${team.first_name} ${team.last_name}.`;
      let notificationUrl = `team/view/${teamId}`;

      // Alert to team member of workflow updation
      const incrementResult_team = await Admin.incrementField(
        team.user_id,
        "noti_count",
        1
      );
      console.log("incrementResult--to--team-----------", incrementResult_team);
      let notificationData_team = {
        user_id: team.user_id,
        url: "onboard/process-team",
        timestamp: currentDate,
        message: "New onboarding stages has assigned to you",
        status: 1,
        from_id: userId,
      };
      console.log("notificationData--team------------", notificationData_team);
      const addNotificationResult_team = await Admin.addNotification(
        notificationData_team
      );
      console.log(
        "addNotificationResult--team-------",
        addNotificationResult_team
      );

      // Alert to user of workflow updation
      const incrementResult_User = await Admin.incrementField(
        userId,
        "noti_count",
        1
      );
      console.log("incrementResult--to--user-----------", incrementResult_User);
      let notificationData_user = {
        user_id: userId,
        url: notificationUrl,
        timestamp: currentDate,
        message: notificationMsg,
        status: 1,
        from_id: userId,
      };
      console.log("notificationData--user------------", notificationData_user);
      const addNotificationResult_user = await Admin.addNotification(
        notificationData_user
      );
      console.log(
        "addNotificationResult--user-------",
        addNotificationResult_user
      );

      // Alert to all admins of product updation

      let adminIds = await Admin.getAllAdminIds();
      let notificationData = {};
      console.log("adminIds====", adminIds);
      for (const adminId of adminIds) {
        console.log("adminId----------", adminId);
        if (adminId != userId) {
          const incrementResult = await Admin.incrementField(
            adminId,
            "noti_count",
            1
          );
          console.log("incrementResult-------------", incrementResult);
          notificationData = {
            user_id: adminId,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: userId,
          };
          console.log("notificationData------------", notificationData);
          const addNotificationResult = await Admin.addNotification(
            notificationData
          );
          console.log("addNotificationResult-------", addNotificationResult);
        }
      }
      reply.send({
        status: 1,
        message: `Workflows for ${team.first_name} ${team.last_name} has been updated successfully!`,
      });
    } else {
      reply.send({ status: 1, message: `Workflows  has been updated successfully!` });
    }
  }
  else{
    reply.send({ status: 0, message: `Failed to update workflows!` });
  }
};

const addToRequest = async (request, reply) => {
  let teamId = request.body.receivedId;
  let requestIdsString = request.body.reqIds;
  let requestIds = requestIdsString.split(",").map(Number);
  let userId = request.body.userId;
  let currentDate = Math.round(moment().valueOf() / 1000);
  let partnerRequests = [];
  let partnerRequestId;
  console.log("requestIds", requestIds);
  if (requestIds) {
    for (const requestId of requestIds) {
      let request = {
        team_user_id: teamId,
        request_id: requestId,
        last_seen: currentDate,
        timestamp: currentDate,
        added_by: userId,
        status: 1,
      };
      partnerRequests.push(request);
    }
  }
  console.log("partnerRequests", partnerRequests);
  if (partnerRequests) {
    partnerRequestId = await Teams.batchInsertTeamRequest(partnerRequests);
  }
  console.log("partnerRequestId - ", partnerRequestId);
  if (partnerRequestId) {
    let team = await Teams.getTeamById(teamId);
    // Notification
    let notificationMsg = `Requests has been assigned to ${team["first_name"]} ${team["last_name"]}.`;
    let notificationUrl = `team/view/${teamId}`;

    // Alert to user of team member details updation
    const incrementResultUser = await Admin.incrementField(
      userId,
      "noti_count",
      1
    );
    console.log("incrementResult--to--user-----------", incrementResultUser);
    let notificationData_user = {
      user_id: userId,
      url: notificationUrl,
      timestamp: currentDate,
      message: notificationMsg,
      status: 1,
      from_id: userId,
    };
    console.log("notificationData--user------------", notificationData_user);
    const addNotificationResult_user = await Admin.addNotification(
      notificationData_user
    );
    console.log(
      "addNotificationResult--user-------",
      addNotificationResult_user
    );

    // Alert to all admins (except current logged in user) of team member details updation

    let adminIds = await Admin.getAllAdminIds();
    let notificationData = {};
    console.log("adminIds====", adminIds);
    for (const adminId of adminIds) {
      console.log("adminId----------", adminId);
      if (adminId != userId) {
        const incrementResult = await Admin.incrementField(
          adminId,
          "noti_count",
          1
        );
        console.log("incrementResult-------------", incrementResult);
        notificationData = {
          user_id: adminId,
          url: notificationUrl,
          timestamp: currentDate,
          message: notificationMsg,
          status: 1,
          from_id: userId,
        };
        console.log("notificationData------------", notificationData);
        const addNotificationResult_admin = await Admin.addNotification(
          notificationData
        );
        console.log(
          "addNotificationResult_admin-------",
          addNotificationResult_admin
        );
      }
    }
    reply.send({
      status: 1,
      message: "Requests has been assigned successfully!",
    });
  } else {
    reply.send({ status: 0, message: "Failed to assign requests!" });
  }
};

const getRequests = async (request, reply) => {
  let teamId = request.body.teamId;
  let requests = await Teams.getRequests("DESC", teamId, true);
  console.log("getRequests result ----------- ", requests[0].length);
  if (requests[0]) {
    return requests[0];
  } else {
    return false;
  }
};

const searchTeam = async (request, reply) => {
  let where = [];
  let serviceIds = request.body.serviceIds;
  let stateIds = request.body.stateIds;
  let availabilityIds = request.body.availabilityIds;
  if (serviceIds) {
    where["service_ids"] = serviceIds;
  }
  if (stateIds) {
    where["state_ids"] = stateIds;
  }
  if (availabilityIds) {
    where["availability_ids"] = availabilityIds;
  }
  let data;
  let teamMembers = await Teams.getAllTeams(false, where);
  data["team_members"] = teamMembers.data
  if (data) {
    reply.send({
      status: 1,
      result: data,
      message: "Search data fetched successfully",
    });
  } else {
    reply.send({ status: 0, message: "error searching data" });
  }
};

const isPrivileged = async (request, reply) => {
  let permissions = 2;
  let result = await Admin.isPrivileged(permissions);
  if (result) {
    reply.send({ status: 1, message: result });
  } else {
    reply.send({ status: 0, message: "Privilages fetching error" });
  }
};

const sendMessage = async (request, reply) => {
  try {
    let userId = request.body.userId; //logged-in user-Id
    let msg = request.body.msg;
    let to = request.body.to;
    let error = "";
    let timestamp = Math.round(moment().valueOf() / 1000);
    let result = false;
    console.log("to, userId, msg, timestamp", to, userId, msg, timestamp);
    if (msg != "") {
      result = await Teams.setPartnerMessage(to, userId, msg, timestamp);
    }
    msg_to = await Admin.getUserById(to);
    msg_from = await Admin.getUserById(userId);
    console.log("send message id ---- ", result);
    if (result !== false) {
      return { msg: 1 };
    }
  } catch (error) {
    console.error(error);
    reply.code(500).send({ error: "Internal Server Error" });
  }
};

const viewMessage = async (request, reply) => {
  const userId = request.body.userId; //logged-in user-Id
  const lastUser = request.body.toId;
  let messages, userName, updateMsgResult;
  console.log("userId,lastUser", userId, lastUser);
  if (lastUser) {
    messages = await Teams.getLastUserMsg(userId, lastUser);
    console.log("messages", messages);
  }
  if (messages) {
    userName = await Teams.getUserName(lastUser);
    const messageCount = messages.length;
    for (let i = 0; i < messageCount; i++) {
      const chatId = messages[i]["chat_id"];
      try {
        updateMsgResult = await Teams.updateMsg(chatId, userId);
        console.log(`Message updated for chat ID ${chatId}:`, updateMsgResult);
      } catch (error) {
        console.error(`Error updating message for chat ID ${chatId}:`, error);
      }
    }
    reply.send({
      status: 1,
      message: messages,
      userName: userName,
      updateMsgResult: updateMsgResult,
    });
  } else {
    reply.send({ status: 1, message: "Failed to fetch messages" });
  }
};

const getNewMsgCount = async (request, reply) => {
  const toId = request.body.userId;
  const userId = request.body.toId;
  console.log("toId ----------- ", toId);
  const msgCnt = await Teams.getNewMsgCount(userId, toId);
  console.log("msgCnt *******************", msgCnt);
  if (msgCnt > 0) {
    reply.send({ status: 1, message: msgCnt });
  } else if (msgCnt === 0) {
    reply.send({ status: 2, message: "No new messages" });
  } else {
    reply.send({ status: 0, message: "New message fetching error" });
  }
};

const getAllUsers = async (request, reply) => {
  try {
    const userId = request.body.userId; //logged-in user
    const userType = request.body.userType;
    let selectedUser = request.body.selectedUser;
    console.log("++++++++++++++++selectedUser", userId, selectedUser);
    // const userId = 1;	//logged-in user
    // const userType = 2;
    // let selectedUser;

    if (!selectedUser) {
      selectedUser = await Teams.getLastUser(userId);
    }
    const users = await Teams.getAllChatUsers(userId,userType);
    if (users) {
      for (const user of users) {
        user.msgCnt = await Teams.getTotalNewMsgCount(user.id);
      }
    }
    const totalCount = await Teams.getTotalNewMsgCount(userId);
    reply.send({
      status: 1,
      selectedUser: selectedUser,
      users: users,
      totalCount: totalCount,
    });
  } catch (error) {
    console.error(error);
    throw error;
  }
};

const updateProfilePic=async(req,res)=>{
  try {
    let TeamUserId = req.body.userId
    let teamData={}
    teamData.profile_pic=req.body.imgURL
    let updated = await Admin.updateUser( TeamUserId, teamData )
    if(updated){
      res.send({ status:1,message:'Profile image updated successfully' })
    }else{
      res.send({ status:0,message:'Profile image updated failed' })
    }
  } catch (error) {
    console.log(error,'error in uploading image')
  }
}

const updateCoverImage=async(req,res)=>{
  try {
    let TeamUserId = req.body.userId
    let teamData={}
    teamData.company_logo=req.body.imgURL
    let updated = await Admin.updateUser( TeamUserId, teamData )
    if(updated){
      res.send({  
        status:1,message:'Cover Image updated successfully'
      })
    }else{
      res.send({
        status:0,message:'Cover Image updated failed'
      })
    }
  } catch (error) {
    console.log(error,'error in uplaoding image')
  }
}


const saveTeamMemberCartOrder = async (req, res) => {
  try {
    const { reorderedItems } = req.body;
    console.log("updatedCardsupdatedCardsupdatedCards",reorderedItems)
    await Teams.updateCardOrderStaffMember(reorderedItems);
    res.status(200).send({ status: 1, message: 'Order saved' });
  } catch (error) {
    console.log('saveReq error : ',error)
    res.status(500).send({ status: 500, message: 'Error saving order', error:error });
  }
}

const updateNotificationSettings = async (request, reply) => {
  try {
    const { userId, smsEnabled, emailEnabled } = request.body;

    const updateData = {
      smsEnabled: smsEnabled ?? 0,
      emailEnabled: emailEnabled ?? 0,
    };
    console.log("updateData", updateData);
    const result = await Admin.updateUser(userId, updateData);

    if (result) {
      reply.send({
        status: 1,
        message: 'Notification settings updated successfully',
      });
    } else {
      reply.send({
        status: 0,
        message: 'Failed to update notification settings',
      });
    }
  } catch (error) {
    console.error("Error in updateNotificationSettings:", error);
    reply.send({ status: 0, message: 'Server error while updating settings' });
  }
};

const getNotificationSettings = async (request, reply) => {
  try {
    const { userId } = request.body;
    console.log('userId', userId)

    const result = await Admin.getNotificationSettingsByUserId(userId);

    if (result) {
      reply.send({
        status: 1,
        message: "Notification settings fetched successfully",
        data: result,
      });
    } else {
      reply.send({
        status: 0,
        message: "User not found or settings unavailable",
      });
    }
  } catch (error) {
    console.error("Error in getNotificationSettings:", error);
    reply.send({
      status: 0,
      message: "Server error while fetching notification settings",
    });
  }
};

const getAllProjectSalesRepsData = async (request, reply) => {
  let { usersId, usersType, isClient } = request.body;
  let page = request.body.page
  let search = request.body.search
  let rowPerpage = request.body.rowsPerPage

  let teamData = [];
  if (usersType !== 1 && usersType !== 3) {
    teamData = await Admin.getTeamByUserId(usersId);
  }
  let team_members = await Teams.getAllProjectSalesRepsMembers(
    true,
    "",
    usersId,
    usersType,
    teamData,
    page,
    rowPerpage,
    search,
    isClient
  );
  
  if (team_members && team_members.data && team_members.data.length > 0) {
    const userId = parseInt(usersId);
    const sortedData = team_members.data.sort((a, b) => {
      const aIsLoggedIn = a.id === userId || a.user_id === userId;
      const bIsLoggedIn = b.id === userId || b.user_id === userId;
      if (aIsLoggedIn && !bIsLoggedIn) return -1;
      if (!aIsLoggedIn && bIsLoggedIn) return 1;
      return 0;
    });
    team_members.data = sortedData;
  }
  
  let states = await Teams.getAllStates("ASC");
  let services = await Teams.getAllServices("ASC");
  let availabilities = await Teams.getAllAvailabilities();
  // let workflows = await Teams.getAllWorkflows();
  let workflows=await Onboard.getAllTeamFacingWorkflow()

 console.log(team_members,'-----------team_members')
  reply.send({
    status: 1,
    message: "Team data fetched successfully",
    team_members: team_members,
    states: states,
    services: services,
    availabilities: availabilities,
    workflows: workflows,
    teamData: teamData,
  });
};

module.exports = {
  getAllTeamsData,
  getAllTeamsDataCollaborators,
  getAllTeamsDataForChat,
  getTeamById,
  getAllUserRoles,
  addTeamMembers,
  deleteTeam,
  updateTeam,
  updateUser,
  addInternalNote,
  viewProfile,
  manageWorkflows,
  addToRequest,
  getRequests,
  searchTeam,
  isPrivileged,
  sendMessage,
  viewMessage,
  getAllUsers,
  getNewMsgCount,
  getAllServices,
  updateProfilePic,
  updateCoverImage,
  saveTeamMemberCartOrder,
  sendMessageToPhoneNumber,
  updateNotificationSettings,
  getNotificationSettings,
  updateUserActive,
  helpDeskUserActive,
  getAllSalesRepsData,
  getAllProjectSalesRepsData,
};
