<?php

namespace GriffinForms\Admin\Js\Local;

class Field extends \GriffinForms\Admin\Js\Local\Single
{
    public function createItem()
    {
        $nonce = wp_create_nonce('create_item');
        return '$("#griffinforms-create-item").click(function(){
            var itemType, data;
            
            resetItemErrors();
            griffinformsHandleAjaxState("waiting"),
            checkItemDataFunctions();
            const itemData = getItemData();
            
            if (griffinformsErrors) {
                $("#griffinforms-item-errors-wrap").show();
                $("html, body").animate({scrollTop: $("#wpbody-content").offset().top}, 200);
                griffinformsHandleAjaxState("done");
                return;
            }
            
            itemType = $(this).attr("data-item-type");
            const jsonData = JSON.stringify(itemData);
            
            data = {
                "action": "createItem",
                "item_type": itemType,
                "field_type": "' . esc_js($this->data['field_type']) . '",
                "item_data": jsonData,
                "nonce": "' . esc_js($nonce) . '"
            };

            griffinformsHandleAjaxState("waiting");
            $.ajax({
                type: "POST",
                url: ajaxurl,
                data: data,
                success: function(response) {
                    try {
                        var json = typeof response === "object" ? response : JSON.parse(response);

                        if (json.success && json.data) {
                            location.replace("' . esc_url_raw($this->editUrl()) . '&id=" + json.data);
                        } else {
                            var text = json.msg || "' . esc_js(__('Failed to create field.', 'griffinforms-form-builder')) . '";
                            griffinformsSnackBar(text, json.time || "");
                        }
                    } catch (e) {
                        griffinformsSnackBar("' . esc_js(__('An unexpected error occurred while creating the field.', 'griffinforms-form-builder')) . '");
                    }
                    griffinformsHandleAjaxState("done");
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    griffinformsSnackBar("' . esc_js(__('Network or server error while creating the field.', 'griffinforms-form-builder')) . '");
                    griffinformsHandleAjaxState("done");
                }
            });
        });';
    }

    public function getIsRequired()
    {
        return 'function getIsrequired() {
            return getToggleCheckBox("griffinforms-isrequired-togglecheckbox");
        }';
    }

    public function getIsReadonly()
    {
        return 'function getIsreadonly() {
            return getToggleCheckBox("griffinforms-isreadonly-togglecheckbox");
        }';
    }

    public function getIsDisabled()
    {
        return 'function getIsdisabled() {
            return getToggleCheckBox("griffinforms-isdisabled-togglecheckbox");
        }';
    }

    public function getIsHidden()
    {
        return 'function getIshidden() {
            return getToggleCheckBox("griffinforms-ishidden-togglecheckbox");
        }';
    }

    public function getIsReusable()
    {
        return 'function getIsreusable() {
            return getToggleCheckBox("griffinforms-isreusable-togglecheckbox");
        }';
    }

    /**
     * Generates JavaScript code to collect the default value for this field type.
     * Supports textarea, inputnumber, inputdate, and generic inputtext.
     *
     * @return string JavaScript code snippet.
     */
    protected function defaultValueJs()
    {
        switch ($this->data['field_type']) {
            case 'textarea':
                return '$("#griffinforms-customtextareavalue-textarea").val();';
            case 'inputnumber':
                return '$("#griffinforms-custominputnumbervalue-inputnumber").val();';
            case 'inputdate':
                return '(function() {
                    var inputValue = $("#griffinforms-custominputdatevalue-inputdate").val().trim();
                    var dateObj = $("#griffinforms-custominputdatevalue-inputdate").datepicker("getDate");
                    if (!dateObj || isNaN(dateObj.getTime())) {
                        showItemError("' . esc_js($this->lang->getText('invalid_date_selected')) . '", "griffinforms-custominputdatevalue-inputdate");
                        return null;
                    }
                    var formattedDate = $.datepicker.formatDate("mm/dd/yy", dateObj);
                    if (formattedDate !== inputValue) {
                        showItemError("' . esc_js($this->lang->getText('invalid_date_selected')) . '", "griffinforms-custominputdatevalue-inputdate");
                        return null;
                    }
                    return Math.floor(dateObj.getTime() / 1000);
                })()';
            case 'inputtime':
                return '(function() {
                    var timeValue = $("#griffinforms-custominputtimevalue-inputtime").val().trim();
                    if (!timeValue) {
                        return "";
                    }
                    var timeParts = timeValue.match(/^(\d{1,2}):(\d{2})$/);
                    if (!timeParts) {
                        showItemError("' . esc_js($this->lang->getText('invalid_time_format')) . '", "griffinforms-custominputtimevalue-inputtime");
                        return null;
                    }
                    var hours = parseInt(timeParts[1], 10);
                    var minutes = parseInt(timeParts[2], 10);
                    if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {
                        showItemError("' . esc_js($this->lang->getText('invalid_time_format')) . '", "griffinforms-custominputtimevalue-inputtime");
                        return null;
                    }
                    var timestamp = Date.UTC(1970, 0, 1, hours, minutes, 0, 0) / 1000;
                    return timestamp;
                })()';
            default:
                return '$("#griffinforms-custom' . esc_attr($this->data['field_type']) . 'value-inputtext").val();';
        }
    }

    /**
     * Outputs JavaScript function to collect default value configuration.
     * Handles custom, variable, and URL GET-based defaults.
     *
     * @return string JavaScript function definition.
     */
    public function getDefaultValue()
    {
        $default_input_id_type = $this->data['field_type'] === 'textarea'
            ? 'textarea'
            : (in_array($this->data['field_type'], array('inputdate', 'inputtime'), true) ? $this->data['field_type'] : 'text');

        if ($this->data['field_type'] === 'inputdate') {
            $default_input_id = 'griffinforms-custominputdatevalue-inputdate';
        } elseif ($this->data['field_type'] === 'inputtime') {
            $default_input_id = 'griffinforms-custominputtimevalue-inputtime';
        } else {
            $default_input_id = 'griffinforms-custom' . esc_attr($this->data['field_type']) . 'value-input' . $default_input_id_type;
        }
            
        return 'function getDefaultvalue() {
            // Determine the expected input element ID based on field type.
            var fieldValue = {};
            // Initialize fieldValue object and read the selected default value type.
            var valueType = $("#griffinforms-fielddefaultvalue-selectfield").val();
            fieldValue["value_type"] = valueType;

            // Handle custom default value input.
            if (valueType == "custom") {
                fieldValue["custom"] = ' . $this->defaultValueJs() . ';
                if (!fieldValue["custom"]) {
                    showItemError("' . esc_js($this->lang->getText('default_value_required')) . '", "' . $default_input_id . '");
                }
            }

            // Handle variable-based default value selection.
            if (valueType == "variable") {
                fieldValue["variable"] = $("#griffinforms-field' . esc_attr($this->data['field_type']) . 'variablevalue-selectfield").val();
            }

            // Handle GET parameter override if enabled.
            if ($("#griffinforms-urlget-togglecheckbox").is(":checked")) {
                fieldValue["get_value"] = 1;
                fieldValue["get_name"] = $("#griffinforms-getname-inputtext").val();
                if (!fieldValue["get_name"]) {
                    showItemError("' . esc_js($this->lang->getText('default_value_getname_required')) . '", "griffinforms-getname-inputtext");
                }
            } else {
                fieldValue["get_value"] = 0;
            }

            // Return the collected default value configuration.
            return fieldValue;
        }';
    }

    public function getPlaceholder()
    {
        return 'function getPlaceholder() {
            return $("#griffinforms-placeholder-inputtext").val();
        }';
    }

    public function getAutocomplete()
    {
        return 'function getAutocomplete() {
            return $("#griffinforms-autocomplete-togglecheckbox").is(":checked") ? 1 : 0;
        }';
    }

    protected function getSignatureSettings()
    {
        return 'function getFieldsettings() {
            var padHeightVal = $("#griffinforms-padheight-inputnumber").val().trim();
            var penThicknessVal = $("#griffinforms-penthickness-inputnumber").val().trim();

            if (!isValidPositiveInteger(padHeightVal)) {
                showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-padheight-inputnumber");
                return "";
            }
            var padHeight = parseInt(padHeightVal, 10);
            if (padHeight < 50 || padHeight > 600) {
                showItemError("' . esc_js(__('Pad height must be between 50 and 600.', 'griffinforms-form-builder')) . '", "griffinforms-padheight-inputnumber");
                return "";
            }

            if (!isValidPositiveInteger(penThicknessVal)) {
                showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-penthickness-inputnumber");
                return "";
            }
            var penThickness = parseInt(penThicknessVal, 10);
            if (penThickness < 1 || penThickness > 10) {
                showItemError("' . esc_js(__('Pen thickness must be between 1 and 10.', 'griffinforms-form-builder')) . '", "griffinforms-penthickness-inputnumber");
                return "";
            }

            return {
                pad_height:            padHeight,
                pen_color:             $("#griffinforms-pencolor-inputcolor").val() || "#000000",
                pen_thickness:         penThickness,
                bg_color:              $("#griffinforms-bgcolor-inputcolor").val() || "#ffffff",
                signature_placeholder: $("#griffinforms-signatureplaceholder-inputtext").val()
            };
        }';
    }

    protected function getInputratingSettings()
    {
        return 'function getFieldsettings() {
            const scaleVal = parseInt($("#griffinforms-scale-inputnumber").val(), 10);
            const iconSizeVal = parseInt($("#griffinforms-iconsize-inputnumber").val(), 10);
            const iconSpacingVal = parseInt($("#griffinforms-iconspacing-inputnumber").val(), 10);

            if (Number.isNaN(scaleVal) || scaleVal < 2 || scaleVal > 10) {
                showItemError("' . esc_js(__('Scale must be between 2 and 10.', 'griffinforms-form-builder')) . '", "griffinforms-scale-inputnumber");
                return "";
            }
            if (Number.isNaN(iconSizeVal) || iconSizeVal < 16) {
                showItemError("' . esc_js(__('Icon size must be at least 16px.', 'griffinforms-form-builder')) . '", "griffinforms-iconsize-inputnumber");
                return "";
            }
            if (iconSizeVal > 64) {
                showItemError("' . esc_js(__('Icon size must be 64px or less.', 'griffinforms-form-builder')) . '", "griffinforms-iconsize-inputnumber");
                return "";
            }
            if (Number.isNaN(iconSpacingVal) || iconSpacingVal < 0) {
                showItemError("' . esc_js(__('Icon spacing must be zero or greater.', 'griffinforms-form-builder')) . '", "griffinforms-iconspacing-inputnumber");
                return "";
            }
            if (iconSpacingVal > 24) {
                showItemError("' . esc_js(__('Icon spacing must be 24px or less.', 'griffinforms-form-builder')) . '", "griffinforms-iconspacing-inputnumber");
                return "";
            }

            const labels = [];
            const stepImages = [];
            $("#griffinforms-rating-steps .rating-step-label").each(function() {
                labels.push($(this).val().trim());
            });
            $("#griffinforms-rating-steps .rating-step-image-id").each(function() {
                stepImages.push(parseInt($(this).val(), 10) || 0);
            });

            while (labels.length < scaleVal) labels.push("");
            while (stepImages.length < scaleVal) stepImages.push(0);
            labels.length = scaleVal;
            stepImages.length = scaleVal;

            return {
                scale: scaleVal,
                icon_group: $("input[name=\"icon_group\"]:checked").val() || "star",
                icon_size: iconSizeVal,
                icon_spacing: iconSpacingVal,
                color_filled: $("#griffinforms-rating-colorfilled-inputcolor").val() || "#f5a623",
                color_empty: $("#griffinforms-rating-colorempty-inputcolor").val() || "#d1d5db",
                custom_image_id: parseInt($("#griffinforms-rating-customimage-id").val(), 10) || 0,
                step_image_ids: stepImages,
                step_labels: labels,
                allow_clear: $("#griffinforms-rating-clear-togglecheckbox").is(":checked") ? 1 : 0
            };
        }';
    }

    protected function getInputrichtextSettings()
    {
        return 'function getFieldsettings() {
            var toolbar = [];
            $(".griffinforms-richtext-toolbar-item:checked").each(function() {
                toolbar.push($(this).val());
            });

            var minHeightVal = $("#griffinforms-minheight-inputnumber").val().trim();
            var maxHeightVal = $("#griffinforms-maxheight-inputnumber").val().trim();
            var maxCharsVal  = $("#griffinforms-maxcharacters-inputnumber").val().trim();

            var minHeight = parseInt(minHeightVal, 10);
            if (isNaN(minHeight) || minHeight < 50) {
                showItemError("' . esc_js(__('Minimum height must be at least 50 px.', 'griffinforms-form-builder')) . '", "griffinforms-minheight-inputnumber");
                return "";
            }

            var maxHeight = parseInt(maxHeightVal, 10);
            if (isNaN(maxHeight) || maxHeight < 0) {
                maxHeight = 0;
            }
            if (maxHeight > 0 && maxHeight < minHeight) {
                showItemError("' . esc_js(__('Maximum height must be greater than minimum height, or 0 for no limit.', 'griffinforms-form-builder')) . '", "griffinforms-maxheight-inputnumber");
                return "";
            }

            var maxChars = parseInt(maxCharsVal, 10);
            if (isNaN(maxChars) || maxChars < 0) {
                maxChars = 0;
            }

            return {
                toolbar:        toolbar,
                placeholder:    $("#griffinforms-placeholder-inputtext").val(),
                min_height:     minHeight,
                max_height:     maxHeight,
                max_characters: maxChars
            };
        }';
    }

    protected function getInputrichtextValidations()
    {
        return 'function getValidations() {
            return {};
        }';
    }

    protected function getInputlikertSettings()
    {
        return 'function getFieldsettings() {
            var raw = document.getElementById("gf-likert-data");
            if (!raw) return "";

            var data;
            try { data = JSON.parse(raw.value || "{}"); } catch(e) { return ""; }

            var rows    = data.rows    || [];
            var columns = data.columns || [];

            if (rows.length < 1) {
                showItemError("' . esc_js(__('At least one row is required.', 'griffinforms-form-builder')) . '", "gf-likert-data");
                return "";
            }
            if (columns.length < 2) {
                showItemError("' . esc_js(__('At least two columns are required.', 'griffinforms-form-builder')) . '", "gf-likert-data");
                return "";
            }

            for (var i = 0; i < rows.length; i++) {
                if (!rows[i].label || rows[i].label.trim() === "") {
                    showItemError("' . esc_js(__('All row labels must be filled in.', 'griffinforms-form-builder')) . '", "gf-likert-data");
                    return "";
                }
            }
            for (var j = 0; j < columns.length; j++) {
                if (!columns[j].label || columns[j].label.trim() === "") {
                    showItemError("' . esc_js(__('All column labels must be filled in.', 'griffinforms-form-builder')) . '", "gf-likert-data");
                    return "";
                }
            }

            return data;
        }';
    }

    protected function getInputlikertValidations()
    {
        return 'function getValidations() {
            return {};
        }';
    }

    protected function getImageselectionSettings()
    {
        return 'function getFieldsettings() {
            var fieldValue = {
                options: [],
                columns_desktop: parseInt($("#gf-imageselection-columns-desktop").val(), 10) || 3,
                columns_mobile: parseInt($("#gf-imageselection-columns-mobile").val(), 10) || 2,
                show_title: $("#gf-imageselection-show-title").is(":checked") ? 1 : 0,
                show_description: $("#gf-imageselection-show-description").is(":checked") ? 1 : 0,
                aspect_ratio: $("#gf-imageselection-aspect-ratio").val() || "1:1",
                randomise: $("#gf-imageselection-randomise").is(":checked") ? 1 : 0,
                default_selected: []
            };

            $(".gf-imageselection-option-row").each(function() {
                var row = $(this);
                var option = {
                    image_id: parseInt(row.find(".gf-imageselection-option-image-id").val(), 10) || 0,
                    image_url: row.find(".gf-imageselection-option-image-url").val() || "",
                    title: row.find(".gf-imageselection-option-title").val() || "",
                    description: row.find(".gf-imageselection-option-description").val() || "",
                    value: row.find(".gf-imageselection-option-value").val() || "",
                    is_none_option: row.find(".gf-imageselection-option-is-none").is(":checked") ? 1 : 0
                };

                if (option.value) {
                    fieldValue.options.push(option);
                }
            });

            $("#gf-imageselection-default-selected-list .gf-imageselection-default-selected-item:checked").each(function() {
                var value = $(this).val();
                if (value) {
                    fieldValue.default_selected.push(value);
                }
            });

            return fieldValue;
        }';
    }

    protected function getImageselectionValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            var validationType = $("#griffinforms-imageselectionvalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "min_max_select") {
                var minSelections = $("#griffinforms-minselections-inputnumber").val();
                var maxSelections = $("#griffinforms-maxselections-inputnumber").val();

                if (!isValidPositiveInteger(minSelections)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-minselections-inputnumber");
                    minSelections = 0;
                }

                if (!isValidPositiveInteger(maxSelections)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-maxselections-inputnumber");
                    maxSelections = 0;
                }

                minSelections = parseInt(minSelections, 10);
                maxSelections = parseInt(maxSelections, 10);

                if (minSelections > 0 && maxSelections > 0 && maxSelections < minSelections) {
                    showItemError("' . esc_js(__('Maximum selections must be greater than or equal to minimum selections.', 'griffinforms-form-builder')) . '", "griffinforms-maxselections-inputnumber");
                }

                fieldValue["min_selections"] = minSelections;
                fieldValue["max_selections"] = maxSelections;
            }

            return fieldValue;
        }';
    }

    public function getFieldOptions()
    {
        $method = 'get' . ucfirst($this->data['field_type']) . 'FieldOptions';
        if (method_exists($this, $method)) {
            return $this->$method();
        }

        $group_selector = $this->data['field_type'] === 'selectfield'
            ? '$(this).find(".griffinforms-selectfield-options-groupname").val()'
            : 'index';

        return 'function getFieldoptions() {
            var fieldValue = {};
            var fieldOptions = 0;

            $(".griffinforms-field-options-container").children(".griffinforms-field-optionsgroup").each(function(index) {
                var groupName = ' . $group_selector . ';
                var optionPair = {};

                $(this).find(".griffinforms-field-options-pair").each(function() {
                    var optionName = $(this).find(".griffinforms-field-optionname").val().trim();
                    var optionValue = $(this).find(".griffinforms-field-optionvalue").val().trim();

                    if (optionName !== "" && optionValue !== "") {
                        fieldOptions++;
                        optionPair[optionName] = optionValue;
                    }
                });

                if (Object.keys(optionPair).length > 0) {
                    fieldValue[groupName] = optionPair;
                }
            });

            if (fieldOptions === 0) {
                showItemError("' . esc_js($this->lang->getText('at_least_one_option_required')) . '", "griffinforms-field-options-container");
            }

            return fieldValue;
        }';
    }

    protected function getPaymentFieldOptions()
    {
        return 'function getFieldoptions() {
            const products = [];
            let hasInvalidQuantity = false;
            const seenSkus = {};

            function parsePositiveIntField($input, fallback) {
                const raw = ($input.val() || "").trim();
                if (raw === "") {
                    $input.removeClass("border-danger");
                    return fallback;
                }
                if (!/^[0-9]+$/.test(raw)) {
                    showItemError("' . esc_js(__('Quantity fields accept only numbers.', 'griffinforms-form-builder')) . '", "griffinforms-payment-products");
                    $input.addClass("border-danger");
                    hasInvalidQuantity = true;
                    return fallback;
                }
                $input.removeClass("border-danger");
                return parseInt(raw, 10);
            }

            $(".griffinforms-payment-product-card").each(function() {
                const product = {};
                const fallbackId = ($(this).attr("data-product-id") || ("prod_" + Math.random().toString(36).substring(2, 8))).trim();
                let skuValue = $(this).find(".griffinforms-payment-product-sku").val().trim();

                if (!skuValue) {
                    skuValue = fallbackId;
                }
                if (seenSkus[skuValue]) {
                    skuValue = skuValue + "_" + Math.random().toString(36).substring(2, 5);
                }
                seenSkus[skuValue] = true;

                product["id"] = skuValue;
                product["name"] = $(this).find(".griffinforms-payment-product-name").val().trim();
                product["price"] = parseFloat($(this).find(".griffinforms-payment-product-price").val()) || 0;
                product["description"] = $(this).find(".griffinforms-payment-product-description").val().trim();
                product["image"] = $(this).find(".griffinforms-payment-product-image").val().trim();
                const linkInput = $(this).find(".griffinforms-payment-product-link");
                product["link"] = linkInput.val().trim();
                const defaultQtyInput = $(this).find(".griffinforms-payment-product-default-qty");
                const minQtyInput = $(this).find(".griffinforms-payment-product-min-qty");
                const maxQtyInput = $(this).find(".griffinforms-payment-product-max-qty");

                const parsedDefault = parsePositiveIntField(defaultQtyInput, 1);
                const parsedMin = parsePositiveIntField(minQtyInput, 1);
                const parsedMax = parsePositiveIntField(maxQtyInput, parsedMin);

                product["default_qty"] = parsedDefault;
                product["min_qty"] = parsedMin;
                product["max_qty"] = parsedMax;
                product["allow_quantity"] = $(this).find(".griffinforms-payment-product-allow-qty").is(":checked") ? 1 : 0;
                product["featured"] = $(this).find(".griffinforms-payment-product-featured").is(":checked") ? 1 : 0;

                if (!product["name"]) {
                    showItemError("' . esc_js(__('Every product needs a name.', 'griffinforms-form-builder')) . '", "griffinforms-payment-products");
                }

                product["default_qty"] = Math.max(1, product["default_qty"]);
                product["min_qty"] = Math.max(1, product["min_qty"]);
                if (product["max_qty"] < product["min_qty"]) {
                    showItemError("' . esc_js(__('Max quantity cannot be less than min quantity.', 'griffinforms-form-builder')) . '", "griffinforms-payment-products");
                    maxQtyInput.addClass("border-danger");
                    hasInvalidQuantity = true;
                    product["max_qty"] = product["min_qty"];
                } else {
                    product["max_qty"] = Math.max(product["min_qty"], product["max_qty"]);
                    maxQtyInput.removeClass("border-danger");
                }
                if (product["default_qty"] < product["min_qty"]) {
                    showItemError("' . esc_js(__('Default quantity cannot be less than minimum quantity.', 'griffinforms-form-builder')) . '", "griffinforms-payment-products");
                    defaultQtyInput.addClass("border-danger");
                    hasInvalidQuantity = true;
                    product["default_qty"] = product["min_qty"];
                } else if (product["default_qty"] > product["max_qty"]) {
                    showItemError("' . esc_js(__('Default quantity cannot be greater than maximum quantity.', 'griffinforms-form-builder')) . '", "griffinforms-payment-products");
                    defaultQtyInput.addClass("border-danger");
                    hasInvalidQuantity = true;
                    product["default_qty"] = product["max_qty"];
                } else {
                    defaultQtyInput.removeClass("border-danger");
                }

                if (product["link"] && !isValidUrl(product["link"])) {
                    showItemError("' . esc_js(__('Please enter a valid product URL.', 'griffinforms-form-builder')) . '", "griffinforms-payment-products");
                    linkInput.addClass("border-danger");
                    hasInvalidQuantity = true;
                } else {
                    linkInput.removeClass("border-danger");
                }

                products.push(product);
            });

            if (hasInvalidQuantity) {
                return false;
            }

            if (!products.length) {
                showItemError("' . esc_js(__('Add at least one product to continue.', 'griffinforms-form-builder')) . '", "griffinforms-payment-products");
            }

            return products;
        }';
    }

    public function getIterations()
    {
        return 'function getIterations() {
            var fieldValue = {};
            if ($("#allow-multiple-iterations").is(":checked")) {
                fieldValue["allow"] = 1;
                fieldValue["min"] = $("#min-iterations-allowed").val();
                fieldValue["max"] = $("#max-iterations-allowed").val();
                fieldValue["unique"] = getToggleCheckBox("only-unique-values");
                fieldValue["add_button_label"] = $("#add-iteration-label").val();

                if (fieldValue["min"] < 0) {
                    showItemError("' . esc_js($this->lang->getText('invalid_min_iterations')) . '", "min-iterations-allowed");
                    $("#min-iterations-allowed").addClass("border-danger");
                    $("#min-iteration-suggestion").show();
                } else {
                    $("#min-iterations-allowed").removeClass("border-danger");
                }

                if (fieldValue["max"] < fieldValue["min"]) {
                    showItemError("' . esc_js($this->lang->getText('invalid_max_iterations')) . '", "max-iterations-allowed");
                    $("#max-iterations-allowed").addClass("border-danger");
                    $("#max-iteration-suggestion").show();
                } else {
                    $("#max-iterations-allowed").removeClass("border-danger");
                }
            } else {
                fieldValue["allow"] = 0;
            }

            return fieldValue;
        }';
    }

    public function getValidations()
    {
        $method = 'get' . esc_attr($this->data['field_type']) . 'Validations';
        return method_exists($this, $method) ? $this->$method() : '';
    }

    protected function getInputratingValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";

            var validationType = $("#griffinforms-inputratingvalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "min_rating") {
                var minRating = parseFloat($("#griffinforms-minrating-inputnumber").val());
                if (isNaN(minRating) || minRating < 1) {
                    showItemError("' . esc_js($this->lang->getText('min_rating_label')) . '", "griffinforms-minrating-inputnumber");
                }
                fieldValue["validation_value"] = minRating;
            }

            return fieldValue;
        }';
    }

    protected function getSelectFieldValidations()
    {
        return 'function getValidations() {
            return {};
        }';
    }

    protected function getInputRadioValidations()
    {
        return 'function getValidations() {
            return {};
        }';
    }

    protected function getSignatureValidations()
    {
        return 'function getValidations() {
            return {};
        }';
    }

    protected function getInputCheckboxValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            var validationType = $("#griffinforms-inputcheckboxvalidation-selectfield").val();
            fieldValue["type"] = validationType;
            var fieldOptions = Object.values(getFieldoptions()).reduce((count, group) => count + Object.keys(group).length, 0);

            if (validationType === "custom-parameters") {
                var minChecks = $("#griffinforms-minchecks-inputnumber").val();
                var maxChecks = $("#griffinforms-maxchecks-inputnumber").val();

                if (!isValidPositiveInteger(minChecks)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-minchecks-inputnumber");
                    minChecks = 0;
                }

                if (!isValidPositiveInteger(maxChecks)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-maxchecks-inputnumber");
                    maxChecks = 0;
                }

                minChecks = parseInt(minChecks);
                maxChecks = parseInt(maxChecks);

                // Validate min and max checks only if they have values
                if (maxChecks < minChecks) {
                    showItemError("' . esc_js($this->lang->getText('invalid_max_checks')) . '", "griffinforms-maxchecks-inputnumber");
                }

                if (minChecks > fieldOptions) {
                    showItemError("' . esc_js($this->lang->getText('min_more_than_options_count')) . '", "griffinforms-minchecks-inputnumber");
                }

                fieldValue["min_checks"] = minChecks;
                fieldValue["max_checks"] = maxChecks;
            }

            return fieldValue;
        }';
    }

    protected function getInputTimeValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";

            var validationType = $("#griffinforms-inputtimevalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "pattern") {
                const pattern = $("#griffinforms-validationpattern-inputtext").val();
                if (!pattern) {
                    showItemError("' . esc_js($this->lang->getText('empty_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                } else if (!isValidPattern(pattern)) {
                    showItemError("' . esc_js($this->lang->getText('invalid_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                }
                fieldValue["pattern"] = pattern;
            }

            if (validationType === "custom-parameters") {
                var minTime = $("#griffinforms-mintime-inputtime").val().trim();
                var maxTime = $("#griffinforms-maxtime-inputtime").val().trim();

                if (minTime) {
                    var minParts = minTime.match(/^(\d{1,2}):(\d{2})$/);
                    if (!minParts) {
                        showItemError("' . esc_js($this->lang->getText('invalid_time_format')) . '", "griffinforms-mintime-inputtime");
                    } else {
                        var minHours = parseInt(minParts[1], 10);
                        var minMinutes = parseInt(minParts[2], 10);
                        if (minHours < 0 || minHours > 23 || minMinutes < 0 || minMinutes > 59) {
                            showItemError("' . esc_js($this->lang->getText('invalid_time_format')) . '", "griffinforms-mintime-inputtime");
                        } else {
                            fieldValue["min"] = Date.UTC(1970, 0, 1, minHours, minMinutes, 0, 0) / 1000;
                        }
                    }
                }

                if (maxTime) {
                    var maxParts = maxTime.match(/^(\d{1,2}):(\d{2})$/);
                    if (!maxParts) {
                        showItemError("' . esc_js($this->lang->getText('invalid_time_format')) . '", "griffinforms-maxtime-inputtime");
                    } else {
                        var maxHours = parseInt(maxParts[1], 10);
                        var maxMinutes = parseInt(maxParts[2], 10);
                        if (maxHours < 0 || maxHours > 23 || maxMinutes < 0 || maxMinutes > 59) {
                            showItemError("' . esc_js($this->lang->getText('invalid_time_format')) . '", "griffinforms-maxtime-inputtime");
                        } else {
                            fieldValue["max"] = Date.UTC(1970, 0, 1, maxHours, maxMinutes, 0, 0) / 1000;
                        }
                    }
                }

                if (fieldValue["min"] && fieldValue["max"] && fieldValue["max"] < fieldValue["min"]) {
                    showItemError("' . esc_js($this->lang->getText('invalid_max_time')) . '", "griffinforms-maxtime-inputtime");
                }
            }

            if (validationType === "db-validate") {
                fieldValue["table"] = $("#griffinforms-tableselect-selectfield").val();
                fieldValue["column"] = $("#griffinforms-columnselect-selectfield").val();
                fieldValue["match_type"] = $("#griffinforms-dbmatchtype-selectfield").val();
            }

            return fieldValue;
        }';
    }

    protected function getInputDateValidations()
    {
        return '
        function getValidations() {
            // Error message constant for invalid positive integer validation
            const ERROR_POSITIVE_INTEGER = "' . esc_js($this->lang->getText('positive_integer_required')) . '";

            // Helper function to validate and return a positive integer or show an error
            function getPositiveInteger(value, errorSelector = "", errorMessage = ERROR_POSITIVE_INTEGER) {
                value = value.trim();
                if (!/^\d+$/.test(value)) {
                    if (errorSelector) {
                        showItemError(errorMessage, errorSelector);
                    }
                    return null;
                }
                return parseInt(value, 10);
            }

            // Initialize fieldValue with the field type
            var fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";

            // Determine selected validation type (none or custom parameters)
            var validationType = $("#griffinforms-inputdatevalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "custom-parameters") {
                // Handle fixed date validation: collects min and max date values
                if ($("#griffinforms-validationdatetype-selectfield").val() === "fixed_date") {
                    fieldValue["date_type"] = "fixed_date";

                    var minDate = $("#griffinforms-mindate-inputdate").datepicker("getDate");
                    var maxDate = $("#griffinforms-maxdate-inputdate").datepicker("getDate");

                    // Validate min and max dates only if both are set
                    if (minDate) {
                        fieldValue["min"] = Math.floor(minDate.getTime() / 1000);
                    }
                    if (maxDate) {
                        fieldValue["max"] = Math.floor(maxDate.getTime() / 1000);
                    }

                    // Show error if both dates are valid and minDate is later than maxDate
                    if (
                        minDate instanceof Date && !isNaN(minDate) &&
                        maxDate instanceof Date && !isNaN(maxDate) &&
                        minDate > maxDate
                    ) {
                        showItemError("' . esc_js($this->lang->getText('invalid_max_date')) . '", "griffinforms-maxdate-inputdate");
                    }
                }

                // Handle relative date validation: collects min and max relative date ranges
                if ($("#griffinforms-validationdatetype-selectfield").val() === "relative_date") {
                    fieldValue["date_type"] = "relative_date";

                    var relativeMin = {
                        days: getPositiveInteger($("#griffinforms-field-relative_min-days").val(), "griffinforms-field-relative_min-days"),
                        weeks: getPositiveInteger($("#griffinforms-field-relative_min-weeks").val(), "griffinforms-field-relative_min-weeks"),
                        months: getPositiveInteger($("#griffinforms-field-relative_min-months").val(), "griffinforms-field-relative_min-months"),
                        years: getPositiveInteger($("#griffinforms-field-relative_min-years").val(), "griffinforms-field-relative_min-years"),
                        date_logic: $("#griffinforms-relativeminlogic-selectfield").val(),
                        date_variable: $("#griffinforms-relativemindatevariable-selectfield").val()
                    };

                    var relativeMax = {
                        days: getPositiveInteger($("#griffinforms-field-relative_max-days").val(), "griffinforms-field-relative_max-days"),
                        weeks: getPositiveInteger($("#griffinforms-field-relative_max-weeks").val(), "griffinforms-field-relative_max-weeks"),
                        months: getPositiveInteger($("#griffinforms-field-relative_max-months").val(), "griffinforms-field-relative_max-months"),
                        years: getPositiveInteger($("#griffinforms-field-relative_max-years").val(), "griffinforms-field-relative_max-years"),
                        date_logic: $("#griffinforms-relativemaxlogic-selectfield").val(),
                        date_variable: $("#griffinforms-relativemaxdatevariable-selectfield").val()
                    };

                    fieldValue["relative_min"] = relativeMin;
                    fieldValue["relative_max"] = relativeMax;
                }

                // Collect allowed day type restriction (e.g., weekdays, weekends)
                fieldValue["day_type"] = $("#griffinforms-validationdaytype-selectfield").val();
            }

            // Return the collected validation configuration
            return fieldValue;
        }';
    }

    protected function getInputUrlValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";

            var validationType = $("#griffinforms-inputurlvalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "pattern") {
                const pattern = $("#griffinforms-validationpattern-inputtext").val();
                if (!pattern) {
                    showItemError("' . esc_js($this->lang->getText('empty_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                } else if (!isValidPattern(pattern)) {
                    showItemError("' . esc_js($this->lang->getText('invalid_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                } else if (!isValidNumberPattern(pattern)) {
                    showItemError("' . esc_js($this->lang->getText('regex_not_suitable_for_numbers')) . '", "griffinforms-validationpattern-inputtext");
                }
                fieldValue["pattern"] = pattern;
            }

            if (validationType === "custom-parameters") {
                fieldValue["protocols"] = [];

                $("#griffinforms-allowprotocoltype-inputcheckbox").children("input").each(function() {
                    if ($(this).prop("checked")) {
                        fieldValue["protocols"].push($(this).val().toLowerCase());
                    }
                });

                // Normalize restricted and excluded TLDs: split on comma, space, or newline; trim, strip leading dot, and filter empty entries
                fieldValue["restricted_tld"] = $("#griffinforms-restrictedtldnames-textarea").val()
                    .split(/[\s,]+/)
                    .map(x => x.trim().replace(/^\./, ""))
                    .filter(x => x);
                fieldValue["excluded_tld"] = $("#griffinforms-excludedtldnames-textarea").val()
                    .split(/[\s,]+/)
                    .map(x => x.trim().replace(/^\./, ""))
                    .filter(x => x);

                // Validate TLD structure
                const tlds = [...fieldValue["restricted_tld"], ...fieldValue["excluded_tld"]];
                const tldPattern = /^[a-z0-9]+(?:\.[a-z0-9]+)*$/i;
                for (let tld of tlds) {
                    if (!tldPattern.test(tld)) {
                        showItemError("' . esc_js($this->lang->getText('invalid_tld_format_prefix')) . '" + "<b>" + tld + "</b>", "gf-custom-parameters-wrap");
                        return {};
                    }
                }

                // Check for overlap between restricted and excluded TLDs
                for (let tld of fieldValue["restricted_tld"]) {
                    if (fieldValue["excluded_tld"].includes(tld)) {
                        showItemError("' . esc_js($this->lang->getText('duplicate_tld_error_prefix')) . '" + "<b>" + tld + "</b>", "gf-custom-parameters-wrap");
                        return {};
                    }
                }
            }

            if (validationType === "db-validate") {
                fieldValue["table"] = $("#griffinforms-tableselect-selectfield").val();
                fieldValue["column"] = $("#griffinforms-columnselect-selectfield").val();
                fieldValue["match_type"] = $("#griffinforms-dbmatchtype-selectfield").val();
            }

            return fieldValue;
        }';
    }

    protected function getInputEmailValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";

            var validationType = $("#griffinforms-inputemailvalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "pattern") {
                const pattern = $("#griffinforms-validationpattern-inputtext").val();
                if (!pattern) {
                    showItemError("' . esc_js($this->lang->getText('empty_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                } else if (!isValidPattern(pattern)) {
                    showItemError("' . esc_js($this->lang->getText('invalid_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                }
                fieldValue["pattern"] = pattern;
            }

            if (validationType === "custom-parameters") {
                if ($("#griffinforms-restrictdomains-togglecheckbox").is(":checked")) {
                    fieldValue["is_restricted_domains"] = 1;
                    fieldValue["restricted_domains"] = $("#griffinforms-restricteddomainnames-textarea").val().split(",").map(x => x.trim()).filter(x => x !== "");
                } else {
                    fieldValue["is_restricted_domains"] = 0;
                    fieldValue["restricted_domains"] = [];
                }

                fieldValue["excluded_domains"] = $("#griffinforms-excludeddomainnames-textarea").val().split(",").map(x => x.trim()).filter(x => x !== "");

                if (!validateDomainLists(fieldValue["restricted_domains"], fieldValue["excluded_domains"])) {
                    return {};
                }
            }

            if (validationType === "db-validate") {
                fieldValue["table"] = $("#griffinforms-tableselect-selectfield").val();
                fieldValue["column"] = $("#griffinforms-columnselect-selectfield").val();
                fieldValue["match_type"] = $("#griffinforms-dbmatchtype-selectfield").val();
            }

            function validateDomainLists(restricted, excluded) {
                const all = [...restricted, ...excluded];
                for (let domain of all) {
                    if (!/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(domain)) {
                        showItemError("' . esc_js($this->lang->getText('invalid_domain_error_prefix')) . '" + "<b>" + domain + "</b>", "gf-custom-parameters-wrap");
                        return false;
                    }
                }

                for (let domain of restricted) {
                    if (excluded.includes(domain)) {
                        showItemError("' . esc_js($this->lang->getText('duplicate_domain_error_prefix')) . '" + "<b>" + domain + "</b>", "gf-custom-parameters-wrap");
                        return false;
                    }
                }

                return true;
            }

            return fieldValue;
        }';
    }

    protected function getInputPasswordValidations()
    {
        return 'function getValidations() {
            const fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";

            const validationType = $("#griffinforms-inputpasswordvalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "pattern") {
                const pattern = $("#griffinforms-validationpattern-inputtext").val();
                if (!pattern) {
                    showItemError("' . esc_js($this->lang->getText('empty_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                } else if (!isValidPattern(pattern)) {
                    showItemError("' . esc_js($this->lang->getText('invalid_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                }
                fieldValue["pattern"] = pattern;
                return fieldValue;
            }

            if (validationType !== "custom-parameters") {
                return fieldValue;
            }

            const messages = {};
            const messageSelectors = {
                "min": "#griffinforms-passwordmessagesmin-inputtext",
                "max": "#griffinforms-passwordmessagesmax-inputtext",
                "allowed_sets": "#griffinforms-passwordmessagesallowedsets-inputtext",
                "require_uppercase": "#griffinforms-passwordmessagesrequireuppercase-inputtext",
                "require_lowercase": "#griffinforms-passwordmessagesrequirelowercase-inputtext",
                "require_number": "#griffinforms-passwordmessagesrequirenumber-inputtext",
                "require_symbol": "#griffinforms-passwordmessagesrequiresymbol-inputtext",
                "disallowed_chars": "#griffinforms-passwordmessagesdisallowedchars-inputtext",
                "min_strength": "#griffinforms-passwordmessagesminstrength-inputtext"
            };

            Object.entries(messageSelectors).forEach(function(entry) {
                const key = entry[0];
                const selector = entry[1];
                messages[key] = $(selector).val().trim();
            });
            fieldValue["messages"] = messages;

            const minInput = $("#griffinforms-passwordminlength-inputnumber").val().trim();
            const maxInput = $("#griffinforms-passwordmaxlength-inputnumber").val().trim();

            fieldValue["min"] = "";
            fieldValue["max"] = "";

            if (minInput !== "") {
                if (!isValidPositiveInteger(minInput)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-passwordminlength-inputnumber");
                } else {
                    fieldValue["min"] = parseInt(minInput, 10);
                }
            }

            if (maxInput !== "") {
                if (!isValidPositiveInteger(maxInput)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-passwordmaxlength-inputnumber");
                } else {
                    fieldValue["max"] = parseInt(maxInput, 10);
                }
            }

            if (fieldValue["min"] !== "" && fieldValue["max"] !== "" && fieldValue["max"] < fieldValue["min"]) {
                showItemError("' . esc_js($this->lang->getText('password_min_greater_than_max_error')) . '", "griffinforms-passwordmaxlength-inputnumber");
            }

            const allowedSets = [];
            $("#griffinforms-password-allowedsets input:checked").each(function() {
                allowedSets.push($(this).val());
            });
            if (!allowedSets.length) {
                showItemError("' . esc_js($this->lang->getText('password_allowed_sets_required')) . '", "griffinforms-password-allowedsets");
            }
            fieldValue["allowed_sets"] = allowedSets;

            const requiredSets = [];
            $("#griffinforms-password-requiredsets input:checked").each(function() {
                requiredSets.push($(this).val());
            });
            const invalidRequired = requiredSets.filter(function(set) {
                return !allowedSets.includes(set);
            });
            if (invalidRequired.length) {
                showItemError("' . esc_js($this->lang->getText('password_required_sets_subset_error')) . '", "griffinforms-password-requiredsets");
            }
            fieldValue["required_sets"] = requiredSets;

            fieldValue["disallowed_chars"] = $("#griffinforms-passworddisallowedchars-inputtext").val();
            fieldValue["min_strength"] = $("#griffinforms-passwordminstrength-selectfield").val();

            return fieldValue;
        }';
    }

    protected function getInputPhoneValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";

            var validationType = $("#griffinforms-inputphonevalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "pattern") {
                const pattern = $("#griffinforms-validationpattern-inputtext").val();
                if (!pattern) {
                    showItemError("' . esc_js($this->lang->getText('empty_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                } else if (!isValidPattern(pattern)) {
                    showItemError("' . esc_js($this->lang->getText('invalid_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                }
                fieldValue["pattern"] = pattern;
            }

            if (validationType === "custom-parameters") {
                var minDigits = $("#griffinforms-mindigits-inputnumber").val().trim();
                var maxDigits = $("#griffinforms-maxdigits-inputnumber").val().trim();

                if (minDigits !== "" && !isValidPositiveInteger(minDigits)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-mindigits-inputnumber");
                    minDigits = "";
                }

                if (maxDigits !== "" && !isValidPositiveInteger(maxDigits)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-maxdigits-inputnumber");
                    maxDigits = "";
                }

                if (minDigits !== "") {
                    fieldValue["min_digits"] = parseInt(minDigits, 10);
                }

                if (maxDigits !== "") {
                    fieldValue["max_digits"] = parseInt(maxDigits, 10);
                }

                if (
                    fieldValue["min_digits"] !== undefined &&
                    fieldValue["max_digits"] !== undefined &&
                    fieldValue["max_digits"] < fieldValue["min_digits"]
                ) {
                    showItemError("' . esc_js($this->lang->getText('invalid_max_number')) . '", "griffinforms-maxdigits-inputnumber");
                }

                fieldValue["format_type"] = $("#griffinforms-phoneformattype-selectfield").val();
                fieldValue["allow_extension"] = $("#griffinforms-allowextension-togglecheckbox").is(":checked") ? 1 : 0;

                var countryCodesRaw = $("#griffinforms-allowedcountrycodes-inputtext").val().split(/[\s,]+/);
                var sanitizedCodes = [];
                var invalidCode = null;

                countryCodesRaw.forEach(function(code) {
                    var trimmed = code.trim();
                    if (!trimmed) {
                        return;
                    }
                    trimmed = trimmed.replace(/^\+/, "");
                    if (!isValidCountryCode(trimmed)) {
                        invalidCode = code.trim();
                    } else {
                        sanitizedCodes.push(trimmed);
                    }
                });

                if (invalidCode !== null) {
                    showItemError("' . esc_js($this->lang->getText('invalid_country_code_error_prefix')) . '" + "<b>" + invalidCode + "</b>", "griffinforms-allowedcountrycodes-inputtext");
                }

                var duplicateCode = hasDuplicates(sanitizedCodes);
                if (duplicateCode !== null) {
                    showItemError("' . esc_js($this->lang->getText('duplicate_country_code_error_prefix')) . '" + "<b>" + duplicateCode + "</b>", "griffinforms-allowedcountrycodes-inputtext");
                }

                fieldValue["allowed_country_codes"] = sanitizedCodes;
            }

            if (validationType === "db-validate") {
                fieldValue["table"] = $("#griffinforms-tableselect-selectfield").val();
                fieldValue["column"] = $("#griffinforms-columnselect-selectfield").val();
                fieldValue["match_type"] = $("#griffinforms-dbmatchtype-selectfield").val();
            }

            return fieldValue;
        }';
    }

    protected function getInputAddressValidations()
    {
        return 'function getValidations() {
            const fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";
            const validationType = $("#griffinforms-inputaddressvalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType !== "custom-parameters") {
                return fieldValue;
            }

            const modeSelect = $("#griffinforms-countryfiltermode-selectfield");
            const allowedTextarea = $("#griffinforms-addressallowedcountries-textarea");
            const excludedTextarea = $("#griffinforms-addressexcludedcountries-textarea");

            fieldValue["country_filter_mode"] = modeSelect.val();
            fieldValue["allowed_countries"] = [];
            fieldValue["excluded_countries"] = [];

            function parseCountryInput(source) {
                return source
                    .split(/[\s,]+/)
                    .map(code => code.trim().toUpperCase())
                    .filter(code => code.length === 2);
            }

            if (fieldValue["country_filter_mode"] === "limit_to_countries") {
                fieldValue["allowed_countries"] = parseCountryInput(allowedTextarea.val());

                if (!fieldValue["allowed_countries"].length) {
                    showItemError("' . esc_js($this->lang->getText('address_country_codes_required')) . '", "griffinforms-addressallowedcountries-textarea");
                }
            }

            if (fieldValue["country_filter_mode"] === "exclude_countries") {
                fieldValue["excluded_countries"] = parseCountryInput(excludedTextarea.val());

                if (!fieldValue["excluded_countries"].length) {
                    showItemError("' . esc_js($this->lang->getText('address_country_codes_required')) . '", "griffinforms-addressexcludedcountries-textarea");
                }
            }

            return fieldValue;
        }';
    }

    protected function getInputNumberValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            fieldValue["field_type"] = "' . esc_html($this->data['field_type']) . '";

            var validationType = $("#griffinforms-inputnumbervalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "pattern") {
                const pattern = $("#griffinforms-validationpattern-inputtext").val();
                if (!pattern) {
                    showItemError("' . esc_js($this->lang->getText('empty_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                } else if (!isValidPattern(pattern)) {
                    showItemError("' . esc_js($this->lang->getText('invalid_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                }
                fieldValue["pattern"] = pattern;
            }

            if (validationType === "custom-parameters") {
                fieldValue["min"] = parseFloat($("#griffinforms-minchars-inputnumber").val());
                fieldValue["max"] = parseFloat($("#griffinforms-maxchars-inputnumber").val());
                fieldValue["number_type"] = $("#griffinforms-allownumbertype-selectfield").val();

                if (fieldValue["max"] < fieldValue["min"]) {
                    showItemError("' . esc_html($this->lang->getText('invalid_max_number')) . '", "griffinforms-maxchars-inputnumber");
                }

                if (fieldValue["number_type"] === "any_number") {
                    fieldValue["allow_decimal"] = $("#griffinforms-allowdecimalvalue-togglecheckbox").is(":checked");
                }
            }

            if (validationType === "db-validate") {
                fieldValue["table"] = $("#griffinforms-tableselect-selectfield").val();
                fieldValue["column"] = $("#griffinforms-columnselect-selectfield").val();
                fieldValue["match_type"] = $("#griffinforms-dbmatchtype-selectfield").val();
            }

            if (validationType === "multiples_of") {
                fieldValue["multiples"] = $("#griffinforms-multiples-inputtext").val().split(",");
            }

            return fieldValue;
        }';
    }

    protected function getInputTextValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";

            var validationType = $("#griffinforms-inputtextvalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "pattern") {
                const pattern = $("#griffinforms-validationpattern-inputtext").val();
                if (!pattern) {
                    showItemError("' . esc_js($this->lang->getText('empty_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                } else if (!isValidPattern(pattern)) {
                    showItemError("' . esc_js($this->lang->getText('invalid_regex_pattern')) . '", "griffinforms-validationpattern-inputtext");
                }
                fieldValue["pattern"] = pattern;
            }

            if (validationType === "custom-parameters") {
                var min = $("#griffinforms-minchars-inputnumber").val();
                var max = $("#griffinforms-maxchars-inputnumber").val();

                if (!isValidPositiveInteger(min)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-minchars-inputnumber");
                    min = 0;
                }

                if (!isValidPositiveInteger(max)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-maxchars-inputnumber");
                    max = 0;
                }

                fieldValue["min"] = parseInt(min, 10);
                fieldValue["max"] = parseInt(max, 10);
                fieldValue["allow_numbers"] = $("#griffinforms-allownumbers-togglecheckbox").is(":checked");
                fieldValue["allow_spaces"] = $("#griffinforms-allowspaces-togglecheckbox").is(":checked");
                fieldValue["allow_splchars"] = $("#griffinforms-allowsplchars-togglecheckbox").is(":checked");
                fieldValue["exclude"] = $("#griffinforms-excludechars-inputtext").val();

                if (fieldValue["min"] < 0) {
                    showItemError("' . esc_js($this->lang->getText('invalid_min_number')) . '", "griffinforms-minchars-inputnumber");
                    $("#griffinforms-minchars-inputnumber").addClass("border-danger");
                } else {
                    $("#griffinforms-minchars-inputnumber").removeClass("border-danger");
                }

                if (fieldValue["max"] < fieldValue["min"]) {
                    showItemError("' . esc_js($this->lang->getText('invalid_max_number')) . '", "griffinforms-maxchars-inputnumber");
                    $("#griffinforms-maxchars-inputnumber").addClass("border-danger");
                } else {
                    $("#griffinforms-maxchars-inputnumber").removeClass("border-danger");
                }
            }

            if (validationType === "db-validate") {
                fieldValue["table"] = $("#griffinforms-tableselect-selectfield").val();
                fieldValue["column"] = $("#griffinforms-columnselect-selectfield").val();
                fieldValue["match_type"] = $("#griffinforms-dbmatchtype-selectfield").val();
            }

            return fieldValue;
        }';
    }

    protected function getTextAreaValidations()
    {
        return 'function getValidations() {
            var fieldValue = {};
            fieldValue["field_type"] = "' . esc_js($this->data['field_type']) . '";

            var validationType = $("#griffinforms-textareavalidation-selectfield").val();
            fieldValue["type"] = validationType;

            if (validationType === "custom-parameters") {
                var minChars = $("#griffinforms-minchars-inputnumber").val();
                var maxChars = $("#griffinforms-maxchars-inputnumber").val();

                if (!isValidPositiveInteger(minChars)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-minchars-inputnumber");
                    minChars = 0;
                }

                if (!isValidPositiveInteger(maxChars)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "griffinforms-maxchars-inputnumber");
                    maxChars = 0;
                }

                fieldValue["min_chars"] = parseInt(minChars, 10);
                fieldValue["max_chars"] = parseInt(maxChars, 10);

                if (fieldValue["max_chars"] < fieldValue["min_chars"]) {
                    showItemError("' . esc_js($this->lang->getText('invalid_max_number')) . '", "griffinforms-maxchars-inputnumber");
                }
            }

            return fieldValue;
        }';
    }

    protected function getFieldSettings()
    {
        $method = 'get' . sanitize_text_field($this->data['field_type']) . 'Settings';
        return method_exists($this, $method) ? $this->$method() : '';
    }

    protected function getInputAddressSettings()
    {
        return 'function getFieldsettings() {
            const labels = {
                line1: $("#griffinforms-addressline1label-inputtext").val().trim(),
                line2: $("#griffinforms-addressline2label-inputtext").val().trim(),
                city: $("#griffinforms-addresscitylabel-inputtext").val().trim(),
                state: $("#griffinforms-addressstatelabel-inputtext").val().trim(),
                postal: $("#griffinforms-addresspostallabel-inputtext").val().trim(),
                country: $("#griffinforms-addresscountrylabel-inputtext").val().trim()
            };

            return {
                labels: labels,
                enable_line2: getToggleCheckBox("griffinforms-addressline2enabled-togglecheckbox")
            };
        }';
    }

    protected function getInputTimeSettings()
    {
        return 'function getFieldsettings() {
            // No field settings for InputTime - HTML5 time input uses browser locale
            return {};
        }';
    }

    protected function getInputDateSettings()
    {
        return 'function getFieldsettings() {
            const fieldValue = {};
            fieldValue["date_format"] = $("#griffinforms-fieldsettingsdateformat-selectfield").val();
            return fieldValue;
        }';
    }

    protected function getInputPhoneSettings()
    {
        return 'function getFieldsettings() {
            const fieldValue = {};
            fieldValue["phone_display_mode"] = $("#griffinforms-fieldsettingsphonedisplaymode-selectfield").val();
            return fieldValue;
        }';
    }

    protected function getPaymentSettings()
    {
        return 'function getFieldsettings() {
            const settings = {};
            const parseLimitValue = function(selector) {
                const element = $(selector);
                if (!element.length) {
                    return 0;
                }
                const raw = parseInt(element.val(), 10);
                if (isNaN(raw) || raw < 0) {
                    element.val(0);
                    return 0;
                }
                return raw;
            };

            settings["layout"] = $("#griffinforms-layout-selectfield").val() || "cards";
            settings["allow_quantity_controls"] = getToggleCheckBox("griffinforms-allowquantitycontrols-togglecheckbox");
            settings["show_images"] = getToggleCheckBox("griffinforms-showimages-togglecheckbox");
            settings["show_descriptions"] = getToggleCheckBox("griffinforms-showdescriptions-togglecheckbox");
            settings["show_prices"] = getToggleCheckBox("griffinforms-showprices-togglecheckbox");
            settings["min_select"] = parseLimitValue("#griffinforms-minselect-inputnumber");
            settings["max_select"] = parseLimitValue("#griffinforms-maxselect-inputnumber");
            settings["tax_mode"] = $("#griffinforms-taxmode-selectfield").val() || "inherit";

            if (settings["tax_mode"] === "custom") {
                settings["tax_rate_type"] = $("#griffinforms-taxratetype-selectfield").val() || "percentage";
                const taxValueInput = $("#griffinforms-taxratevalue-inputnumber");
                let taxValue = parseFloat(taxValueInput.val());
                if (isNaN(taxValue) || taxValue < 0) {
                    showItemError("' . esc_js(__('Enter a valid tax value greater than or equal to zero.', 'griffinforms-form-builder')) . '", "griffinforms-taxratevalue-inputnumber");
                    taxValueInput.addClass("border-danger");
                    taxValue = 0;
                } else {
                    taxValueInput.removeClass("border-danger");
                }
                settings["tax_rate_value"] = taxValue;
                settings["tax_display_label"] = ($("#griffinforms-taxdisplaylabel-inputtext").val() || "Tax").trim() || "Tax";
                settings["tax_registration_label"] = ($("#griffinforms-taxregistrationlabel-inputtext").val() || "").trim();
                settings["tax_registration_number"] = ($("#griffinforms-taxregistrationnumber-inputtext").val() || "").trim();
            } else {
                settings["tax_rate_type"] = "";
                settings["tax_rate_value"] = "";
                settings["tax_display_label"] = "";
                settings["tax_registration_label"] = "";
                settings["tax_registration_number"] = "";
            }

            if (settings["max_select"] > 0 && settings["max_select"] < settings["min_select"]) {
                showItemError("' . esc_js(__('Maximum selected products cannot be lower than the minimum.', 'griffinforms-form-builder')) . '", "griffinforms-maxselect-inputnumber");
            }

            return settings;
        }';
    }

    protected function getInputPasswordSettings()
    {
        return 'function getFieldsettings() {
            const settings = {};
            const getTrimmedValue = function (selector) {
                const element = $(selector);
                if (!element.length) {
                    return "";
                }
                return $.trim(element.val());
            };

            const elementExists = function (selector) {
                return $(selector).length > 0;
            };

            settings["display_strength_meter"] = getToggleCheckBox("griffinforms-displaystrengthmeter-togglecheckbox");
            settings["show_password_toggle"] = getToggleCheckBox("griffinforms-showpasswordtoggle-togglecheckbox");
            settings["autocomplete_mode"] = getTrimmedValue("#griffinforms-autocompletemode-selectfield");
            settings["require_confirmation"] = getToggleCheckBox("griffinforms-requireconfirmation-togglecheckbox");
            settings["confirmation_label"] = getTrimmedValue("#griffinforms-confirmationlabel-inputtext");
            settings["confirmation_message"] = getTrimmedValue("#griffinforms-confirmationmessage-inputtext");
            if (settings["require_confirmation"]) {
                if (!settings["confirmation_label"]) {
                    if (elementExists("#griffinforms-confirmationlabel-inputtext")) {
                        showItemError("' . esc_js($this->lang->getText('password_confirmation_label_required')) . '", "griffinforms-confirmationlabel-inputtext");
                    }
                }
                if (!settings["confirmation_message"]) {
                    if (elementExists("#griffinforms-confirmationmessage-inputtext")) {
                        showItemError("' . esc_js($this->lang->getText('password_confirmation_message_required')) . '", "griffinforms-confirmationmessage-inputtext");
                    }
                }
            } else {
                settings["confirmation_label"] = "";
                settings["confirmation_message"] = "";
            }
            settings["encrypt_passwords"] = getToggleCheckBox("griffinforms-encryptpasswords-togglecheckbox");
            settings["encryption_key"] = getTrimmedValue("#griffinforms-encryptionkey-inputtext");
            if (settings["encrypt_passwords"] && !settings["encryption_key"]) {
                if (elementExists("#griffinforms-encryptionkey-inputtext")) {
                    showItemError("' . esc_js($this->lang->getText('password_encryption_key_required')) . '", "griffinforms-encryptionkey-inputtext");
                }
            }
            return settings;
        }';
    }

    protected function getFileUploadSettings()
    {
        $image_mimes = array_keys($this->choices->getChoices('image_mimes'));
        return '
        function getFieldsettings() {
            const imageMimes = ' . wp_json_encode($image_mimes) . ';
            const fieldValue = {};

            // --- Quick select MIME (dropdown) ---
            fieldValue["mime_quick_select"] = "all";
            fieldValue["mime_quick_select"] = $("[name=\"mime_quick_select\"]").val();

            // --- Allowed MIME presets (checkboxes) ---
            fieldValue["allowed_mimes"] = [];
            $("input[name=\"allowed_mimes[]\"]:checked").each(function(){
                const v = (this.value || "").toLowerCase().trim();
                if (v) fieldValue["allowed_mimes"].push(v);
            });

            // --- Custom mimes/extensions (CSV/space/semicolon/newlines) → store ONLY extensions ---
            (function(){
                const raw = $("#gf-fileupload-custom-mimes").val() || "";
                const tokens = raw
                    .split(/[\s,;]+/)
                    .map(s => String(s).trim().toLowerCase())
                    .filter(Boolean)
                    .map(s => {
                        // If token looks like a MIME (type/subtype), keep only the subtype (e.g., application/pdf → pdf)
                        const slash = s.indexOf(\'/\');
                        if (slash !== -1) {
                            s = s.slice(slash + 1);
                        }
                        // Drop leading dot from extensions (e.g., .pdf → pdf)
                        s = s.replace(/^\./, \'\');
                        return s;
                    })
                    .filter(Boolean);

                // De-duplicate while preserving order
                const seen = new Set();
                const exts = [];
                for (const t of tokens) {
                    if (!seen.has(t)) { seen.add(t); exts.push(t); }
                }
                fieldValue["custom_mimes"] = exts;
            })();

            // Determine whether image-specific constraints should apply
            function hasImageExt(list){
                if (!Array.isArray(list)) return false;
                return list.some(v => imageMimes.includes(String(v).toLowerCase()));
            }
            const qs = (fieldValue["mime_quick_select"] || \'\').toLowerCase();
            const isImageQuickSelect = [\'image\',\'images\',\'photos\',\'pictures\',\'image_only\'].includes(qs);
            const isImageMode = isImageQuickSelect || hasImageExt(fieldValue["allowed_mimes"]) || hasImageExt(fieldValue["custom_mimes"]);

            // Require at least one MIME (preset or custom)
            if ((!Array.isArray(fieldValue["allowed_mimes"]) || fieldValue["allowed_mimes"].length === 0) && (!Array.isArray(fieldValue["custom_mimes"]) || fieldValue["custom_mimes"].length === 0)) {
                showItemError("' . esc_js($this->lang->getText('at_least_one_mime_required', 'error_msg')) . '", "gf-fileupload-allowed-mimes");
            }

            // Accept ONLY clean numeric strings; reject mixed alpha-numeric (no silent coercion)
            function getFloatOrError(sel) {
                const raw = $(sel).val().trim();
                if (raw === "") return "";
                // allows: 10, 10.5 ; rejects: 10px, 1e3, +10, -10
                const re = /^(?:\d+)(?:\.\d+)?$/;
                if (!re.test(raw)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", sel.replace("#",""));
                    return "";
                }
                return parseFloat(raw);
            }
            function getIntOrError(sel) {
                const raw = $(sel).val().trim();
                if (raw === "") return "";
                // integers only; rejects 10px, 10.0, -1
                if (!/^\d+$/.test(raw)) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", sel.replace("#",""));
                    return "";
                }
                return parseInt(raw, 10);
            }

            // --- Size limits ---
            const perFileId = "#gf-fileupload-max-size-mb";
            const totalId   = "#gf-fileupload-total-size-mb";
            fieldValue["max_size_mb"]   = getFloatOrError(perFileId);
            fieldValue["total_size_mb"] = getFloatOrError(totalId);
            if (fieldValue["max_size_mb"] !== "" && fieldValue["max_size_mb"] < 0) {
                showItemError("' . esc_js($this->lang->getText('invalid_max_file_size', 'error_msg')) . '", perFileId.replace("#",""));
            }
            if (fieldValue["total_size_mb"] !== "" && fieldValue["total_size_mb"] < 0) {
                showItemError("' . esc_js($this->lang->getText('invalid_total_size_cap', 'error_msg')) . '", totalId.replace("#",""));
            }
            // Per-file size cannot exceed total size (when both are set)
            if (
                fieldValue["max_size_mb"] !== "" &&
                fieldValue["total_size_mb"] !== "" &&
                Number(fieldValue["max_size_mb"]) > Number(fieldValue["total_size_mb"]) 
            ) {
                showItemError("' . esc_js($this->lang->getText('total_less_than_per_file', 'error_msg')) . '", totalId.replace("#",""));
            }

            // --- Image constraints ---
            if (isImageMode) {
                fieldValue["image_min_width"]   = getIntOrError("#gf-img-min-width");
                fieldValue["image_max_width"]   = getIntOrError("#gf-img-max-width");
                fieldValue["image_min_height"]  = getIntOrError("#gf-img-min-height");
                fieldValue["image_max_height"]  = getIntOrError("#gf-img-max-height");

                // Disallow 0; allow blank to mean "no constraint"
                if (fieldValue["image_min_width"] === 0)  { showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "gf-img-min-width");   fieldValue["image_min_width"] = ""; }
                if (fieldValue["image_max_width"] === 0)  { showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "gf-img-max-width");   fieldValue["image_max_width"] = ""; }
                if (fieldValue["image_min_height"] === 0) { showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "gf-img-min-height");  fieldValue["image_min_height"] = ""; }
                if (fieldValue["image_max_height"] === 0) { showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "gf-img-max-height");  fieldValue["image_max_height"] = ""; }

                const mpSel = "#gf-img-max-mp";
                const mpRaw = $(mpSel).val().trim();
                if (mpRaw === "") {
                    fieldValue["image_max_megapixels"] = "";
                } else {
                    const mp = parseFloat(mpRaw);
                    if (Number.isNaN(mp) || mp <= 0) {
                        showItemError("' . esc_js($this->lang->getText('invalid_megapixels', 'error_msg')) . '", mpSel.replace("#",""));
                        fieldValue["image_max_megapixels"] = "";
                    } else {
                        fieldValue["image_max_megapixels"] = mp;
                    }
                }

                if (fieldValue["image_min_width"] !== "" && fieldValue["image_max_width"] !== "" && fieldValue["image_max_width"] < fieldValue["image_min_width"]) {
                    showItemError("' . esc_js($this->lang->getText('invalid_max_width', 'error_msg')) . '", "gf-img-max-width");
                }
                if (fieldValue["image_min_height"] !== "" && fieldValue["image_max_height"] !== "" && fieldValue["image_max_height"] < fieldValue["image_min_height"]) {
                    showItemError("' . esc_js($this->lang->getText('invalid_max_height', 'error_msg')) . '", "gf-img-max-height");
                }

                fieldValue["image_aspect_mode"]   = ($("#gf-img-aspect-mode").val() || "free").toLowerCase();
                fieldValue["image_aspect_preset"] = $("#gf-img-aspect-preset").val() || "4:3";
                fieldValue["image_aspect_custom_w"] = getIntOrError("#gf-img-aspect-custom-w");
                fieldValue["image_aspect_custom_h"] = getIntOrError("#gf-img-aspect-custom-h");

                if (fieldValue["image_aspect_mode"] === "custom") {
                    if (!fieldValue["image_aspect_custom_w"] || !fieldValue["image_aspect_custom_h"]) {
                        showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "gf-img-aspect-custom-w");
                        showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "gf-img-aspect-custom-h");
                    }
                }

                if (fieldValue["image_aspect_mode"] !== "custom") {
                    fieldValue["image_aspect_custom_w"] = "";
                    fieldValue["image_aspect_custom_h"] = "";
                }

                fieldValue["image_auto_rotate_exif"] = $("#gf-img-auto-rotate").is(":checked") ? 1 : 0;
                fieldValue["image_strip_exif"]       = $("#gf-img-strip-exif").is(":checked") ? 1 : 0;
            } else {
                // Not in image mode: blank out image-only constraints to avoid hidden-field errors
                fieldValue["image_min_width"] = fieldValue["image_max_width"] = "";
                fieldValue["image_min_height"] = fieldValue["image_max_height"] = "";
                fieldValue["image_max_megapixels"] = "";
                fieldValue["image_aspect_mode"] = "free";
                fieldValue["image_aspect_preset"] = "4:3";
                fieldValue["image_aspect_custom_w"] = fieldValue["image_aspect_custom_h"] = "";
                fieldValue["image_auto_rotate_exif"] = 0;
                fieldValue["image_strip_exif"] = 0;
            }

            // --- Optional: max files & storage mode if present ---
            if ( $("#gf-fileupload-max-files").length ) {
                fieldValue["max_files"] = getIntOrError("#gf-fileupload-max-files");
                if (fieldValue["max_files"] !== "" && fieldValue["max_files"] < 1) {
                    showItemError("' . esc_js($this->lang->getText('positive_integer_required')) . '", "gf-fileupload-max-files");
                }
            }
            if ( $("#griffinforms-fieldsettingsstoragemode-selectfield").length ) {
                fieldValue["storage_mode"] = $("#griffinforms-fieldsettingsstoragemode-selectfield").val();
            }

            // --- Allow multiple select (HTML multiple attribute) ---
            if ($("#gf-fileupload-allow-multiple").length) {
                fieldValue["allow_multiple_select"] = $("#gf-fileupload-allow-multiple").is(":checked") ? 1 : 0;
            }

            return fieldValue;
        }';
    }

    protected function getTermsconditionsSettings()
    {
        $accept_default = esc_js($this->lang->getText('terms_accept_label', 'default'));
        $decline_default = esc_js($this->lang->getText('terms_decline_label', 'default'));

        return 'function getFieldsettings() {
            const fieldValue = {};
            const checkboxLabel = $("#griffinforms-termscheckboxlabel-inputtext").val().trim();
            const anchorText = $("#griffinforms-termsanchortext-inputtext").val().trim();
            const subtext = $("#griffinforms-termssubtext-textarea").val().trim();
            const linkType = $("#griffinforms-termslinktype-selectfield").val();
            const pageId = $("#griffinforms-termspageid-selectfield").val();
            const postId = $("#griffinforms-termspostid-selectfield").val();
            const openInModal = $("#griffinforms-termsopeninmodal-togglecheckbox").is(":checked") ? 1 : 0;
            const acceptLabel = $("#griffinforms-termsacceptlabel-inputtext").val().trim();
            const declineLabel = $("#griffinforms-termsdeclinelabel-inputtext").val().trim();

            if (!checkboxLabel) {
                showItemError("' . esc_js($this->lang->getText('terms_checkbox_label', 'required')) . '", "griffinforms-termscheckboxlabel-inputtext");
            }

            if (!anchorText) {
                showItemError("' . esc_js($this->lang->getText('terms_anchor_text', 'required')) . '", "griffinforms-termsanchortext-inputtext");
            }

            if (linkType === "post") {
                if (!postId || postId === "0") {
                    showItemError("' . esc_js($this->lang->getText('terms_link_target', 'required')) . '", "griffinforms-termspostid-selectfield");
                }
            } else {
                if (!pageId || pageId === "0") {
                    showItemError("' . esc_js($this->lang->getText('terms_link_target', 'required')) . '", "griffinforms-termspageid-selectfield");
                }
            }

            fieldValue["checkbox_label"] = checkboxLabel;
            fieldValue["anchor_text"] = anchorText;
            fieldValue["subtext"] = subtext;
            fieldValue["link_type"] = linkType;
            fieldValue["page_id"] = linkType === "page" ? parseInt(pageId || 0, 10) : 0;
            fieldValue["post_id"] = linkType === "post" ? parseInt(postId || 0, 10) : 0;
            fieldValue["open_in_modal"] = openInModal;
            fieldValue["accept_label"] = openInModal ? (acceptLabel || "' . $accept_default . '") : "";
            fieldValue["decline_label"] = openInModal ? (declineLabel || "' . $decline_default . '") : "";

            return fieldValue;
        }';
    }

    public function getFormstyle()
    {
        return 'function getFormstyle() {
            return $("#griffinforms-current-formstyle-name").attr("data-item-id");
        }';
    }
}
