const sgMail = require('@sendgrid/mail')
const { SENDGRID_API_KEY, BASE_URL, portalName, SEND_EMAIL } = require("../constants/constant")
const { sendPartnerMail, activateProfile } = require("../constants/emailTemplates");
const Admin = require ('../models/admin')
const moment = require("moment");
const sequelize = require("../config/dbconnection");
const { empty, arrayDiffAssoc, generateUniquePin } = require('../Helpers/Common');
const Driver = require('../models/driver')
const Installation = require('../models/installation')
const ProjectTask = require('../models/projectTask')
const crypto = require("crypto");
const Password = require("node-php-password");
const { getRouteDatabyId } = require('../models/routes');
let currentDate = Math.round(moment().valueOf() / 1000);
const RequestUpdates = require('../models/requestUpdates')

const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
const { MAIL_SENDER, TWILIO_PHONE, TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN } = require("../constants/constant");
const client = require("twilio")(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);

function formatHoursToHHMMSS(hours) {
  const duration = moment.duration(hours, "hours");
  const formattedDuration = moment
    .utc(duration.asMilliseconds())
    .format("HH:mm:ss");
  return formattedDuration;
}

const transporter = nodemailer.createTransport({
  host: 'mail.signwisesolutions.com', // Replace with your domain's mail server (WHM SMTP host)
  port: 465, // 465 for secure SMTP (SSL), or 587 for TLS
  secure: true, // Use true for 465, false for other ports
  auth: {
    user: 'noreply@signwisesolutions.com', 
    pass: 'signwise@2024', 
  },
});

const AddDrivers=async(req,res)=>{
  try {
    let {userId,values} = req.body 
    let data={}
    if(!empty(values)){
      const isEmailExist = await Admin.isEmailExist(values.email);
      if(!isEmailExist){
        data['name']= values.name
        data['email']= values.email
        data['phone']= values.phone
        data['phone_country_code'] = values.phone_country_code
        // data['blood_group']= values?.blood_group?.value
        data['licence_number']= values.licence_number
        data['licence_image']= values.licence_image
        data['hourly_rate']= values.hourly_rate
        data['gender']= values.gender
        data['status']= 1
        data['address'] = values.address
        data['profile_photo'] = values.profile_photo
        data['timestamp']= currentDate
        data['added_by']= userId
        data['verified'] = values?.verified == true ? 1 : 0;
        let user={}
        user['first_name'] = data['name']
        user['company_name'] = data['name']
        user['email'] = data['email']
        user['username'] = data['email'];
        let password=crypto.randomBytes(5).toString("hex")
        let hashedPassword = Password.hash(password);
        user['password'] = hashedPassword;
        user['admin_password']=password
        user['profile_pic'] = data['profile_photo'];
        user['status'] = 1;
        user['user_type'] = 24;
        user['activated_by_admin']=1;
        // Generate unique PIN for user
        user['user_pin_unique'] = await generateUniquePin(sequelize);
        let addedUserId = await Admin.addUser(user);
        let result = ''
        if(addedUserId){
          data['user_id'] = addedUserId;
          data['status'] = 1;
          result = await Driver.addDriver(data)
          if(result){ 
          ///////////notification////////////////////////
            let notification_msg = `New Driver <strong>${data['name']}</strong> has been added .`
            let notification_url = `driver/view/${result.id}`
            const incrementResult_User = await Admin.incrementField(
              userId,
              "noti_count",
              1
            );
  
            let notificationData_user = {
              user_id: userId,
              url: notification_url,
              timestamp: currentDate,
              message: notification_msg,
              status: 1,
              from_id: userId,
            };
  
            const addNotificationResult_user = await Admin.addNotification(
              notificationData_user
            );
            let adminIds = await Admin.getAllAdminIds();
            for (let eachadminIds of adminIds) {
              if (eachadminIds != userId) {
                let incrementResult = await Admin.incrementField(eachadminIds, 'noti_count', 1)
                let addNotification = {
                  user_id: eachadminIds,
                  url: notification_url,
                  timestamp: moment().unix(),
                  message: notification_msg,
                  status: 1,
                  from_id: userId,
                }
                const addNotificationResult = await Admin.addNotification(addNotification);
              }
            }
            let subject = portalName + " - Your account has been activated";
            let welcome = "Hello " + user['company_name'] + ","
            let email_content = `Thank you for creating your account. 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 mailOptions = {
              to:  user.email,  
              from: '"SignWise Solutions" <noreply@signwisesolutions.com>',
              subject: subject,
              text: subject,
              html: message,
            }
            try {
              if(SEND_EMAIL){
              await transporter.sendMail(mailOptions);
              console.log('Email sent');
              }
            } catch (error) {
              console.error('##########Err', error);
            }
            let adminEmails = await Admin.getAllAdminEmails();
            let adminSubject = portalName + " - A new user has been registered";
            let adminWelcome = "Hello ! Admin" + ","
            let admin_email_content = `A new user 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) {
              const mailOptions = {
                to:  row,  
                from: '"SignWise Solutions" <noreply@signwisesolutions.com>',
                subject: adminSubject,
                text: adminSubject,
                html: adminSubject,
              }
              try {
                if(SEND_EMAIL){
                await transporter.sendMail(mailOptions);
                console.log('Email sent');
                }
              } catch (error) {
                console.error('##########Err', error);
              }
            }
          }
        }
        if(!empty(result) && !empty(addedUserId)){
          res.send({ status:1,message:`Driver ${result['name']} added successfully` })
        }else{
          res.send({ status:0,message:'Failed to add driver' })
        }
      }else{
        res.send({ status:0, message:'Email ID already exists. Please use another Email ID ' })
      }
    }
    else{
      res.send({ status:0,message:'Please fill all the fields' }) 
    }
  } catch (error) {
    console.log(error,'error in adding drivers')
    res.send({ status:500, message:'error in adding drivers', error:error }) 
  }
}

