const { empty, removeNull } = require("../Helpers/Common");
const moment = require("moment");
const uniqid = require('uniqid');
const DesignFormTemplate = require("../models/designFormTemplate");
const Admin = require("../models/admin");
const RequestActivity = require("../models/RequestActivity");

// Add Design Form Template
const addDesignFormTemplate = async (req, res) => {
    try {
        let { userId, values, name } = req.body;
        const template = {
            name: name,
            timestamp: moment().unix(),
            updated_on: moment().unix(),
            added_by: req.body.userId,
            status: 6,
        };

        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 design form template!' });
            return;
        }

        let templateId = await DesignFormTemplate.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 DesignFormTemplate.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 DesignFormTemplate.addTemplateFieldOptions(customFieldOptions);
                    }
                }
            }
            let notificationMessage = "New Design Form Template " + name + " has been created"
            let notificationUrl = "design-order/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: 0, msg: "Failed to add design form template"
            })
        }
    } catch (error) {
        console.error(error);
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

// Get All Design Form Templates
const getAllDesignFormTemplate = async (req, res) => {
    try {
        let { value } = req.body
        let result = await DesignFormTemplate.getAllDesignFormTemplates(value)
        if (!empty(result)) {
            res.send({
                status: 1, result
            })
        } else {
            res.send({
                status: 0, result: []
            })
        }
    } catch (error) {
        console.log(error)
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

// Get Template By ID
const getDesignFormTemplateById = async (req, res) => {
    try {
        let { id } = req.body
        let data = await DesignFormTemplate.getTemplateDataById(id)
        
        let formattedData = [];
        
        // Match installation template exactly - no empty check before forEach
        data.forEach(item => {
            const templateName = item.template;
            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" : "";
                    
                    let mappedArray = field.options?.map(item => {
                        return {
                            label: item.label,
                            value: item.value,
                            selected: item.selected
                        };
                    });
                    
                    // Match installation template exactly - always include values
                    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
            });
        });
        
        // Match installation template response format exactly
        if (!empty(data)) {
            res.send({
                status: 1, data, formattedData
            })
        } else {
            res.send({
                status: 0
            })
        }
    } catch (error) {
        // Match installation template error handling
        console.log(error)
    }
}

// Update Design Form Template
const updateDesignFormTemplate = async (req, res) => {
    try {
        let { userId, values, name, id } = req.body;
        // Match installation template exactly - include timestamp, added_by, status: 1
        const template = {
            name: req.body.name,
            timestamp: moment().unix(),
            updated_on: moment().unix(),
            added_by: req.body.userId,
            status: 6,
        };

        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 update design form template!' });
            return;
        }

        let templateId = await DesignFormTemplate.updateTemplate(id, template)

        if (templateId) {
            let i = 1;
            // row.name is now field_uid (unique identifier) to handle cases where multiple fields share same row_id
            const names = values.map(item => `"${item.name}"`);
            const namesCSV = names.join(', ');

            let deleteExisting = await DesignFormTemplate.removeCustomField(id, namesCSV)

            for (const row of values) {
                // row.name is field_uid (unique identifier) from form builder
                let existing = await DesignFormTemplate.checkExisting(id, row.name)
                const customFields = {};
                customFields.template_id = templateId;
                // Preserve existing row_id if field exists, otherwise generate new row_id
                customFields.row_id = existing ? existing.row_id : ('row' + uniqid());
                customFields.column_id = existing ? existing.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();
                }

                // Match installation template exactly - preserve existing field_uid if field exists
                customFields.field_uid = existing ? existing.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){
                    // Match installation template exactly
                    fieldId = await DesignFormTemplate.updateTemplateField(existing.id, customFields)
                }
                else{
                    fieldId = await DesignFormTemplate.addTemplateField(customFields);
                }

                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(', ');

                    let fetchAllOptions = await DesignFormTemplate.fetchOptions(fieldId)
                    if (fetchAllOptions) {
                        let deleteExisting = await DesignFormTemplate.removeFieldOptions(fieldId, namesCSV)
                    }

                    for (const fieldOption of row.values) {
                        // Match installation template - checkExistingOptions(field_id, option_id)
                        // Only check if fieldOption.value is an integer (existing option ID)
                        let existing = await DesignFormTemplate.checkExistingOptions(fieldId, Number.isInteger(fieldOption.value) ? fieldOption.value : null)
                        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;

                        if(existing){
                            const fieldOptionId = await DesignFormTemplate.updateTemplateFieldOptions(customFieldOptions, fieldOption.value)
                        }
                        else{
                            const fieldOptionId = await DesignFormTemplate.addTemplateFieldOptions(customFieldOptions);
                        }
                    }
                }
            }
            // Match installation template exactly - send notification to user who updated too
            let notificationMessage = "Design Form Template " + req.body.name + " has been Updated"
            let notificationUrl = "design-order/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);
                }
            }
            // Match installation template - also notify the user who updated
            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 {
            // Match installation template error message format
            res.send({
                status: 1, msg: "Failed to add new template"
            })
        }
    } catch (error) {
        // Match installation template error handling
        console.error(error);
        res.status(500).send({ message: "Server error" + error });
    }
}

