const { empty } = require("../Helpers/Common");
const sequelize = require("../config/dbconnection");
const Sequelize = require('sequelize')
const moment = require("moment")
const uniqid = require('uniqid')

// Design Form Template - Main template table
const DesignFormTemplate = sequelize.define('design_form_templates', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    name: { type: Sequelize.STRING, allowNull: false },
    // template_uid: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    // stage_uid: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    template_uid: { type: Sequelize.STRING(50), allowNull: false },
    stage_uid: { type: Sequelize.STRING(50), allowNull: false },
    added_by: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    updated_on: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 6 }, // 6 = Active, 7 = Inactive
    module: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null } // 1 = Design Order, 2 = Sales Order, etc.
}, { timestamps: false })

// Design Form Fields - Fields within templates
const DesignFormField = sequelize.define('design_form_fields', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    template_id: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    name: { type: Sequelize.STRING, allowNull: false, defaultValue: "input" },
    html_tag: { type: Sequelize.STRING, allowNull: false },
    input_type: { type: Sequelize.INTEGER, allowNull: true, defaultValue: null },
    is_required: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
    placeholder: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    help_text: { type: Sequelize.STRING, allowNull: true },
    date_format: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    pattern: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    content: { type: Sequelize.STRING, allowNull: true },
    default_select: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    a_href: { type: Sequelize.STRING, allowNull: true },
    a_target: { type: Sequelize.TINYINT, allowNull: true, defaultValue: 0 },
    row_id: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    column_id: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    field_uid: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    tag_uid: { type: Sequelize.STRING, allowNull: true, defaultValue: null },
    position_order: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
    added_by: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
}, { timestamps: false })

// Design Form Field Options - Options for fields (dropdown, radio, checkbox options)
const DesignFormFieldOption = sequelize.define('design_form_field_options', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    field_id: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    option_name: { type: Sequelize.STRING, allowNull: false },
    selected: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
    position_order: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 0 },
    added_by: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    timestamp: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
}, { timestamps: false })

// Design Form Submissions - Store form field values for design orders
const DesignFormSubmission = sequelize.define('design_form_submissions', {
    id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
    design_order_id: { type: Sequelize.INTEGER, allowNull: false },
    template_id: { type: Sequelize.INTEGER, allowNull: false },
    field_id: { type: Sequelize.INTEGER, allowNull: false },
    value: { type: Sequelize.TEXT, allowNull: true },
    timestamp: { type: Sequelize.INTEGER, allowNull: false, defaultValue: false },
    status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1 },
}, { timestamps: false, tableName: 'design_form_submissions' })

// Get all design form templates
const getAllDesignFormTemplates = async (all = false) => {
    try {
        let whereCondition = ""
        if (all) {
            whereCondition = " or dft.status=7"
        }
        let result = await sequelize.query(`
            SELECT 
                dft.*,
                CONCAT(u.first_name, ' ', u.last_name) AS authorized_by,
                dft.updated_on AS lastupdatedtime
            FROM 
                design_form_templates dft
            LEFT JOIN 
                users u ON dft.added_by = u.id
            WHERE 
                dft.status=6 ${whereCondition}
            ORDER BY 
                dft.id DESC;
        `);
        if (!empty(result)) {
            if (result[0].length > 0) {
                let data = result[0];
                return data;
            } else {
                return false;
            }
        } else {
            return false
        }
    } catch (error) {
        console.log(error, "error in getting all design form templates");
        return false;
    }
};

// Get design form templates by module
const getDesignFormTemplatesByModule = async (module) => {
    try {
        let result = await sequelize.query(`
            SELECT 
                dft.*,
                CONCAT(u.first_name, ' ', u.last_name) AS authorized_by,
                dft.updated_on AS lastupdatedtime
            FROM 
                design_form_templates dft
            LEFT JOIN 
                users u ON dft.added_by = u.id
            WHERE 
                dft.status=6 AND dft.module = ${module}
            ORDER BY 
                dft.id DESC;
        `);
        if (!empty(result)) {
            if (result[0].length > 0) {
                let data = result[0];
                return data;
            } else {
                return [];
            }
        } else {
            return []
        }
    } catch (error) {
        console.log(error, "error in getting design form templates by module");
        return [];
    }
};