const getAllDrivers=async(req,res)=>{
    try {
      const {userId, userType} = req.body
     let result = await Driver.getAllDrivers(userId, userType)
     if(!empty(result)){
        res.send({
            status:1 ,result
        })
     }else{
        res.send({
            status:0
        })
     }
    } catch (error) {
        console.log(error+'error in fetching drivers')
    }
}

const getDriverDatabyId=async(req,res)=>{
    try {
        let {id} = req.body
        let result = await Driver.getDriverById(id)
        if(result){
            res.send({
                status:1,result
            })
        }else{
            res.send({
                status:0,status:0,message:'Data not found'
            })
        }
    } catch (error) {
      console.log(error)
      res.send({
        status:500,message:'Error fetching data'
      })
    }
}
const getDriverDatabyUserId=async(req,res)=>{
    try {
        let {id} = req.body
        let result = await Driver.getDriverByuserId(id)
        if(result){
            res.send({
                status:1,result
            })
        }else{
          res.send({
            status:0,message:'Data not found'
          })
        }
    } catch (error) {
        console.log(error)
        res.send({
          status:500,message:'Error fetching data'
      })
    }
}
const updateDriver=async(req,res)=>{
  try {
    let {userId, values, id, driverUserId} = req.body
    if(!empty(values)){
      const isEmailExist = await Admin.isEmailExist(values.email,driverUserId);
      if(!isEmailExist){
        let data={} 
        data['name']= values.name
        data['email']= values.email
        data['phone']= values.phone
        data['phone_country_code'] = values.phone_country_code
        //  data['blood_group']= values?.blood_group?.value
        data['licence_number']= values.licence_number
        data['licence_image']= values.licence_image
        data['hourly_rate']= values.hourly_rate
        data['gender']= values.gender
        data['status']= 1
        data['address'] = values.address
        data['profile_photo'] = values.profile_photo
        data['timestamp']= currentDate
        data['added_by']= userId
        data['verified'] = values?.verified == true ? 1 : 0;               
        let result = await Driver.updateDriver(data,id)
        let user={}
        user['first_name'] = data['name'];
        user['company_name'] = data['name']
        user['username'] = data['email'];
        user['email'] = data['email'];
        user['profile_pic'] = data['profile_photo'];
        if(values.password && values.password !== ""){
          let password = values.password;
          let hashedPassword = Password.hash(password);
          user['password'] = hashedPassword;
          user['admin_password']=password
        }
        const updateUserResult = await Admin.updateUser(driverUserId, user);
        if(result){
          let notification_msg = `Driver <strong>${data['name']}</strong> has been updated.`
          let notification_url = `driver/view/${id}`
          const incrementResult_User = await Admin.incrementField( userId,  "noti_count", 1 );
          let notificationData_user = {
            user_id: userId,
            url: notification_url,
            timestamp: currentDate,
            message: notification_msg,
            status: 1,
            from_id: userId,
          };
          const addNotificationResult_user = await Admin.addNotification( notificationData_user );
          let adminIds = await Admin.getAllAdminIds();
          for (let eachadminIds of adminIds) {
            if (eachadminIds != userId) {
              let incrementResult = await Admin.incrementField(eachadminIds, 'noti_count', 1)
              let addNotification = {
                user_id: eachadminIds,
                url: notification_url,
                timestamp: moment().unix(),
                message: notification_msg,
                status: 1,
                from_id: userId,
              }
              const addNotificationResult = await Admin.addNotification(addNotification);
            }
          }
          res.send({ status:1,message:`Driver ${data['name']} updated successfully` })
        }else{
          res.send({ status:0,message:'Failed to update driver' })
        }
      } else {
        res.send({ status:0, message:'Email ID already exists. Please use another Email ID ' })
      }
    } else {
      res.send({ status:0,message:'Please fill the fields' }) 
    }
  } catch (error) {
    console.log(error)
    res.send({
      status:500,message:'Error updating driver', error: error
    })
  }
}
const changeStatusOfDriver=async(req,res)=>{
    try {
        let {id,userId,status} = req.body
        let data={}
        data['status']= status
        let result = await Driver.updateDriver(data,id)
         
        if(result){
        if(data['status']===0){
          res.send({
            status:0,message:'Driver Deactivated successfully'
          })
        }else if(data['status']===1){
            res.send({
                status:1,message:'Driver activated successfully'
              })
        }else if(data['status']===2){
            res.send({
                status:2,message:'Driver Deleted successfully'
              })
        }
    }else{
        res.send({
            status:false
        })
    }
    } catch (error) {
        console.log(error)
    }
}
const getAllActiveDrivers=async(req,res)=>{
  try {
     let result = await Driver.getAllActiveDrivers()
     if(!empty(result)){
       res.send({
        status:1,drivers:result
       })
     }
  } catch (error) {
    console.log(error)
  }
}
const getAllVerifiedActiveDrivers = async (req,res) => {
  try {
    let result = await Driver.getAllVerifiedActiveDrivers()
    if(result){
       res.send({ status:1,Message : 'Drivers fetched successfully',drivers:result })
    }else{
      res.send({ status:0,Message : 'No drivers found' })
    }
  } catch (error) {
    console.log(error)
    res.send({ status:500,Message : 'Error fetching drivers'})
  }
}

