const { json } = require("sequelize");
const sequelize = require("../config/dbconnection");
const { empty } = require('../Helpers/Common');
const Admin = require('../models/admin');
const CustomFields = require('../models/customFields')
const CustomFieldTemplate = require('../models/customFieldTemplate')
const moment = require('moment');
const uniqid = require('uniqid');
const getAllCustomFields = async (req, res) => {
  try {
    let all=true
    let result = await CustomFieldTemplate.getAllCustomFields(all)
    res.send({
      result,
      status: 1,
      message: ' Successfully fetched customfields'
    })
  } catch (error) {
    console.log(error)
  }
}
const deletCustomFieldTemplate = async (req, res) => {
  try {
    let { templateId, userId, status, userType } = req.body;
    let currentDate = Math.round(moment().valueOf() / 1000);
    let template = {}
    template['status'] = status
    if (!empty(templateId)) {
      let data = await CustomFieldTemplate.getTemplateByid(templateId)
      let deleted = await CustomFieldTemplate.updateCustomFieldTemplate(templateId, template)

      if (template['status'] == 2) {

        if (deleted) {

          let notificationMsg = `The custom field template <strong>".${data['name']}."</strong> has been deleted.`;
          let notificationUrl = "custom-fields";
          if (userType !== 1) {
            Admin.incrementField(userId, 'noti_count', 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }
          let adminId = await Admin.getAllAdminIds()
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, 'noti_count', 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }
          res.send({
            status: 2, message: `The custom field template ${data['name']} has been deleted.`
          })
        }
      } else if (template['status'] == 1) {

        if (deleted) {

          let notificationMsg = `The custom field template <strong>".${data['name']}."</strong> has been made active.`;
          let notificationUrl = "custom-fields";
          if (userType !== 1) {
            Admin.incrementField(userId, 'noti_count', 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }
          let adminId = await Admin.getAllAdminIds()
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, 'noti_count', 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }
          res.send({
            status: 1, message: `The custom field template ${data['name']} has been made active.`
          })
        }
      } else if (template['status'] == 0) {

        if (deleted) {

          let notificationMsg = `The custom field template <strong>".${data['name']}."</strong> has been made inactive.`;
          let notificationUrl = "custom-fields";
          if (userType !== 1) {
            Admin.incrementField(userId, 'noti_count', 1);
            Admin.addNotification({
              user_id: userId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }
          let adminId = await Admin.getAllAdminIds()
          for (let eachAdminId of adminId) {
            Admin.incrementField(eachAdminId, 'noti_count', 1);
            Admin.addNotification({
              user_id: eachAdminId,
              url: notificationUrl,
              timestamp: currentDate,
              message: notificationMsg,
              status: 1,
              from_id: userId,
            });
          }
          res.send({
            status: 0, message: `The Template ${data['name']} has been made inactive!`
          })
        }
      }
    }
  } catch (error) {
    console.log(error, 'error in delete custom field')
  }
}



const addTemplate = async (req, res) => {
  try {
    console.log(req.body, '*8888888888888888888888888888888888888')
    let { userId, values, name } = req.body;
    const template = {
      name: req.body.name,
      timestamp: moment().unix(),
      updated_on: moment().unix(),
      added_by: req.body.userId,
      status: 1,
    };

    const formFields = req.body.values;
    let stageId = uniqid()
    let formFieldId = uniqid()
    template['template_uid'] = formFieldId
    template['stage_uid'] = uniqid()
    // template.template_uid = formFields.id;

    // if (formFields.stages && formFields.stages.length > 0) {
    //   template.stage_uid = formFields.stages[0].id;
    // } else {
    //   res.status(400).send({ status: 0, message: 'Failed to create custom field template!' });
    //   return;
    // }
    if (empty(values)) {
      res.status(400).send({ status: 0, message: 'Failed to create custom field template!' });
      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.row_id = row.name;
        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;
        console.log("##############", row.subtype);
        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) {
            console.log("RRRRRRRRRRRRRNN", fieldId);
            const customFieldOptions = {};
            customFieldOptions.field_id = fieldId;
            customFieldOptions.option_name = fieldOption.label;
            customFieldOptions.selected = fieldOption.selected ? parseInt(fieldOption.selected) : 0

            // if (formFields.fields[fieldId].content && customFieldOptions.option_name === formFields.fields[fieldId].content) {
            //   customFieldOptions.selected = 1;
            // }

            customFieldOptions.position_order = o++;
            customFieldOptions.timestamp = moment().unix();
            customFieldOptions.added_by = userId;
            customFieldOptions.status = 1;

            const fieldOptionId = await CustomFieldTemplate.addTemplateFieldOptions(customFieldOptions);
          }
        }
      }
      let notificationMessage = "New custom field template " + req.body.name + " has been created"
      let notificationUrl = "dashboard/custom-field-template"
      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 new template"
      })
    }
  } catch (error) {
    console.error(error);
    res.status(500).send({ message: "Server error" + error });
  }
}
const viewCustomTemplate = async (req, res) => {
  try {
    let { id } = req.body
    let data = await CustomFieldTemplate.getTemplateDataById(id)
    
    if (!empty(data)) {
      res.send({
        status: 1, data
      })
    } else {
      res.send({
        status: 0
      })
    }

  } catch (error) {
    console.log(error)
  }
}
const getTemplateById = async (req, res) => {
  try {
    let { id } = req.body
    let data = await CustomFieldTemplate.getTemplateDataById(id)

   let formattedData = [];

    
    data.forEach(item => {
     
      const templateName = item.template_name;
      const fields = [];
  
   
      for (const key in item.fields) {
          if (item.fields.hasOwnProperty(key)) {
              const field = item.fields[key];
              const { content: label, tag: type, required,field_id,name} = field;
              const className = type !== "radio-group" && type !== "checkbox-group" ? "form-control" : "";

            {console.log("##########field.options",field)}
          let mappedArray = field.options?.map(item => {
              return {
                label: item.label,
                value:item.value,
                selected: item.selected,
               
                
              };
            });
            
            field.options
              fields.push({
                  label,
                  type,
                  required: required === 0 ? false : true,
                  className: className,
                  values:mappedArray,
                  field_id,
                  name
              });
          }
      }
  
      // Push template name and formatted fields into the formattedData array
      formattedData.push({
          template: templateName,
          fields
      });
  });
  

  

    if (!empty(data)) {
      res.send({
        status: 1, data,formattedData
      })
    } else {
      res.send({
        status: 0
      })
    }

  }
  catch (error) {
    console.log(error)
  }
}