// Get all templates with their form data by module (batch API - single call)
const getAllTemplatesWithDataByModule = async (module) => {
    try {
        // First get all templates
        const templates = await getDesignFormTemplatesByModule(module);
        
        if (!templates || templates.length === 0) {
            return [];
        }
        
        // Get form data for all templates at once
        const templatesWithData = await Promise.all(
            templates.map(async (template) => {
                const templateData = await getTemplateDataById(template.id);
                // getTemplateDataById returns array with one object: [{ template: "...", fields: {...} }]
                if (templateData && templateData.length > 0) {
                    return {
                        ...template,
                        formData: templateData[0] // Extract the first object which contains template name and fields
                    };
                }
                return {
                    ...template,
                    formData: null
                };
            })
        );
        
        return templatesWithData;
    } catch (error) {
        console.log(error, "error in getting all templates with data by module");
        return [];
    }
};

// Add new template
const addTemplate = async (data) => {
    try {
        let results = await DesignFormTemplate.create(data)
        if (results) {
            return results.id;
        }
        else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in adding design form template')
        return false;
    }
}

// Update template
const updateTemplate = async (id, data) => {
    try {
        let result = await DesignFormTemplate.update(data, {
            where: {
                id: id
            }
        })
        if (result) {
            return id
        } else {
            return false
        }
    } catch (error) {
        console.log(error, 'error in updating design form template')
        return false;
    }
}

// Add template field
const addTemplateField = async (data) => {
    try {
        let results = await DesignFormField.create(data)
        if (results) {
            return results.id;
        }
        else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in adding design form field')
        return false;
    }
}

// Update template field
const updateTemplateField = async (id, data) => {
    try {
        let result = await DesignFormField.update(data, {
            where: {
                id: id
            }
        })
        if (result) {
            return id
        } else {
            return false
        }
    } catch (error) {
        console.log(error, 'error in updating design form field')
        return false;
    }
}

// Add field option
const addTemplateFieldOptions = async (data) => {
    try {
        let results = await DesignFormFieldOption.create(data)
        if (results) {
            return results.id;
        }
        else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in adding design form field option')
        return false;
    }
}

// Get template by ID with all fields and options
const getTemplateDataById = async (id) => {
    try {
        let result = await sequelize.query(`
            SELECT 
                dft.id AS template_id,
                dft.name AS template_name,
                dft.template_uid,
                dft.stage_uid,
                dft.added_by,
                dft.timestamp,
                dft.updated_on,
                dft.status AS template_status
            FROM 
                design_form_templates dft
            WHERE 
                dft.id = ${id} AND dft.status = 6
        `);

        if (empty(result) || empty(result[0]) || result[0].length === 0) {
            return false;
        }

        let templateData = result[0][0];
        let fieldsResult = await sequelize.query(`
            SELECT 
                dff.*
            FROM 
                design_form_fields dff
            WHERE 
                dff.template_id = ${id} AND dff.status = 1
            ORDER BY 
                dff.position_order ASC
        `);

        let fields = {};
        if (!empty(fieldsResult) && fieldsResult[0].length > 0) {
            for (let field of fieldsResult[0]) {
                let optionsResult = await sequelize.query(`
                    SELECT 
                        dffo.*
                    FROM 
                        design_form_field_options dffo
                    WHERE 
                        dffo.field_id = ${field.id} AND dffo.status = 1
                    ORDER BY 
                        dffo.position_order ASC
                `);

                let options = [];
                if (!empty(optionsResult) && optionsResult[0].length > 0) {
                    options = optionsResult[0].map(opt => ({
                        label: opt.option_name,
                        value: opt.id,
                        selected: opt.selected
                    }));
                }

                // Use field_uid as name to ensure unique identification (form builder uses field_uid as key)
                // This prevents issues when multiple fields have the same row_id
                fields[field.field_uid] = {
                    id: field.id,
                    field_id: field.id,
                    name: field.field_uid,  // Use field_uid as name for unique identification
                    tag: field.html_tag,
                    type: field.html_tag,
                    content: field.content,
                    required: field.is_required,
                    placeholder: field.placeholder,
                    help_text: field.help_text,
                    date_format: field.date_format,
                    pattern: field.pattern,
                    default_select: field.default_select,
                    a_href: field.a_href,
                    a_target: field.a_target,
                    row_id: field.row_id,
                    column_id: field.column_id,
                    field_uid: field.field_uid,
                    tag_uid: field.tag_uid,
                    position_order: field.position_order,
                    options: options
                };
            }
        }

        return [{
            template: templateData.template_name,
            template_id: templateData.template_id,
            fields: fields
        }];
    } catch (error) {
        console.log(error, "error in getting design form template by id");
        return false;
    }
}