const getAssignedRoutesByDriver =async (req,res) =>{
  try{
    const {driverId} = req.body
    const result = await Driver.getAssignedRoutesByDriver(driverId)
    if(result){
      for(const route of result){
        const routeId = route.route_id
        const routeData = await Driver.getAssignedInstallationsByRoute(driverId,routeId)
        route.routeData = routeData
      }
      res.send({ status:1, Message : 'Routes fetched successfully',routes:result })
    }else{
      res.send({ status:0,Message : 'No routes found' })
    }
  }catch(error){
    console.log('Error : ',error);
  }  
}

const getAcceptedRoutesByDriver =async (req,res) =>{
  try{
    const {driverId,isInstaller,userId,userType,hasAcceptedRoutesPermission} = req.body
    console.log('hasAcceptedRoutesPermission/////',hasAcceptedRoutesPermission);
    // const driverData = await Driver.getDriverById(driverId);
    const driverData = await Driver.getUserDataById(userId);
    console.log('driverData',driverData)
    const newUserId = driverData[0]?.user_id
    let newhours = 0
    // const result = await Driver.getAcceptedRoutesByDriver(driverId)
    const result = await Driver.getAcceptedRoutes(driverId,isInstaller,userId,userType,hasAcceptedRoutesPermission)
    if(result){
      for(const route of result){
        const routeId = route.route_id
        const projectId = route.project_id
        // const routeData = await Driver.getAcceptedInstallationsByRoute(driverId,routeId)
        const routeData = await Driver.getAcceptedInstallationsByRouteForApp(driverId,routeId,isInstaller,userId,userType,hasAcceptedRoutesPermission)
        const projectFiles = await Installation.getProjectFilesByProjectId(projectId)
        route.projectFiles = projectFiles && projectFiles.length > 0 ? projectFiles : []

        let reqAttachmentsFiles = await ProjectTask.fetchAllFilesFromRequest(null,projectId)
        console.log('reqAttachmentsFiles', reqAttachmentsFiles)
        const files = []
    
        
        if (reqAttachmentsFiles && reqAttachmentsFiles.length > 0) {
          reqAttachmentsFiles.forEach(file => {
            const ext = file.extension?.toLowerCase();
    
            // list of non-image allowed extensions
            const nonImageExts = ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt"];
    
            if (nonImageExts.includes(ext)) {
              files.push(file);
            }
          });
          }
        route.hasProjectFiles = (projectFiles && projectFiles.length || reqAttachmentsFiles && files.length) > 0 ? 1 : 0
    

        if(routeData && routeData?.length > 0){
          for(const rData of routeData){
            rData.hasProjectFiles = route.hasProjectFiles
            let updates = await RequestUpdates.fetchAllUpdates(5, rData.request_id, null, null, userId, userType)
            rData.updates = updates
            const instId = rData?.id
            const installationData = await Installation.fetchApointmentById(instId);
            if(installationData && installationData?.length > 0){
              let requestId = installationData[0]?.request_id;
              let installationNewHours = 0; 
              const stafftimelogs = await ProjectTask.fetchStaffTaskTimelog( false, newUserId, false, false, false, instId );
              if (stafftimelogs && stafftimelogs?.length > 0) {
                for (const subData of stafftimelogs) {
                  if (parseInt(subData.installation_id) == instId) {
                    const startMoment = moment.unix(subData.start_time);
                    let endMoment;
                    if (subData.end_time !== null) {
                        endMoment = moment.unix(subData.end_time);
                    } else {
                        endMoment = moment();
                    }
                    const duration = moment.duration(endMoment.diff(startMoment));
                    const hours = duration.asHours();
                    subData['hours'] = hours
                    if (!isNaN(hours)) {
                      installationNewHours += hours;
                      newhours += hours;
                    }
                  }
                }
              }
              rData['newhours'] = installationNewHours;
              
              installationNewHours = formatHoursToHHMMSS(installationNewHours);
              rData['clockedHours'] = installationNewHours;
            }
          }
          route.routeData = routeData
        }
      }
      res.send({ status:1, Message : 'Routes fetched successfully',routes:result })
    }else{
      res.send({ status:0,Message : 'No routes found' })
    }
  }catch(error){
    console.log('Error : ',error);
  }  
}

