const  Projects  = require("../models/Projects");

const StaffSchedular=require("../models/staffSchedular")
const moment = require("moment");
const Admin = require("../models/admin");
const { rfqEmail } = require("../constants/emailTemplates");
const sgMail = require('@sendgrid/mail')
const { SENDGRID_API_KEY, BASE_URL, portalName, SEND_EMAIL } = require("../constants/constant")
const nodemailer = require('nodemailer');


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


const newSchedule = async (req, reply) => {
    let { userId, values } = req.body
    let currentDate = moment().unix();
    let data = {
      project_id: values.project.id,
      task_id: values.task.ID,
      subtask_id:values.subtask.ID,
      team: values.employee.id,
      shift_start: values.shift_start,
      shift_end: values.shift_end,
      timestamp: moment().unix(),
      added_by: userId,
      
    };
    insertedstatus = await StaffSchedular.addschedule(data)
    if (insertedstatus) {
      let welcome = `Hello ${values.employee.first_name},`
      let subject = 'A new Job has been assigned to you';
      let email_content = `New  job: ${values.project.name} task: ${values.task.name} has been assigned to you ` ;
      let message = rfqEmail()
      message = message.replace('[emailContent]', email_content)
      message = message.replace('[CONTENT]', welcome)
     
      message = message.replace('[LOGIN_URL]', `${BASE_URL}`)
      const msg = {
        to: values.employee.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)
      //   })

      const mailOptions = {
        to:  values.employee.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);
       
      }
            
    
      let notificationMsg = `New Job has been schedule for  ${values.employee.first_name}`;
  
  
      let notificationUrl = "staff-payout";
      const incrementResult_User = await Admin.incrementField(
        userId,
        "noti_count",
        1
      );
  
      let notificationData_user = {
        user_id: userId,
        url: notificationUrl,
        timestamp: currentDate,
        message: notificationMsg,
        status: 1,
        from_id: userId,
      };
      const addNotificationResult_user = await Admin.addNotification(
        notificationData_user
      );
      let adminIds = await Admin.getAllAdminIds();
      let notificationData = {};
  
      for (const adminId of adminIds) {
        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
          );
        }
      }

      welcome = "Hello Admin,"
      email_content=`New  job: ${values.project.name} task: ${values.task.name} has been assigned to ${values.employee.first_name}`
      subject=" A new Job has been assigned "
      message = rfqEmail()
      message = message.replace('[emailContent]', email_content)
      message = message.replace('[CONTENT]', welcome)
     
      message = message.replace('[LOGIN_URL]', `${BASE_URL}`)
      let adminEmails = await Admin.getAllAdminEmails();
      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: subject,
          text: subject,
          html: message,
        }
        // sgMail
        //   .send(msg)
        //   .then(() => {
        //     console.log('Email sent')
        //   })
        //   .catch((error) => {
        //     console.error(error)
        //   })

        const mailOptions = {
          to:  row , 
          from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
          subject: subject,
          text: subject,
          html: message,
        }
        try {
          if(SEND_EMAIL){
          await transporter.sendMail(mailOptions);
          console.log('Email sent');
          }
        } catch (error) {
          console.error('##########Err', error);
         
        }
      }
      reply.send({ status: 1, message: notificationMsg });
    }
    else {
      reply.send({ status: 0, message: " Failed to assign new job " });
  
    }
  }

const getStaffScheduls=async(req,reply)=>{
    console.log("$$$$$$$$$$$",req.body);
    let {userId,userType,values,userName,hasViewPermission}=req.body
    console.log("$$$$$$$$$$$",userType);
    
  let data=await StaffSchedular.getschedule(userType,userId,hasViewPermission)
  reply.send({ status: 1, data: data });

}

  module.exports={newSchedule,getStaffScheduls}