// Delete template (soft delete by setting status)
const deleteTemplate = async (id) => {
    try {
        let result = await DesignFormTemplate.update(
            { status: 0 },
            {
                where: {
                    id: id
                }
            }
        )
        return result;
    } catch (error) {
        console.log(error, 'error in deleting design form template')
        return false;
    }
}

// Deactivate/Activate template
const deactivateTemplate = async (templateId, status) => {
    try {
        let result = await DesignFormTemplate.update(
            { status: status, updated_on: moment().unix() },
            {
                where: {
                    id: templateId
                }
            }
        )
        return result;
    } catch (error) {
        console.log(error, 'error in deactivating design form template')
        return false;
    }
}

// Fetch field options
const fetchOptions = async (fieldId) => {
    try {
        let result = await sequelize.query(`
            SELECT 
                dffo.*
            FROM 
                design_form_field_options dffo
            WHERE 
                dffo.field_id = ${fieldId} AND dffo.status = 1
            ORDER BY 
                dffo.position_order ASC
        `);
        if (!empty(result) && result[0].length > 0) {
            return result[0];
        } else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in fetching design form field options')
        return false;
    }
}

// Remove field options (for updating)
const removeFieldOptions = async (fieldId, excludeIds) => {
    try {
        let whereCondition = ""
        if (excludeIds && excludeIds !== "") {
            whereCondition = ` AND id NOT IN (${excludeIds})`
        }
        let query = await sequelize.query(`UPDATE design_form_field_options SET status = 0 WHERE field_id = ${fieldId} ${whereCondition}`)
        if (query) {
            return true;
        } else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in removing design form field options')
        return false;
    }
}

// Get template by ID (simple)
const getTemplateByid = async (id) => {
    try {
        let result = await DesignFormTemplate.findOne({
            where: { id: id }
        })
        if (result) {
            return result.dataValues;
        } else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in getting design form template by id')
        return false;
    }
}

// Delete template by ID (soft delete)
const deteleCustomTemplateById = async (templateId) => {
    try {
        let result = await DesignFormTemplate.update(
            { status: 0 },
            {
                where: {
                    id: templateId
                }
            }
        )
        if (result) {
            return true;
        } else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in deleting design form template')
        return false;
    }
}

// Remove custom field - check by field_uid (unique identifier)
const removeCustomField = async (id, fieldUids) => {
    try {
        // Delete fields that don't match by field_uid (form builder uses field_uid as name)
        // This ensures unique identification even when multiple fields share the same row_id
        let query = await sequelize.query(`DELETE FROM design_form_fields WHERE field_uid NOT IN (${fieldUids}) AND template_id = ${id}`)
        if (query) {
            return true;
        } else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in removing design form field')
        return false;
    }
}