// const updateTemplate = async (req, res) => {
//   try {
//     console.log(req.body, '*8888888888888888888888888888888888888')
//     let { userId, values, name,id } = req.body;
//     const template = {
//       name: req.body.name,
//       timestamp: moment().unix(),
//       updated_on: moment().unix(),
//       added_by: req.body.userId,
//       status: 1,
//     };

//     const formFields = req.body.values;
//     let stageId = uniqid()
//     let formFieldId = uniqid()
//     template['template_uid'] = formFieldId
//     template['stage_uid'] = uniqid()
//     // template.template_uid = formFields.id;

//     // if (formFields.stages && formFields.stages.length > 0) {
//     //   template.stage_uid = formFields.stages[0].id;
//     // } else {
//     //   res.status(400).send({ status: 0, message: 'Failed to create custom field template!' });
//     //   return;
//     // }
//     if (empty(values)) {
//       res.status(400).send({ status: 0, message: 'Failed to update custom field template!' });
//       return;
//     }


//     let templateId = await CustomFieldTemplate.updateCustomFieldTemplate(id, template)

//     if (templateId) {
//     //  let deleteExisting=await CustomFieldTemplate.deleteCustomField(id)
//     let deleteExisting=await CustomFieldTemplate.updateCustomField(id)
//       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;
//         console.log("##############", row.subtype);
//         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) {
//             console.log("RRRRRRRRRRRRRNN", fieldId);
//             const customFieldOptions = {};
//             customFieldOptions.field_id = fieldId;
//             customFieldOptions.option_name = fieldOption.label;
//             customFieldOptions.selected = fieldOption.selected ? parseInt(fieldOption.selected) : 0

