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/questionairetemplate')
const Questionnaire = require('../models/questionairetemplate')
const moment = require('moment');
const uniqid = require('uniqid');
const getAllCustomFields = async (req, res) => {
  try {
    console.log("HIIIIIIIIIIIIIIII");
    let result = await CustomFieldTemplate.getAllCustomFields()
    res.send({
      result,
      status: 1,
      message: ' Successfully fetched Questionnaire Templates '
    })
  } 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 <strong>".${data['name']}."</strong> 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 {
    
      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()
      
      console.log("###########qw",values);
      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 formFields.rows) {
        //   for (const column of formFields.columns) {
        //     if (column.fields.includes(row.columns)) {
        //       for (const fieldId of column.fields) {
        //         const customFields = {};
        //         customFields.template_id = templateId;
        //         customFields.row_id = row.id;
        //         customFields.column_id = column.id;
        //         customFields.html_tag = formFields.fields[fieldId].tag;
        //         customFields.name = formFields.fields[fieldId].config.label.replace(/[\r\n]+/g, '').trim();
  
        //         if (formFields.fields[fieldId].attrs.required) {
        //           customFields.is_required = formFields.fields[fieldId].attrs.required;
        //         }
  
        //         if (formFields.fields[fieldId].attrs.description) {
        //           customFields.help_text = formFields.fields[fieldId].attrs.description;
        //         }
  
        //         customFields.tag_uid = formFields.fields[fieldId].meta.id;
  
        //         if (formFields.fields[fieldId].content) {
        //           customFields.content = formFields.fields[fieldId].content.replace(/[\r\n]+/g, '').trim();
        //         }
  
        //         customFields.field_uid = fieldId;
        //         customFields.position_order = i++;
  
        //         if (formFields.fields[fieldId].attrs.placeholder) {
        //           customFields.placeholder = formFields.fields[fieldId].attrs.placeholder;
        //         }
  
        //         if (formFields.fields[fieldId].attrs.date_format) {
        //           customFields.date_format = formFields.fields[fieldId].attrs.date_format;
        //         }
  
        //         if (formFields.fields[fieldId].attrs.pattern) {
        //           customFields.pattern = formFields.fields[fieldId].attrs.pattern;
        //         }
  
        //         if (formFields.fields[fieldId].attrs.href) {
        //           customFields.a_href = formFields.fields[fieldId].attrs.href;
        //         }
  
        //         if (formFields.fields[fieldId].attrs.target) {
        //           customFields.a_target = formFields.fields[fieldId].attrs.target;
        //         }
  
        //         if (customFields.tag_uid === 'header') {
        //           customFields.default_select = 'h1';
        //           if (formFields.fields[fieldId].attrs.tag) {
        //             formFields.fields[fieldId].attrs.tag.forEach((headerTag) => {
        //               if (headerTag.selected) {
        //                 customFields.default_select = headerTag.value;
        //               }
        //             });
        //           }
        //         }
  
        //         customFields.timestamp = Math.floor(Date.now() / 1000);
        //         customFields.added_by = userId;
        //         customFields.status = 1;
  
        //         if (formFields.fields[fieldId].tag === 'input') {
        //           customFields.input_type = formFields.fields[fieldId].attrs.type || 'text';
        //         }
  
        //         const fieldId =await CustomFieldTemplate.addTemplateField(customFields);
  
        //         if (formFields.fields[fieldId].options) {
        //           let o = 1;
        //           for (const fieldOption of formFields.fields[fieldId].options) {
        //             const customFieldOptions = {};
        //             customFieldOptions.field_id = fieldId;
        //             customFieldOptions.option_name = fieldOption.label;
        //             customFieldOptions.selected = parseInt(fieldOption.selected);
  
        //             if (formFields.fields[fieldId].content && customFieldOptions.option_name === formFields.fields[fieldId].content) {
        //               customFieldOptions.selected = 1;
        //             }
  
        //             customFieldOptions.position_order = o++;
        //             customFieldOptions.timestamp = Math.floor(Date.now() / 1000);
        //             customFieldOptions.added_by = userId;
        //             customFieldOptions.status = 1;
  
        //             const fieldOptionId = addTemplateFieldOptions(customFieldOptions);
        //           }
        //         }
        //       }
        //     }
        //   }
        // }
  
        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;
  console.log("############,",row.label);
          if (!empty(row.label)) {
            customFields.content = row.label;
          }
  
          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) {
              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 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()
      
      console.log("###########qw",values);
      if (empty(values)) {
        res.status(400).send({ status: 0, message: 'Failed to create custom field template!' });
        return;
      }
     
  
      let templateId = await CustomFieldTemplate.updateCustomFieldTemplate(id,template)
  
      if (templateId) {
        const names = values.map(item => `"${item.name}"`);
        const namesCSV = names.join(', ');
        let deleteExisting=await CustomFieldTemplate.removeCustomField(id,namesCSV)
        let i = 1;
        
        for (const row of values) {
          let existing=await CustomFieldTemplate.checkExisting(id,row.name)
          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;
  console.log("############,",row.label);
          if (!empty(row.label)) {
            customFields.content = row.label;
          }
  
          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';
          }
          let fieldId
          if(existing){
            console.log("##############existing", existing);
             fieldId = await CustomFieldTemplate.updateTemplateField(existing.id,customFields)
          }
          else{
         
             fieldId = await CustomFieldTemplate.addTemplateField(customFields);
             console.log("RRRRRRRRRRRRRNNentered", fieldId);
          }
          console.log("RRRRRRRRRRRRRNN", fieldId);
  
          if (row.values) {
            let o = 1;
            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)
          }
            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="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 viewQuestionTemplate=async(req,res)=>{
    try {
      let {id} = req.body
      let data = await Questionnaire.get_qnsTemplateData_by_id(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;
                const className = type !== "radio-group" && type !== "checkbox-group" ? "form-control" : "";

              {console.log("##########field.options",field.options)}
            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,
                });
            }
        }
    
        // 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,data:[],formattedData:[]
         })
       }
    } catch (error) {
      console.log(error)
    }
  }
  module.exports = {
    getAllCustomFields,
    deletCustomFieldTemplate,
    addTemplate,
    viewQuestionTemplate,
    UpdateTemplate
  }