// Check if field exists - check by field_uid (unique identifier)
const checkExisting = async (id, fieldUid) => {
    try {
        // Check by field_uid since form builder uses field_uid as name for unique identification
        let query = await sequelize.query(`SELECT * FROM design_form_fields WHERE field_uid = "${fieldUid}" AND template_id = ${id}`)
        if (query.length > 0 && query[0].length > 0) {
            return query[0][0];
        } else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in checking existing design form field')
        return false;
    }
}

// Check if field option exists - match installation template signature (field_id, option_id)
const checkExistingOptions = async (fieldId, optionId) => {
    try {
        // Only check if optionId is provided (existing option with integer ID)
        if (optionId === null || optionId === undefined) {
            return false;
        }
        let query = await sequelize.query(`SELECT * FROM design_form_field_options WHERE id = ${optionId} AND field_id = ${fieldId} AND status = 1`)
        if (query.length > 0 && query[0].length > 0) {
            return query[0][0];
        } else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in checking existing design form field option')
        return false;
    }
}

// Update template field options
const updateTemplateFieldOptions = async (data, id) => {
    try {
        let result = await DesignFormFieldOption.update(data, {
            where: {
                id: id
            }
        })
        if (result) {
            return true
        } else {
            return false
        }
    } catch (error) {
        console.log(error, 'error in updating design form field options')
        return false;
    }
}

// Batch insert design form submissions
const updateBatchData = async (table, data) => {
    try {
        if (empty(data) || data.length === 0) {
            return false;
        }
        for (const row of data) {
            const duplicateData = [];
            for (const [key, value] of Object.entries(row)) {
                duplicateData.push(`${key}='${value}'`);
            }
        
            const insertString = `INSERT INTO ${table} SET ${duplicateData.join(', ')}`;
            const updateString = `ON DUPLICATE KEY UPDATE ${duplicateData.join(', ')}`;
            const sql = `${insertString} ${updateString}`;
        
            try {
                const [result] = await sequelize.query(sql);      
            } catch (error) {     
                console.error(error);
            }
        }
        return true;
    } catch (error) {
        console.log(error, `error in batch update for ${table}`);
        return false;
    }
}

// Get saved design form submissions by template ID and design order ID
// Similar to getTemplateDataId in installation.js
const getDesignFormSubmissionsById = async (templateId, designOrderId) => {
    try {
        let result = await sequelize.query(`
            SELECT 
                dfs.*,
                dff.content,
                dff.html_tag,
                dff.field_uid,
                dff.name
            FROM design_form_submissions dfs
            LEFT JOIN design_form_fields dff ON dff.id = dfs.field_id
            WHERE dfs.template_id = ${templateId} 
            AND dfs.design_order_id = ${designOrderId}
            AND dfs.status = 1
        `);
        
        if (!empty(result) && result[0].length > 0) {
            return result[0];
        } else {
            return false;
        }
    } catch (error) {
        console.log(error, 'error in getting design form submissions by id');
        return false;
    }
}