const getDeliveredRoutesByDriver =async (req,res) =>{
  try{
    // const {driverId} = req.body
    const {driverId,isInstaller,userId,userType} = req.body

    // const result = await Driver.getDeliveredRoutesByDriver(driverId)
    console.log('userTypeuserTypeuserType',userType)
    const result = await Driver.getDeliveredRoutesForApp(driverId,isInstaller,userId,userType)
    if(result){
      for(const route of result){
        const routeId = route.route_id
        // const routeData = await Driver.getDeliveredInstallationsByRoute(driverId,routeId)
        const routeData = await Driver.getDeliveredInstallationsByRouteforApp(driverId,routeId,isInstaller,userId,userType)
        route.routeData = routeData
      }
      res.send({ status:1, Message : 'Routes fetched successfully',routes:result })
    }else{
      res.send({ status:0,Message : 'No routes found' })
    }
  }catch(error){
    console.log('Error : ',error);
  }  
}

const getFailedRoutesByDriver =async (req,res) =>{
  try{
    // const {driverId} = req.body
    const {driverId,isInstaller,userId,userType} = req.body

    // const result = await Driver.getFailedRoutesByDriver(driverId)
    const result = await Driver.getFailedRoutesforApp(driverId,isInstaller,userId,userType)
    if(result){
      for(const route of result){
        const routeId = route.route_id
        // const routeData = await Driver.getFailedInstallationsByRoute(driverId,routeId)
        const routeData = await Driver.getFailedInstallationsByRouteForApp(driverId,routeId,isInstaller,userId,userType)
        route.routeData = routeData
      }
      res.send({ status:1, Message : 'Routes fetched successfully',routes:result })
    }else{
      res.send({ status:0,Message : 'No routes found' })
    }
  }catch(error){
    console.log('Error : ',error);
  }  
}

