const { empty, removeNull } = require("../Helpers/Common");
const moment = require('moment')
const crypto = require("crypto");
const Campaign = require('../models/campaign')
const Admin = require('../models/admin')
const CustomFieldTemplate = require('../models/customFieldTemplate')
const uniqid = require('uniqid');
let currentDate = Math.round(moment().valueOf() / 1000);


//remember
// const CAMPAIGN STATUS = [
//   { id: 4, value: 'Planning' },
//   { id: 1, value: 'Active ' },
//   { id: 2, value: 'In Active' },
//   { id: 3, value: 'Completed' },
// ]
const createCampaigns=async(req,res)=>{
    try {
        const {userId,values} = req.body;
        if(!empty(values)){
            let campaigndata={}
            campaigndata['name'] = values.name
            campaigndata['campaign_type'] = values.type
            campaigndata['budget'] =values.budget
            if(!empty(values.tags)){
              campaigndata['target_list'] = values.tags
            }
            campaigndata['campaign_status'] = values.status.id
            campaigndata['start_date'] = values.start?moment(values.start).unix():currentDate
            campaigndata['end_date'] = values.end?moment(values.end).unix():currentDate
            campaigndata['description'] = values.description
            campaigndata['added_by']=userId
            campaigndata['added_time']=currentDate
            campaigndata['updated_by']=userId
            campaigndata['updated_time']=currentDate
            campaigndata['status']=1; 

            let addedResult = await Campaign.createCampaigns(campaigndata)
            if(!empty(addedResult)){
                if(userId!==1){
                    let teamId = await Admin.getTeamByUserId(userId)
                    let teamMember={}
                    teamMember['campaign_id']=addedResult;
                    teamMember['team_id']=teamId;
                    teamMember['added_time']=currentDate;
                    teamMember['added_by']=userId;
                    teamMember['status']=1;
                
                    let campaignTeamId = await Campaign.createBatchCampaignTeam(teamMember)

                }
                ////////////////////// notification
                let notificationMsg = `Campaign <strong>".${campaigndata['name']}."</strong> has been added to ".portalName.`;
                let notificationUrl = "campaigns";
        
              
        
                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
                    );
                  }
                }
                res.send({
                  status: 1,
                  message: `Campaign ${campaigndata['name']}." has been successfully added !`,
                });
              } else {
                res.send({ status: 0, message: `Error adding campaign!` });
              }          
        }
        else{
            res.send({
                status:0,message:'Failed to add new campaign'
            })
        }
    } catch (error) {
        console.log(error)
    }
}
const getAllcampaigns=async(req,res)=>{
    try {
      const {page,rowsPerPage,search} = req.body

        let {data,totalCount}= await Campaign.getAllcampaigns(page,rowsPerPage,search)    
        if(!empty(data)){
            res.send({
                status:1,data,totalCount
            })
        }else{
          res.send({
            status:0,totalCount
        })
        }
    } catch (error) {
        console.log(error)
    }
}
const editCamapaign=async(req,res)=>{
    try {
        const {userId,values,campaignId} = req.body
        if(!empty(values)){
            let campaigndata={}
            campaigndata['name'] = values.name
            campaigndata['campaign_type'] = values.type
            campaigndata['budget'] =values.budget
            if(!empty(values.tags)){
              campaigndata['target_list'] = values.tags
            }else{
              campaigndata['target_list'] =null
            }
            campaigndata['campaign_status'] = values.status.id
            campaigndata['start_date'] = values.start?moment(values.start).unix():currentDate
            campaigndata['end_date'] = values.end?moment(values.end).unix():currentDate
            campaigndata['description'] = values.description
            campaigndata['added_by']=userId
            campaigndata['added_time']=currentDate
            campaigndata['updated_by']=userId
            campaigndata['updated_time']=currentDate
            campaigndata['status']=1; 
            let updatedResult = await Campaign.updateCampaign(campaignId,campaigndata)

            if(updatedResult){
                let notificationMsg = `Campaign <strong>".${campaigndata['name']}."</strong> has been updated to ".portalName.`;
                let notificationUrl = "campaigns";
        
              
        
                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
                    );
                  }
                }
                res.send({
                  status: 1,
                  notification: notificationMsg,
                  message: `Campaign ${campaigndata['name']}." has been updated successfully  !`,
                });
              } 
              else {
                res.send({ status: 0, message: `Error updating campaign!` });
              }          
         }
      
    } catch (error) {
        console.log(error)
    }
}
const getCampaignById=async(req,res)=>{
    try {
        const {campaignId} = req.body
        let result = await Campaign.getCampaignById(campaignId)
        if(!empty(result)){
            res.send({
                result,status:1
            })
        }else{
            res.send({
                status:0
            })
        }
    } catch (error) {
        console.log(error)
    }
}
const deleteCampaign = async(req,res)=>{
  try {
    const {status,campaignId,userId}= req.body
    let campaignData={}
    campaignData['status'] = status
    if(!empty(campaignId)){
      let deletedResult = await Campaign.updateCampaign(campaignId,campaignData)
      let data = await Campaign.getCampaignById(campaignId)
      
      let notificationMsg=''
      if(campaignData['status']===2){
        notificationMsg = `The campaign "${data[0]['name']}" has been deleted.`
      }
      else if(campaignData['status']===0){
            notificationMsg = `The campaign "${data[0]['name']}" has been made inactive.`
      }
      else{
        notificationMsg = `The campaign "${data[0]['name']}" has been made active.`
      }
      if(deletedResult){
        // let data = await Campaign.getCampaignById(campaignId)
        /////////notification
        let notification_url="campaigns"
        const incrementResult_User = await Admin.incrementField(
          userId,
          "noti_count",
          1
        );
        let notificationData_user = {
          user_id: userId,
          url: notification_url,
          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: notification_url,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            };
            const addNotificationResult = await Admin.addNotification(
              notificationData
            );
          }
        }
        res.send({
          status: 'success',
          notification: notificationMsg,
          message: `Campaign ${data[0]['name']}." has been updated successfully  !`,
        });
      } 
      }
      else{
        res.send({
          status:0,message:'Failed to updated campaign'
        })
      }

  } catch (error) {
    console.log(error)
  }
}
const addCampaignForm = async (req, res) => {
  try {
    let { userId, values, name,campaignId } = req.body;
    const template = {
      name: name,
      timestamp: moment().unix(),
      updated_on: moment().unix(),
      campaignId:campaignId,
      added_by: req.body.userId,
      status: 5,
    };

    const formFields = values;
    let stageId = uniqid()
    let formFieldId = uniqid()
    template['template_uid'] = formFieldId
    template['stage_uid'] = uniqid()
   
    if (empty(values)) {
      res.status(400).send({ status: 0, message: 'Failed to create new campaign form !' });
      return;
    }
   

    let templateId = await CustomFieldTemplate.addTemplate(template)

    if (templateId) {
      let i = 1;

      for (const row of values) {
        const customFields = {};
        customFields.template_id = templateId;
        customFields.row_id = 'row'+uniqid();
        customFields.column_id = 'column'+uniqid();
        customFields.html_tag = row.type;
        customFields.name = row.type  ;

        if (row.required) {
          customFields.is_required = 1;
        }

        if (row.description) {
          customFields.help_text = row.description;
        }

        customFields.tag_uid = row.type;

        if (!empty(row.label)) {
          customFields.content = row.label.replace(/[\r\n]+/g, '').trim();
        }

        customFields.field_uid = 'field'+uniqid();
        customFields.position_order = i++;

        if (row.placeholder) {
          customFields.placeholder = row.placeholder;
        }

        if (row.date_format) {
          customFields.date_format = row.date_format;
        }

        if (row.pattern) {
          customFields.pattern = row.pattern;
        }

        if (row.href) {
          customFields.a_href = row.href;
        }

        if (row.target) {
          customFields.a_target = row.target;
        }

        if (customFields.tag_uid === 'header') {
          customFields.default_select = 'h1';
          if (row.tag) {
            row.tag.forEach((headerTag) => {
              if (headerTag.selected) {
                customFields.default_select = headerTag.value;
              }
            });
          }
        }

        customFields.timestamp = moment().unix();
        customFields.added_by = userId;
        customFields.status = 1;
       
        if (!empty(row.subtype)) {
          customFields.input_type = row.subtype || 'text';
        }

        const fieldId = await CustomFieldTemplate.addTemplateField(customFields);

        if (row.values) {
          let o = 1;
          for (const fieldOption of row.values) {
           
            const customFieldOptions = {};
            customFieldOptions.field_id = fieldId;
            customFieldOptions.option_name = fieldOption.label;
            customFieldOptions.selected =fieldOption.selected? parseInt(fieldOption.selected):0
            customFieldOptions.position_order = o++;
            customFieldOptions.timestamp = moment().unix();
            customFieldOptions.added_by = userId;
            customFieldOptions.status = 1;

            const fieldOptionId = await CustomFieldTemplate.addTemplateFieldOptions(customFieldOptions);
          }
        }
      }
      let notificationMessage="New Campaign form  "+name+" has been created"
      let notificationUrl="campaign/create-new-form"      
      const 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: notificationUrl,
          timestamp: moment().unix(),
          message: notificationMessage,
          status: 1,
          from_id: userId,
        }
        const addNotificationResult = await Admin.addNotification(addNotification);
      }
      }
      const incrementResult_User = await Admin.incrementField(userId, "noti_count", 1);
   
      let notificationData_user = {
          user_id: userId,
          url: notificationUrl,
          timestamp: moment().unix(),
          message: notificationMessage,
          status: 1,
          from_id:userId,
      };
    
      const addNotificationResult_user = await Admin.addNotification(notificationData_user);
      res.send({
        status:1,msg:notificationMessage
    })
    }
    else{
      res.send({
        status:1,msg:"Failed to add campaign form "})
    }
  } catch (error) {
    console.error(error);
    res.status(500).send({ message: "Server error"+error });
  }
}
const getAllCampaignFormByID=async(req,res)=>{
  try {
    const {id,userId,userType} = req.body
   let result = await Campaign.getAllCampaignFormById(id)
   if(!empty(result)){
    res.send({
      status:1 ,result
    })
   }else{
    res.send({
      status:0
    })
   }
  } catch (error) {
    console.log(error)
  }
}
const getCampaignFormDataById=async(req,res)=>{
  try {
    let {id,userId,userType} = req.body
    if(!empty(id)){
       let data = await Campaign.getCampaignFormDataById(id)
       if(!empty(data)){
        res.status(200).send({
          status:1,data
        })
       }else{
        res.status(500).send({
          status:0
        })
       }
    }
  } catch (error) {
    console.log(error)
  }
}
const deleteCampaignForm=async(req,res)=>{
  try {
    const {data,campaignID} = req.body
    let campaignData={}
    campaignData["status"] = 2
    let result = await CustomFieldTemplate.DeleteCampaignForm(campaignData,data.id,campaignID)
    if(result===true){
      res.status(200).send({
        status:1,message:`Campaign Form ${data.name} has been deleted successfully`
      })
    }else{
      res.status(500).send({
        status:0,message:`Failed to delete ${data.name} `
      })
    }
  } catch (error) {
    console.log(error)
  }
}
const submitCampaignForm=async(req,res)=>{
  try {
    let unique_id = crypto.randomBytes(3).toString("hex");

    const {id,submitForm} = req.body
    let campaignId = await CustomFieldTemplate.getCampaignIdFromCustomTemplate(id)

    if(!empty(submitForm)){
      const field_value_pairs = [];
      let valueData = removeNull(submitForm)
      for (const [key, value] of Object.entries(valueData)) {
        if (value && typeof value === 'object' && "value" in value) {
          field_value_pairs.push({ "field_id": value.field_id, "value": value.value,form_id: id, campaignId: campaignId,unique_id:unique_id, timestamp: currentDate, status: 1,});
        } else if (value && Array.isArray(value) && value.every(item => typeof item === 'object' && "value" in item)) {
          for (const item of value) {
            if(!empty(item.value)){
              field_value_pairs.push({ "field_id": item.field_id, "value": item.value,form_id: id, campaignId: campaignId, timestamp: currentDate,unique_id:unique_id, status: 1,});
            }     
          }
        }
      
      }

      if (!empty(field_value_pairs)) {
        let submissionResponse = await Campaign.updateBatchData(
          "campaign_form_fields",
          field_value_pairs
        );
        if(submissionResponse===true){
          res.status(200).send({
            status:1,message:'Form submitted successfully'
          })
        }else{
          res.status(500).send({
            status:0,message:'Failed to submit the form '
          })
        }
      }
      
    }else{
    res.status(500).send({
        status:0,message:'Failed to submit the form .'
    })
    }
  } catch (error) {
    console.log(error)
  }
}
    
const getFormUserByid=async(req,res)=>{
  try {
    const {id} = req.body 
    const  data = await Campaign.getFormUsersDataByFormId(id)
    if(!empty(data)){
      res.status(200).send({
        status:1,data
      })
    }else{
      res.status(500).send({
        status:0
      })
    }
  } catch (error) {
    console.log(error)
  }
}
module.exports={
    createCampaigns,
    getAllcampaigns,
    editCamapaign,
    getCampaignById,
    deleteCampaign,
    addCampaignForm,
    getAllCampaignFormByID,
    getCampaignFormDataById,
    deleteCampaignForm,
    submitCampaignForm,
    getFormUserByid,
}