// Get template data with saved values (similar to getInstTemplateDataById)
const getTemplateDataWithSavedValues = async (templateId, designOrderId) => {
    try {
        // First get the template structure
        let templateData = await getTemplateDataById(templateId);
        
        if (!templateData || templateData.length === 0) {
            return false;
        }
        
        // Get saved submissions
        let savedSubmissions = await getDesignFormSubmissionsById(templateId, designOrderId);
        
        // If no saved submissions, return template structure without values
        if (!savedSubmissions) {
            return templateData;
        }
        
        // Map saved values to fields
        // Handle multiple values for same field (e.g., multiple files, checkbox groups)
        let fieldValuesMap = {};
        
        savedSubmissions.forEach(submission => {
            const fieldUid = submission.field_uid || submission.name;
            if (!fieldValuesMap[fieldUid]) {
                fieldValuesMap[fieldUid] = [];
            }
            fieldValuesMap[fieldUid].push(submission.value);
        });
        
        // Update template data with saved values
        templateData.forEach(template => {
            Object.keys(template.fields).forEach(fieldUid => {
                const field = template.fields[fieldUid];
                const savedValues = fieldValuesMap[fieldUid];
                
                if (savedValues && savedValues.length > 0) {
                    // For file fields, we might have multiple values (content_1, content_2, etc.)
                    // For other fields, we typically have one value
                    if (field.tag === 'file' || field.html_tag === 'file') {
                        // Files are stored with multiple keys (content_1, content_2, etc.)
                        // We'll set the value as an array of URLs
                        field.savedValues = savedValues;
                    } else if (field.tag === 'checkbox-group' || field.html_tag === 'checkbox-group') {
                        // Checkbox groups can have multiple selected values
                        field.savedValues = savedValues;
                    } else {
                        // Single value fields (text, textarea, select, autocomplete, etc.)
                        field.value = savedValues[0];
                    }
                }
            });
        });
        
        return templateData;
    } catch (error) {
        console.log(error, 'error in getting template data with saved values');
        return false;
    }
}

// Get all templates with saved values for a design order (batch API - single call)
const getAllTemplatesWithSavedValues = async (designOrderId, module = 1) => {
    try {
        // First get all templates for the module
        const templates = await getDesignFormTemplatesByModule(module);
        
        if (!templates || templates.length === 0) {
            return [];
        }
        
        // Get all template IDs
        const templateIds = templates.map(t => t.id);
        
        if (templateIds.length === 0) {
            return [];
        }
        
        // Get all submissions for this design order and these templates in one query
        let allSubmissions = await sequelize.query(`
            SELECT 
                dfs.*,
                dff.content,
                dff.html_tag,
                dff.field_uid,
                dff.name,
                dff.template_id
            FROM design_form_submissions dfs
            LEFT JOIN design_form_fields dff ON dff.id = dfs.field_id
            WHERE dfs.design_order_id = ${designOrderId}
            AND dfs.template_id IN (${templateIds.join(',')})
            AND dfs.status = 1
        `);
        
        const submissions = allSubmissions[0] || [];
        
        // Group submissions by template_id
        const submissionsByTemplate = {};
        submissions.forEach(submission => {
            const templateId = submission.template_id;
            if (!submissionsByTemplate[templateId]) {
                submissionsByTemplate[templateId] = [];
            }
            submissionsByTemplate[templateId].push(submission);
        });
        
        // Process each template
        const templatesWithData = await Promise.all(
            templates.map(async (template) => {
                const templateId = template.id;
                
                // Get template structure
                const templateData = await getTemplateDataById(templateId);
                
                if (!templateData || templateData.length === 0) {
                    return null;
                }
                
                // Get saved submissions for this template
                const savedSubmissions = submissionsByTemplate[templateId] || [];
                
                // If no saved submissions, skip this template
                if (savedSubmissions.length === 0) {
                    return null;
                }
                
                // Map saved values to fields
                let fieldValuesMap = {};
                
                savedSubmissions.forEach(submission => {
                    const fieldUid = submission.field_uid || submission.name;
                    if (!fieldValuesMap[fieldUid]) {
                        fieldValuesMap[fieldUid] = [];
                    }
                    fieldValuesMap[fieldUid].push(submission.value);
                });
                
                // Update template data with saved values
                const templateWithValues = templateData[0];
                Object.keys(templateWithValues.fields).forEach(fieldUid => {
                    const field = templateWithValues.fields[fieldUid];
                    const savedValues = fieldValuesMap[fieldUid];
                    
                    if (savedValues && savedValues.length > 0) {
                        if (field.tag === 'file' || field.html_tag === 'file') {
                            field.savedValues = savedValues;
                        } else if (field.tag === 'checkbox-group' || field.html_tag === 'checkbox-group') {
                            field.savedValues = savedValues;
                        } else {
                            field.value = savedValues[0];
                        }
                    }
                });
                
                // Convert fields object to array format for frontend
                let fieldsArray = [];
                Object.keys(templateWithValues.fields).forEach(fieldUid => {
                    const field = templateWithValues.fields[fieldUid];
                    fieldsArray.push({
                        field_id: field.field_id,
                        name: field.name || field.field_uid,
                        content: field.content,
                        html_tag: field.tag || field.html_tag,
                        value: field.value || field.savedValues || '',
                        savedValues: field.savedValues || [],
                        options: field.options || [],
                        required: field.required,
                        field_uid: field.field_uid
                    });
                });
                
                // Check if template has at least one field with data
                const hasData = fieldsArray.some(field => {
                    const hasValue = field.value && field.value !== '' && field.value !== null
                    const hasSavedValues = field.savedValues && Array.isArray(field.savedValues) && field.savedValues.length > 0
                    return hasValue || hasSavedValues
                });
                
                if (hasData) {
                    return {
                        ...template,
                        fields: fieldsArray
                    };
                }
                
                return null;
            })
        );
        
        // Filter out null values (templates with no submissions or no data)
        return templatesWithData.filter(t => t !== null);
    } catch (error) {
        console.log(error, 'error in getting all templates with saved values');
        return [];
    }
}