const acceptAssignedInstallationsByDriver = async (req,res) => {
  const {instId, route_id, driverId, userId} = req.body;
  let currentDate = Math.round(moment().valueOf() / 1000);
  let resultArray = []
  let data = {};
  data['status'] = 2
  for (const id of instId){
    const result = Installation.updateInstallationStatus(data,id,route_id)
    let installationData = await Installation.fetchApointmentById(id)


    if(installationData?.length > 0){
        let installation = installationData[0]
        // Notification
        let notificationMsg = `Installation ${installation.name} has been accepted by ${installation.driver_name}.`;
        let notificationUrl = "installation";
        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 );

        if(installation?.fcmToken){
          const message = {
            data: {
                // Your custom data payload if needed
                // Example:
                score: '850',
                time: '2:45'
            },
            notification: {
                title: 'Installation',
                body: `Installation ${installation.name} has been accepted by ${installation.driver_name}.`
            },
            token: installation.fcmToken // Add registration tokens of specific devices here
          };


          admin.messaging().send(message)
              .then((response) => {
              console.log('Successfully sent message:', response);
            // Assuming 'res' is used to respond to an HTTP request
              res.send({ success: true, response });
              })
              .catch((error) => {
                console.error('Error sending message:', error);
            res.status(500).send({ error: error.message });
          });
        }

        let adminIds = await Admin.getAllAdminIds();
        let notificationData = {};
        for (const adminId of adminIds) {
            if (adminId != userId) {
            const incrementResult = await Admin.incrementField(adminId, "noti_count", 1);
            notificationData = {
                user_id: adminId,
                url: notificationUrl,
                timestamp: currentDate,
                message: notificationMsg,
                status: 1,
                from_id: userId,
            };
            const addNotificationResult = await Admin.addNotification( notificationData );    
            }
        }
    }
    resultArray.push(result)
  }
  if(resultArray?.length === instId?.length){
    res.send({status:1,message:"Route accepted successfully"})
  }else{
    res.send({status:0,message:`Failed to accept  route`})
  }
}