//             // if (formFields.fields[fieldId].content && customFieldOptions.option_name === formFields.fields[fieldId].content) {
//             //   customFieldOptions.selected = 1;
//             // }

//             customFieldOptions.position_order = o++;
//             customFieldOptions.timestamp = moment().unix();
//             customFieldOptions.added_by = userId;
//             customFieldOptions.status = 1;

//             const fieldOptionId = await CustomFieldTemplate.addTemplateFieldOptions(customFieldOptions);
//           }
//         }
//       }
//       let notificationMessage = "Custom field template " + req.body.name + " has been updated"
//       let notificationUrl = "dashboard/custom-field-template"
//       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 update  template"
//       })
//     }
//   } catch (error) {
//     console.error(error);
//     res.status(500).send({ message: "Server error" + error });
//   }
// }
const updateTemplate = async (req, res) => {
  try {
   
    let { userId, values, name,id } = req.body;
    const template = {
      name: req.body.name,
      timestamp: moment().unix(),
      updated_on: moment().unix(),
      added_by: req.body.userId,
      status: 1,
    };

    const formFields = req.body.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 custom field template!' });
      return;
    }

    let templateId = await CustomFieldTemplate.updateCustomFieldTemplate(id,template)
    // let templateId = await CustomFieldTemplate.addTemplate(template)

    if (templateId) {
      let i = 1;
      // let deleteExisting=await CustomFieldTemplate.deleteCustomField(id)
      const names = values.map(item => `"${item.name}"`);
      const namesCSV = names.join(', ');

      console.log("################Delete Existing",namesCSV);
      let deleteExisting=await CustomFieldTemplate.removeCustomField(id,namesCSV)
      // let deleteExisting=await CustomFieldTemplate.updateCustomField(id)
      console.log("################Delete Existing",deleteExisting);
      for (const row of values) {
        let existing=await CustomFieldTemplate.checkExisting(id,row.name)
        const customFields = {};
        customFields.template_id = templateId;
        customFields.row_id = row.name||row.type;
        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;
        console.log("##############", row.subtype);
        if (!empty(row.subtype)) {
          customFields.input_type = row.subtype || 'text';
        }
        console.log("##############", existing);
        let fieldId
        if(existing){
          console.log("##############existing", existing);
           fieldId = await CustomFieldTemplate.updateTemplateField(existing.id,customFields)
        }
        else{
           fieldId = await CustomFieldTemplate.addTemplateField(customFields);
        }
       
        if (row.values) {
          let o = 1;
          console.log("RRRRRRRRRRRRRNN", fieldId);
          let names = row.values.map(item =>item.value);
          let integerValues = names.filter(value => Number.isInteger(value));
          let namesCSV = integerValues.join(', ');
          console.log("RRRRRRRRRRRRRNN", namesCSV);
          let fetchAllOptions=await CustomFieldTemplate.fetchOptions(fieldId)
          if(fetchAllOptions){
            let deleteExisting=await CustomFieldTemplate.removeCustomFieldOptions(fieldId,namesCSV)
          }
         
          console.log("fetchAllOptions", fetchAllOptions);
          for (const fieldOption of row.values) {
            console.log("RRRRRRRRRRRRRNN", fieldId);
            let existing=await CustomFieldTemplate.checkExistingOptions(Number.isInteger(fieldOption.value),fieldId)
            const customFieldOptions = {};
            customFieldOptions.field_id = fieldId;
            customFieldOptions.option_name = fieldOption.label;
            customFieldOptions.selected = fieldOption.selected ? parseInt(fieldOption.selected) : 0

            // if (formFields.fields[fieldId].content && customFieldOptions.option_name === formFields.fields[fieldId].content) {
            //   customFieldOptions.selected = 1;
            // }

            customFieldOptions.position_order = o++;
            customFieldOptions.timestamp = moment().unix();
            customFieldOptions.added_by = userId;
            customFieldOptions.status = 1;
            if(existing){
              const fieldOptionId = await CustomFieldTemplate.updateTemplateFieldOptions(customFieldOptions,fieldOption.value)
            }
            else{
              const fieldOptionId = await CustomFieldTemplate.addTemplateFieldOptions(customFieldOptions);
            }
           
          }
        }
      }
      let notificationMessage = "New custom field template " + req.body.name + " has been Updated"
      let notificationUrl = "dashboard/custom-field-template"
      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 new template"
      })
    }
  } catch (error) {
    console.error(error);
    res.status(500).send({ message: "Server error" + error });
  }
}
const DuplicateTemplate = async (req, res) => {
  try {
    console.log(req.body, '*8888888888888888888888888888888888888')
    let { userId, values, id } = req.body;

    let data = await CustomFieldTemplate.getTemplateDataById(id)
    let formattedData = [];

    
    data.forEach(item => {
     
      const templateName = item.template_name;
      const fields = [];
  
   
      for (const key in item.fields) {
          if (item.fields.hasOwnProperty(key)) {
              const field = item.fields[key];
              const { content: label, tag: type, required,field_id,name} = field;
              const className = type !== "radio-group" && type !== "checkbox-group" ? "form-control" : "";

            {console.log("##########field.options",field)}
          let mappedArray = field.options?.map(item => {
              return {
                label: item.label,
                value:item.value,
                selected: item.selected,
               
                
              };
            });
            
            field.options
              fields.push({
                  label,
                  type,
                  required: required === 0 ? false : true,
                  className: className,
                  values:mappedArray,
                  field_id,
                  name
              });
          }
      }
  
      // Push template name and formatted fields into the formattedData array
      formattedData.push({
          template: templateName,
          fields
      });
  });
   
    let time=moment().unix()
    const template = {
      name:formattedData[0].template+time,
      timestamp: moment().unix(),
      updated_on: moment().unix(),
      added_by: req.body.userId,
      status: 1,
    };

    const formFields = formattedData[0].fields;
    let stageId = uniqid()
    let formFieldId = uniqid()
    template['template_uid'] = formFieldId
    template['stage_uid'] = uniqid()
    // template.template_uid = formFields.id;

    // if (formFields.stages && formFields.stages.length > 0) {
    //   template.stage_uid = formFields.stages[0].id;
    // } else {
    //   res.status(400).send({ status: 0, message: 'Failed to create custom field template!' });
    //   return;
    // }
    if (empty(formFields)) {
      res.status(400).send({ status: 0, message: 'Failed to create custom field template!' });
      return;
    }


    let templateId = await CustomFieldTemplate.addTemplate(template)

    if (templateId) {
      let i = 1;
    
      for (const row of formFields) {

        const customFields = {};
        customFields.template_id = templateId;
        // customFields.row_id = 'row' + uniqid();
        customFields.row_id = row.name;
        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;
        console.log("##############", row.subtype);
        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) {
            console.log("RRRRRRRRRRRRRNN", fieldId);
            const customFieldOptions = {};
            customFieldOptions.field_id = fieldId;
            customFieldOptions.option_name = fieldOption.label;
            customFieldOptions.selected = fieldOption.selected ? parseInt(fieldOption.selected) : 0

            // if (formFields.fields[fieldId].content && customFieldOptions.option_name === formFields.fields[fieldId].content) {
            //   customFieldOptions.selected = 1;
            // }

            customFieldOptions.position_order = o++;
            customFieldOptions.timestamp = moment().unix();
            customFieldOptions.added_by = userId;
            customFieldOptions.status = 1;

            const fieldOptionId = await CustomFieldTemplate.addTemplateFieldOptions(customFieldOptions);
          }
        }
      }
      let notificationMessage = "New custom field template " + formattedData[0].template + " has been duplicated"
      let notificationUrl = "dashboard/custom-field-template"
      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 new template"
      })
    }
  } catch (error) {
    console.error(error);
    res.status(500).send({ message: "Server error" + error });
  }
}
module.exports = {
  getAllCustomFields,
  deletCustomFieldTemplate,
  viewCustomTemplate,
  addTemplate,
  getTemplateById,
  updateTemplate,DuplicateTemplate
}