// Delete all submissions for a design order
const deleteSubmissionsByDesignOrderId = async (designOrderId) => {
    try {
        const result = await sequelize.query(`
            DELETE FROM design_form_submissions 
            WHERE design_order_id = :designOrderId
        `, {
            replacements: { designOrderId },
            type: Sequelize.QueryTypes.DELETE
        });
        return true;
    } catch (error) {
        console.log(error, 'error in deleting design form submissions by design order id');
        return false;
    }
}

// Check if submissions exist for a design order and template
const checkSubmissionsExist = async (designOrderId, templateId) => {
    try {
        const result = await sequelize.query(`
            SELECT id 
            FROM design_form_submissions 
            WHERE design_order_id = :designOrderId AND template_id = :templateId
            LIMIT 1
        `, {
            replacements: { designOrderId, templateId },
            type: Sequelize.QueryTypes.SELECT
        });
        return result && result.length > 0;
    } catch (error) {
        console.log(error, 'error in checking design form submissions');
        return false;
    }
}

// Get template name by template ID
const getTemplateNameById = async (templateId) => {
    try {
        const result = await sequelize.query(`
            SELECT name 
            FROM design_form_templates 
            WHERE id = :templateId
        `, {
            replacements: { templateId },
            type: Sequelize.QueryTypes.SELECT
        });
        if (result && result[0] && result[0].name) {
            return result[0].name;
        }
        return null;
    } catch (error) {
        console.log(error, 'error in getting template name by id');
        return null;
    }
}

module.exports = {
    DesignFormTemplate,
    DesignFormField,
    DesignFormFieldOption,
    DesignFormSubmission,
    getAllDesignFormTemplates,
    getDesignFormTemplatesByModule,
    getAllTemplatesWithDataByModule,
    addTemplate,
    updateTemplate,
    addTemplateField,
    updateTemplateField,
    addTemplateFieldOptions,
    getTemplateDataById,
    deleteTemplate,
    deactivateTemplate,
    fetchOptions,
    removeFieldOptions,
    getTemplateByid,
    deteleCustomTemplateById,
    removeCustomField,
    checkExisting,
    checkExistingOptions,
    updateTemplateFieldOptions,
    updateBatchData,
    getDesignFormSubmissionsById,
    getTemplateDataWithSavedValues,
    getAllTemplatesWithSavedValues,
    deleteSubmissionsByDesignOrderId,
    checkSubmissionsExist,
    getTemplateNameById
}