const cancelAssignedRouteByDriver = async (req,res) => {
  const {instId, route_id, driverId, userId} = req.body;
  let currentDate = Math.round(moment().valueOf() / 1000);
  let resultArray = []
  let data = {};
  data['status'] = 1
  for (const id of instId){
    const result = Installation.updateInstallationStatus(data,id,route_id)
    resultArray.push(result)
  }
  if(resultArray?.length === instId?.length){
    let routeData = await getRouteDatabyId(route_id);
    if(routeData?.length > 0){
        let route = routeData[0]
        // Notification
        let notificationMsg = `Assigned Route ${route?.name} has been cancelled.`;
        let notificationUrl = "transportation";
        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) {
            if (adminId != userId) {
            const incrementResult = await Admin.incrementField(adminId, "noti_count", 1);
            notificationData = {
                user_id: adminId,
                url: notificationUrl,
                timestamp: currentDate,
                message: notificationMsg,
                status: 1,
                from_id: userId,
            };
            const addNotificationResult = await Admin.addNotification( notificationData );    
            }
        }
    }

    const getUserData = await Driver.getDriverByuserId(userId)

    if(getUserData){

      const message = {
        data: {
            // Your custom data payload if needed
            // Example:
            score: '850',
            time: '2:45'
        },
        notification: {
            title: 'Route',
            body: `Assigned Route has been cancelled.`
        },
        token: getUserData.fcmToken // Add registration tokens of specific devices here
    };
  
  
    admin.messaging().send(message)
               .then((response) => {
                console.log('Successfully sent message:', response);
             // Assuming 'res' is used to respond to an HTTP request
               res.send({ success: true, response });
                })
               .catch((error) => {
                 console.error('Error sending message:', error);
             res.status(500).send({ error: error.message });
           });

    }
    res.send({status:1,message:"Route cancelled successfully"})
  }else{
    res.send({status:0,message:`Failed to cancel route`})
  }
}

const sendMessageToPhoneNumber = async (phoneNumber,OTP) => {
  try {


     const messageContents = `SignWise Solutions-
    Hello ,
    Your OTP for reset your password is ${OTP}.
    `;

    const message = await client.messages.create({
      body: messageContents,
      to: `+91${phoneNumber}`,
      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",error);
  }
};

const sendMessageToEmail =  async(email,OTP)=>{


  const mailOptions = {
    to:  email,  
    from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
    subject: `Signwise Sollutions`,
    text: `OTP for Reset your password`,
    html: `${OTP} is the OTP for reset your password`,
  }
  try {
    if(SEND_EMAIL){
    await transporter.sendMail(mailOptions);
    console.log('Email sent');
    }
    
  } catch (error) {
    console.error('##########Err', error);
   
  }
}


const sendOtpToDriver = async (req, res) => {
  try {
    const { method, contact } = req.body;
    const OTP = Math.floor(1000 + Math.random() * 9000); 

    if (!method || !contact) {
      return res.status(400).send({ message: "Method and contact are required." });
    }
    let isExisting= false
    if (method === 'sms') {
       isExisting = await Admin.findUserByPhoneNumber(contact)
      if(isExisting){
        await sendMessageToPhoneNumber(contact, OTP);
      }else{
        return res.send({ message: "User not found",status:2 });
      }
    } else if (method === 'email') {
       isExisting = await Admin.findUserByEmail(contact)
      if(isExisting){
      await sendMessageToEmail(contact, OTP);
      }else{
        return res.send({ message: "User not found",status:2 });
      }
    } else {
      return res.status(400).send({ message: "Invalid method. Use 'sms' or 'email'.",status:2 });
    }

    res.status(200).send({ message: "OTP sent successfully.",status:1,OTP:OTP,driverId:isExisting[0].id });
  } catch (error) {
    console.error('Error sending OTP:', error);
    res.status(500).send({ message: error.message || "Failed to send OTP." });
  }
};


const resetDriverPassword = async(req,res)=>{
  try {
    const {driverId,password} =req.body
    let hashedPassword = Password.hash(password);
    let result = await Driver.updateDriverPassword(driverId,hashedPassword,password)
    if(result){
      res.send({status:1,message:"success"})
    }else{
      res.send({status:0,message:"failed"})

    }
  } catch (error) {
    console.error('Error sending OTP:', error);
    res.status(500).send({ message: error?.message || "Failed to send OTP." });
  }
}

module.exports={
    AddDrivers,
    getAllDrivers,
    getDriverDatabyUserId,
    getDriverDatabyId,
    updateDriver,
    changeStatusOfDriver,
    getAllActiveDrivers,
    getAllVerifiedActiveDrivers,
    getAssignedRoutesByDriver,
    getAcceptedRoutesByDriver,
    acceptAssignedInstallationsByDriver,
    cancelAssignedRouteByDriver,
    getDeliveredRoutesByDriver,
    getFailedRoutesByDriver,
    sendOtpToDriver,
    resetDriverPassword
}