// Delete Design Form Template
const deleteDesignFormTemplate = async (req, res) => {
    try {
        const { data } = req.body
        let result = await DesignFormTemplate.deteleCustomTemplateById(data.id)
        if (result === true) {
            res.status(200).send({
                status: 1, message: `Design Form Template ${data.name} has been deleted successfully`
            })
        } else {
            res.status(500).send({
                status: 0, message: `Failed to delete ${data.name}`
            })
        }
    } catch (error) {
        console.log(error)
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

// Deactivate/Activate Design Form Template
const deactivateDesignFormTemplate = 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 DesignFormTemplate.getTemplateByid(templateId)
            let updated = await DesignFormTemplate.deactivateTemplate(templateId, status)

            if (updated) {
                let notificationMsg = status === 6
                    ? `The design form template "${data['name']}" has been made active.`
                    : `The design form template "${data['name']}" has been deactivated.`;
                let notificationUrl = "design-order/template";

                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: notificationMsg
                })
            } else {
                res.send({
                    status: 0, message: "Failed to update template status"
                })
            }
        } else {
            res.send({
                status: 0, message: "Template ID is required"
            })
        }
    } catch (error) {
        console.log(error)
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

// Duplicate Design Form Template
const duplicateDesignFormTemplate = async (req, res) => {
    try {
        let { userId, id } = req.body;

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

        data.forEach(item => {
            const templateName = item.template;
            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" : "";

                    let mappedArray = field.options?.map(item => {
                        return {
                            label: item.label,
                            value: item.value,
                            selected: item.selected,
                        };
                    });

                    fields.push({
                        label,
                        type,
                        required: required === 0 ? false : true,
                        className: className,
                        values: mappedArray,
                        field_id,
                        name
                    });
                }
            }

            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: 6,
        };

        const formFields = formattedData[0].fields;

        let formFieldId = uniqid()
        template['template_uid'] = formFieldId
        template['stage_uid'] = uniqid()

        if (empty(formFields)) {
            res.status(400).send({ status: 0, message: 'Failed to duplicate design form template!' });
            return;
        }

        let templateId = await DesignFormTemplate.addTemplate(template)

        if (templateId) {
            let i = 1;

            for (const row of formFields) {
                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;
                }

                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++;

                customFields.timestamp = moment().unix();
                customFields.added_by = userId;
                customFields.status = 1;

                const fieldId = await DesignFormTemplate.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 DesignFormTemplate.addTemplateFieldOptions(customFieldOptions);
                    }
                }
            }
            res.send({
                status: 1, msg: "Design Form Template duplicated successfully"
            })
        }
        else {
            res.send({
                status: 0, msg: "Failed to duplicate design form template"
            })
        }
    } catch (error) {
        console.error(error);
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

// Get Design Form Templates by Module
const getDesignFormTemplatesByModule = async (req, res) => {
    try {
        let { module } = req.body;
        
        if (module === undefined || module === null) {
            res.status(400).send({ status: 0, message: 'Module parameter is required!' });
            return;
        }

        let result = await DesignFormTemplate.getDesignFormTemplatesByModule(module);
        
        if (result && result.length > 0) {
            res.send({
                status: 1,
                data: result
            });
        } else {
            res.send({
                status: 1,
                data: []
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

// Get all templates with form data by module (batch API - single call)
const getAllTemplatesWithDataByModule = async (req, res) => {
    try {
        let { module } = req.body;
        
        if (module === undefined || module === null) {
            res.status(400).send({ status: 0, message: 'Module parameter is required!' });
            return;
        }

        let result = await DesignFormTemplate.getAllTemplatesWithDataByModule(module);
        
        if (result && result.length > 0) {
            res.send({
                status: 1,
                data: result
            });
        } else {
            res.send({
                status: 1,
                data: []
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

// Save Design Form Template Submission
const saveDesignFormTemplate = async (req, res) => {
    try {
        let { submitForm, design_order_id, id, status, userId } = req.body;
        let currentDate = moment().unix();

        if (!design_order_id || !id) {
            res.status(400).send({ status: 0, message: 'Design order ID and template ID are required!' });
            return;
        }

        if (empty(submitForm)) {
            res.status(400).send({ status: 0, message: 'Form data is required!' });
            return;
        }

        // Check if submissions exist to determine if it's an add or update
        const submissionsExist = await DesignFormTemplate.checkSubmissionsExist(design_order_id, id);

        const field_value_pairs = [];
        let valueData = removeNull(submitForm);
        
        // Track unique field_id + value combinations to prevent duplicates
        const seenPairs = new Set();

        for (const [key, value] of Object.entries(valueData)) {
            // Skip checkboxgroup key - checkbox values are stored in field-specific arrays
            if (key === 'checkboxgroup') {
                continue;
            }
            
            // Handle regular fields (text, textarea, date, number, select, file, etc.)
            // This includes files stored as content_1, content_2, etc.
            if (value && typeof value === 'object' && "value" in value && "field_id" in value) {
                const formattedValue =
                    value.content === "date" && typeof value.value === 'number' && !isNaN(value.value)
                        ? moment.unix(value.value).format('YYYY-MM-DD')
                        : value.value;
                
                // Only save if value is not empty
                if (formattedValue !== '' && formattedValue !== null && formattedValue !== undefined) {
                    const pairKey = `${id}_${value.field_id}_${formattedValue}`;
                    if (!seenPairs.has(pairKey)) {
                        seenPairs.add(pairKey);
                        field_value_pairs.push({
                            design_order_id: design_order_id,
                            template_id: id,
                            field_id: value.field_id,
                            value: formattedValue,
                            timestamp: currentDate,
                            status: status || 1,
                        });
                    }
                }
            } 
            // Handle checkbox groups (array of objects with field_id and value)
            else if (value && Array.isArray(value) && value.length > 0) {
                for (const item of value) {
                    if (item && typeof item === 'object' && "field_id" in item && !empty(item.value)) {
                        const formattedValue = item.value;
                        const pairKey = `${id}_${item.field_id}_${formattedValue}`;
                        
                        // Only add if we haven't seen this combination before (prevent duplicates)
                        if (!seenPairs.has(pairKey)) {
                            seenPairs.add(pairKey);
                            field_value_pairs.push({
                                design_order_id: design_order_id,
                                template_id: id,
                                field_id: item.field_id,
                                value: formattedValue,
                                timestamp: currentDate,
                                status: status || 1,
                            });
                        }
                    }
                }
            }
        }

        if (!empty(field_value_pairs)) {
            let submissionResponse = await DesignFormTemplate.updateBatchData(
                "design_form_submissions",
                field_value_pairs
            );
            
            if (submissionResponse) {
                // Add activity log
                const activityMessage = submissionsExist 
                    ? "Design forms updated successfully."
                    : "Design forms added successfully.";
                
                const activityData = {
                    design_order_id: design_order_id,
                    activity: activityMessage,
                    added_by: userId,
                    timestamp: currentDate,
                    status: 1
                };
                
                await RequestActivity.addDesignOrderUpdate(activityData);
                
                res.send({
                    status: 1,
                    message: "Design form template saved successfully"
                });
            } else {
                res.send({
                    status: 0,
                    message: "Failed to save design form template"
                });
            }
        } else {
            res.send({
                status: 0,
                message: "No form data to save"
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

// Batch save multiple design form templates at once
const batchSaveDesignFormTemplates = async (req, res) => {
    try {
        let { forms, design_order_id, status, userId, deleteExisting } = req.body;
        let currentDate = moment().unix();

        if (!design_order_id) {
            res.status(400).send({ status: 0, message: 'Design order ID is required!' });
            return;
        }

        if (empty(forms) || !Array.isArray(forms) || forms.length === 0) {
            res.status(400).send({ status: 0, message: 'Forms array is required!' });
            return;
        }

        // Check if any submissions exist for this design order (before delete if deleteExisting is true)
        let submissionsExist = false;
        if (deleteExisting !== true) {
            // Check if any template has existing submissions
            for (const formData of forms) {
                const { id: templateId } = formData;
                if (templateId) {
                    const exists = await DesignFormTemplate.checkSubmissionsExist(design_order_id, templateId);
                    if (exists) {
                        submissionsExist = true;
                        break;
                    }
                }
            }
        } else {
            // If deleteExisting is true, it's always an update
            submissionsExist = true;
        }

        // If deleteExisting is true, delete all existing submissions for this design order
        // This ensures clean updates when fields/options are added or edited
        if (deleteExisting === true) {
            try {
                await DesignFormTemplate.deleteSubmissionsByDesignOrderId(design_order_id);
                console.log(`Deleted existing submissions for design order ${design_order_id}`);
            } catch (deleteError) {
                console.error('Error deleting existing submissions:', deleteError);
                // Continue with save even if delete fails
            }
        }

        const allFieldValuePairs = [];

        // Process each form
        for (const formData of forms) {
            const { submitForm, id: templateId } = formData;

            if (!templateId) {
                console.warn('Skipping form without template ID');
                continue;
            }

            if (empty(submitForm)) {
                console.warn(`Skipping form ${templateId} - no form data`);
                continue;
            }

            let valueData = removeNull(submitForm);

            // Track unique field_id + value combinations to prevent duplicates
            const seenPairs = new Set();
            
            for (const [key, value] of Object.entries(valueData)) {
                // Skip checkboxgroup key - checkbox values are stored in field-specific arrays
                if (key === 'checkboxgroup') {
                    continue;
                }
                
                // Handle regular fields (text, textarea, date, number, select, file, etc.)
                if (value && typeof value === 'object' && "value" in value && "field_id" in value) {
                    const formattedValue =
                        value.content === "date" && typeof value.value === 'number' && !isNaN(value.value)
                            ? moment.unix(value.value).format('YYYY-MM-DD')
                            : value.value;
                    
                    // Only save if value is not empty
                    if (formattedValue !== '' && formattedValue !== null && formattedValue !== undefined) {
                        const pairKey = `${templateId}_${value.field_id}_${formattedValue}`;
                        if (!seenPairs.has(pairKey)) {
                            seenPairs.add(pairKey);
                            allFieldValuePairs.push({
                                design_order_id: design_order_id,
                                template_id: templateId,
                                field_id: value.field_id,
                                value: formattedValue,
                                timestamp: currentDate,
                                status: status || 1,
                            });
                        }
                    }
                } 
                // Handle checkbox groups (array of objects with field_id and value)
                else if (value && Array.isArray(value) && value.length > 0) {
                    for (const item of value) {
                        if (item && typeof item === 'object' && "field_id" in item && !empty(item.value)) {
                            const formattedValue = item.value;
                            const pairKey = `${templateId}_${item.field_id}_${formattedValue}`;
                            
                            // Only add if we haven't seen this combination before
                            if (!seenPairs.has(pairKey)) {
                                seenPairs.add(pairKey);
                                allFieldValuePairs.push({
                                    design_order_id: design_order_id,
                                    template_id: templateId,
                                    field_id: item.field_id,
                                    value: formattedValue,
                                    timestamp: currentDate,
                                    status: status || 1,
                                });
                            }
                        }
                    }
                }
            }
        }

        if (!empty(allFieldValuePairs)) {
            let submissionResponse = await DesignFormTemplate.updateBatchData(
                "design_form_submissions",
                allFieldValuePairs
            );
            
            if (submissionResponse) {
                // Add single activity log
                const activityMessage = submissionsExist 
                    ? "Design forms updated successfully."
                    : "Design forms added successfully.";
                
                const activityData = {
                    design_order_id: design_order_id,
                    activity: activityMessage,
                    added_by: userId,
                    timestamp: currentDate,
                    status: 1
                };
                
                await RequestActivity.addDesignOrderUpdate(activityData);
                
                res.send({
                    status: 1,
                    message: `Successfully saved ${forms.length} design form template(s)`,
                    savedCount: forms.length
                });
            } else {
                res.send({
                    status: 0,
                    message: "Failed to save design form templates"
                });
            }
        } else {
            res.send({
                status: 0,
                message: "No form data to save"
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

// Get Design Form Template with Saved Values (for viewing/editing)
// Similar to getInstTemplateDatabyId in installation.js
const getDesignFormTemplateWithSavedValues = async (req, res) => {
    try {
        const { templateId, designOrderId } = req.body;
        
        if (!templateId || !designOrderId) {
            res.status(400).send({ 
                status: 0, 
                message: 'Template ID and Design Order ID are required!' 
            });
            return;
        }
        
        const data = await DesignFormTemplate.getTemplateDataWithSavedValues(
            templateId, 
            designOrderId
        );
        
        if (data && data.length > 0) {
            // Format the response similar to installation template
            // Convert fields object to array format for easier frontend handling
            let formattedData = data.map(template => {
                let fieldsArray = [];
                Object.keys(template.fields).forEach(fieldUid => {
                    const field = template.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
                    });
                });
                
                return {
                    template: template.template,
                    template_id: template.template_id,
                    fields: fieldsArray
                };
            });
            
            res.status(200).send({
                status: 1,
                data: formattedData
            });
        } else {
            res.status(200).send({
                status: 0,
                message: 'No template data found'
            });
        }
    } catch (error) {
        console.error(error, 'error in getting design form template with saved values');
        res.status(500).send({ 
            status: 0, 
            message: 'Server error: ' + error.message 
        });
    }
}

// Get all templates with saved values for a design order (batch API - single call)
const getAllDesignFormTemplatesWithSavedValues = async (req, res) => {
    try {
        const { designOrderId, module } = req.body;

        if (!designOrderId) {
            res.status(400).send({
                status: 0,
                message: 'Design Order ID is required!'
            });
            return;
        }

        const data = await DesignFormTemplate.getAllTemplatesWithSavedValues(
            designOrderId,
            module || 1
        );

        if (data && data.length > 0) {
            res.status(200).send({
                status: 1,
                data: data
            });
        } else {
            res.status(200).send({
                status: 1,
                data: []
            });
        }
    } catch (error) {
        console.error(error, 'error in getting all design form templates with saved values');
        res.status(500).send({
            status: 0,
            message: 'Server error: ' + error.message
        });
    }
}

// Link Module to Design Form Template
const linkModuleToTemplate = async (req, res) => {
    try {
        let { templateId, module, userId } = req.body;

        if (!templateId || !module) {
            res.status(400).send({ status: 0, message: 'Template ID and module are required!' });
            return;
        }

        // Validate module value (1 = Design Order, 2 = Sales Order, etc.)
        if (!Number.isInteger(module) || module < 1) {
            res.status(400).send({ status: 0, message: 'Invalid module value!' });
            return;
        }

        const template = {
            module: module,
            updated_on: moment().unix(),
        };

        let result = await DesignFormTemplate.updateTemplate(templateId, template);

        if (result) {
            let notificationMessage = `Module has been linked to template`;
            let notificationUrl = "design-order/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,
                message: "Module linked successfully"
            });
        } else {
            res.send({
                status: 0,
                message: "Failed to link module"
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).send({ status: 0, message: "Server error: " + error });
    }
}

module.exports = {
    addDesignFormTemplate,
    getAllDesignFormTemplate,
    getDesignFormTemplateById,
    updateDesignFormTemplate,
    deleteDesignFormTemplate,
    deactivateDesignFormTemplate,
    duplicateDesignFormTemplate,
    linkModuleToTemplate,
    getDesignFormTemplatesByModule,
    getAllTemplatesWithDataByModule,
    saveDesignFormTemplate,
    batchSaveDesignFormTemplates,
    getDesignFormTemplateWithSavedValues,
    getAllDesignFormTemplatesWithSavedValues
}

