<?php

namespace GriffinForms\Admin\Js\Local;

class Form extends \GriffinForms\Admin\Js\Local\Single
{
    public function getAutofill()
    {
        return 'function getAutofill() {
                return $("#griffinforms-autofill-togglecheckbox").is(":checked");
                }';
    }

    public function getCompliancemode()
    {
        return 'function getCompliancemode() {
                return $("#griffinforms-compliancemode-togglecheckbox").is(":checked");
                }';
    }

    public function getComplianceprofile()
    {
        return 'function getComplianceprofile() {
                return $("#griffinforms-complianceprofile-selectfield").val();
                }';
    }

    public function getComplianceflags()
    {
        return 'function getComplianceflags() {
                var fieldValue = {};
                var mode = $("#griffinforms-complianceflagmode-selectfield").val() || "inherit";
                var storeIp = $("#griffinforms-complianceflagstoreip-togglecheckbox").is(":checked");
                var storeUserAgent = $("#griffinforms-complianceflagstoreuseragent-togglecheckbox").is(":checked");
                var retentionDays = $("#griffinforms-complianceflagretentiondays-inputnumber").val();

                retentionDays = retentionDays !== undefined ? retentionDays.toString().trim() : "";
                if (retentionDays === "") {
                    retentionDays = 0;
                } else {
                    retentionDays = parseInt(retentionDays, 10);
                    if (isNaN(retentionDays) || retentionDays < 0) {
                        showItemError("' . esc_js($this->lang->getText('invalid_retention_days')) . '", "griffinforms-complianceflagretentiondays-inputnumber");
                        retentionDays = 0;
                    }
                }

                fieldValue["mode"] = mode;
                fieldValue["store_ip"] = storeIp ? 1 : 0;
                fieldValue["store_user_agent"] = storeUserAgent ? 1 : 0;
                fieldValue["retention_days"] = retentionDays;

                return fieldValue;
                }';
    }
    
    public function getLimitEntries()
    {
        return 'function getLimitentries() {
                    var fieldValue, toggle, limit, message;
                
                    $("#griffinforms-limitentriescount-inputnumber").removeClass("border-danger");
    
                    fieldValue = {};
                    toggle = $("#griffinforms-togglelimitentries-togglecheckbox").is(":checked");
                    fieldValue["toggle"] = toggle;
    
                    if (toggle) {
                        limit = $("#griffinforms-limitentriescount-inputnumber").val();
                        limit = limit.trim();
                        limit = parseFloat(limit);
    
                        if (!limit || isNaN(limit) || !Number.isInteger(limit) || limit < 1) {  // Ensures limit is a positive integer
                            showItemError("' . esc_js($this->lang->getText('invalid_limit')) . '", "griffinforms-limitentriescount-inputnumber");
                            fieldValue["limit"] = "";  // Ensures an invalid entry does not get stored
                        } else {
                            fieldValue["limit"] = limit;
                            message = $("#griffinforms-limitentriesmessage-textarea").val();
                            message = message.trim();
                            fieldValue["message"] = message;
                        }                
                    } else {
                        fieldValue["limit"] = "";
                        fieldValue["message"] = "";
                    }
                    return fieldValue;
                }';
    }

    public function getAvailabilityWindow()
    {
        return 'function getAvailabilitywindow() {
                    var fieldValue = {};
                    var toggle = $("#griffinforms-toggleavailabilitywindow-togglecheckbox").is(":checked");
                    fieldValue["toggle"] = toggle;

                    if (toggle) {
                        fieldValue["start_date"] = $("#griffinforms-availabilitywindowstartdate-inputdate").val() || "";
                        fieldValue["start_time"] = $("#griffinforms-availabilitywindowstarttime-inputtime").val() || "";
                        fieldValue["end_date"] = $("#griffinforms-availabilitywindowenddate-inputdate").val() || "";
                        fieldValue["end_time"] = $("#griffinforms-availabilitywindowendtime-inputtime").val() || "";
                        fieldValue["pre_message"] = $.trim($("#griffinforms-availabilitywindowpremessage-textarea").val() || "");
                        fieldValue["post_message"] = $.trim($("#griffinforms-availabilitywindowpostmessage-textarea").val() || "");
                    } else {
                        fieldValue["start_date"] = "";
                        fieldValue["start_time"] = "";
                        fieldValue["end_date"] = "";
                        fieldValue["end_time"] = "";
                        fieldValue["pre_message"] = "";
                        fieldValue["post_message"] = "";
                    }

                    return fieldValue;
                }';
    }

    public function getProgressBar()
    {
        return 'function getProgressbar() {
                    var fieldValue = {};
                    fieldValue["toggle"] = $("#griffinforms-progressbartoggle-togglecheckbox").is(":checked");
                    fieldValue["style"] = $("#griffinforms-progressbarstyle-selectfield").val() || "stepper";
                    fieldValue["show_page_headings"] = $("#griffinforms-progressbarshowpageheadings-togglecheckbox").is(":checked");
                    return fieldValue;
                }
                $(function () {
                    $("#griffinforms-progressbarstyle-wrap, #griffinforms-progressbarshowpageheadings-wrap").toggle($("#griffinforms-progressbartoggle-togglecheckbox").is(":checked"));
                });
                $(document).on("change", "#griffinforms-progressbartoggle-togglecheckbox", function () {
                    var isOn = $(this).is(":checked");
                    $("#griffinforms-progressbarstyle-wrap, #griffinforms-progressbarshowpageheadings-wrap").toggle(isOn);
                });
                ';
    }

    public function getLifetimeSubmissionCount()
    {
        return 'function getLifetimesubmissioncount() {
                    var $badge = $("#griffinforms-lifetimesubmissioncount-wrap [data-gf-lifetime-count]");
                    var rawValue = $badge.attr("data-gf-lifetime-count-value");
                    var count = rawValue !== undefined ? parseInt(rawValue, 10) : NaN;

                    if (isNaN(count)) {
                        var textValue = $badge.text() || "";
                        textValue = textValue.replace(/,/g, "").trim();
                        count = parseInt(textValue, 10);
                    }

                    if (isNaN(count)) {
                        count = 0;
                    }

                    return count;
                }';
    }
    
    public function getAccessLevel()
    {
        return 'function getAccesslevel() {
                var fieldValue, accessStatus, roleStatus;
                
                $("#griffinforms-selectuserroles-multiselect").removeClass("border-danger");
                
                fieldValue = {};
                
                accessStatus = $("input[name=toggle_public_access]:checked").val();
                
                if (accessStatus === "public_access") {
                    fieldValue["access"] = "public_access";
                    fieldValue["role_access"] = false;
                    fieldValue["roles"] = "";
                } else {
                    fieldValue["access"] = "registered_access";

                    roleStatus = $("#griffinforms-toggleroleaccess-togglecheckbox").is(":checked"); 
                    fieldValue["role_access"] = roleStatus;
                    
                    if (roleStatus) {
                        fieldValue["roles"] = $("#griffinforms-selectuserroles-multiselect").val();
                        
                        if (fieldValue["roles"] == "") {
                            $("#griffinforms-selectuserroles-multiselect").addClass("border-danger");
                            showItemError("' . esc_js($this->lang->getText('no_roles_selected')) . '");
                        }
                    } else {
                        fieldValue["roles"] = "";
                    }
                }
                
                return fieldValue;
        }';
    }

    public function getSubmissionEdit()
    {
        return 'function getSubmissionedit() {
                var fieldValue = {};
                var isEnabled = $("#griffinforms-togglesubmissionedit-togglecheckbox").is(":checked");

                fieldValue["toggle"] = isEnabled ? 1 : 0;

                if (!isEnabled) {
                    fieldValue["original_submitters"] = 0;
                    fieldValue["email_owners"] = 0;
                    fieldValue["role_access"] = 0;
                    fieldValue["user_access"] = 0;
                    fieldValue["email_fields"] = [];
                    fieldValue["roles"] = [];
                    fieldValue["users"] = [];
                    fieldValue["max_edits"] = 0;
                    return fieldValue;
                }

                fieldValue["original_submitters"] = $("#griffinforms-submissioneditoriginalsubmitters-togglecheckbox").is(":checked") ? 1 : 0;
                fieldValue["email_owners"] = $("#griffinforms-submissioneditemailowners-togglecheckbox").is(":checked") ? 1 : 0;
                fieldValue["role_access"] = $("#griffinforms-submissioneditroleaccess-togglecheckbox").is(":checked") ? 1 : 0;
                fieldValue["user_access"] = $("#griffinforms-submissionedituseraccess-togglecheckbox").is(":checked") ? 1 : 0;

                if (!fieldValue["original_submitters"] && !fieldValue["email_owners"] && !fieldValue["role_access"] && !fieldValue["user_access"]) {
                    showItemError("' . esc_js(__('Choose at least one submission edit access mode.', 'griffinforms-form-builder')) . '");
                }

                fieldValue["email_fields"] = $("#griffinforms-submissioneditemailfields-multiselect").val() || [];
                fieldValue["roles"] = $("#griffinforms-submissioneditroles-multiselect").val() || [];

                var timeMode = $("#griffinforms-submissionedittimemode-selectfield").val() || "none";
                var timeValue = {
                    "mode": timeMode,
                    "start_date": "",
                    "start_time": "",
                    "end_date": "",
                    "end_time": "",
                    "duration_days": 0,
                    "duration_hours": 0,
                    "pre_message": "",
                    "post_message": ""
                };

                if (timeMode === "window") {
                    timeValue["start_date"] = $("#griffinforms-submissionedittimewindowstartdate-inputdate").val() || "";
                    timeValue["start_time"] = $("#griffinforms-submissionedittimewindowstarttime-inputtime").val() || "";
                    timeValue["end_date"] = $("#griffinforms-submissionedittimewindowenddate-inputdate").val() || "";
                    timeValue["end_time"] = $("#griffinforms-submissionedittimewindowendtime-inputtime").val() || "";
                    timeValue["pre_message"] = $.trim($("#griffinforms-submissionedittimewindowpremessage-textarea").val() || "");
                    timeValue["post_message"] = $.trim($("#griffinforms-submissionedittimewindowpostmessage-textarea").val() || "");
                } else if (timeMode === "duration") {
                    timeValue["duration_days"] = parseInt($.trim($("#griffinforms-submissionedittimedurationdays-inputnumber").val() || "0"), 10) || 0;
                    timeValue["duration_hours"] = parseInt($.trim($("#griffinforms-submissionedittimedurationhours-inputnumber").val() || "0"), 10) || 0;
                    timeValue["post_message"] = $.trim($("#griffinforms-submissionedittimedurationpostmessage-textarea").val() || "");
                }

                var users = [];
                $("#griffinforms-submissionedituser-pills [data-gf-user-id]").each(function() {
                    var userId = parseInt($(this).attr("data-gf-user-id"), 10);
                    if (userId > 0) {
                        users.push(userId);
                    }
                });
                fieldValue["users"] = users;
                fieldValue["time"] = timeValue;

                var maxEdits = $.trim($("#griffinforms-submissioneditmaxedits-inputnumber").val() || "");
                if (maxEdits === "") {
                    maxEdits = 0;
                } else {
                    maxEdits = parseInt(maxEdits, 10);
                    if (isNaN(maxEdits) || maxEdits < 0) {
                        showItemError("' . esc_js(__('Maximum edit count must be 0 or a positive number.', 'griffinforms-form-builder')) . '", "griffinforms-submissioneditmaxedits-inputnumber");
                        maxEdits = 0;
                    }
                }

                fieldValue["max_edits"] = maxEdits;
                return fieldValue;
        }';
    }
    
    public function getUserAction()
    {
        return 'function getUseraction() {
                var fieldValue = {};
                                            
                $("#griffinforms-successmessage-textarea").removeClass("border-danger");

                fieldValue["type"] = $("input[name=action_type]:checked").val();
                    
                if (fieldValue["type"] === "do_nothing") {
                    fieldValue["message"] = "";
                    fieldValue["url"] = "";
                }                    
                    
                if (fieldValue["type"] === "show_success_message") {
                    fieldValue["message"] = $.trim($("#griffinforms-successmessage-textarea").val());
                    fieldValue["url"] = "";
                        
                    if (fieldValue["message"] === "") {
                        $("#griffinforms-successmessage-textarea").addClass("border-danger");
                        showItemError("' . esc_js($this->lang->getText('empty_success_message')) . '");
                    }
                }                    
                    
                if (fieldValue["type"] === "redirect_user") {
                    fieldValue["url"] = $("#griffinforms-redirectionurl-inputurl").val();
                    fieldValue["message"] = "";
                        
                    if (!isValidUrl(fieldValue["url"])) {
                        showItemError("' . esc_js($this->lang->getText('invalid_redirection_url')) . '", "griffinforms-redirectionurl-inputurl");
                    }
                }
                    
                return fieldValue;
        }';
    }
    
    public function getAlertEmails()
    {
        return 'function getAlertemails() {
                var sendTo, fieldValue;
                
                fieldValue = {};
                                
                sendTo = $("input[name=entry_alerts_to]:checked").val();
                                    
                if (sendTo === "specific_emails") {
                    var validCount = 0;
                    var maxEmails = 5;

                    $(".gf-entryalert-row").each(function () {
                        var emailInput = $(this).find(".griffinforms-entryalertsemails-input");
                        var messageIdInput = $(this).find(".gf-entryalert-message-id");
                        var emailValue = $.trim(emailInput.val());
                        var messageId = parseInt(messageIdInput.val(), 10);

                        emailInput.removeClass("border-danger");

                        if (!emailValue) {
                            return;
                        }
                        
                        if (isValidEmail(emailValue) == false) {
                            showItemError("' . esc_js($this->lang->getText('invalid_email')) . '", "griffinforms-entryalertsemails-container");
                            emailInput.addClass("border-danger");
                            return;
                        }

                        if (!messageId || isNaN(messageId)) {
                            messageId = 0;
                        }

                        if (validCount < maxEmails) {
                            fieldValue[emailValue] = messageId;
                            validCount++;
                        }
                    });

                    if (validCount === 0) {
                        showItemError("' . esc_js($this->lang->getText('invalid_email')) . '", "griffinforms-entryalertsemails-container");
                        $(".griffinforms-entryalertsemails-input").each(function () {
                            if (!$.trim($(this).val())) {
                                $(this).addClass("border-danger");
                            }
                        });
                    }
                }
                
                return fieldValue;
        }';
    }
    
    public function getAutoresponder()
    {
        return 'function getAutoresponder() {
        // =======================================================
        // Collects autoresponder mapping data for form submission
        // - Checks if the autoresponder toggle is enabled.
        // - Extracts email field to message mappings from JSON.
        // - Converts the data to an array of objects in the format:
        //   [{ "email_field_id": "68", "message_id": "15" }, ...]
        // - Returns an empty string if toggle is off or data is invalid.
        // =======================================================
        var toggle = $("#griffinforms-toggleautoresponder-togglecheckbox").is(":checked");
        // Clear mapping field if toggle is off to avoid stale data submission
        if (!toggle) {
            $("#griffinforms-emailfield-mappings").val("");
            return "";
        }

        if (toggle) {
            var mappingJson = $("#griffinforms-emailfield-mappings").val();
            try {
                var parsed = JSON.parse(mappingJson);
                if (typeof parsed === "object" && parsed !== null && Object.keys(parsed).length > 0) {
                    var formattedArray = Object.keys(parsed).map(function(fieldId) {
                        var mapping = parsed[fieldId];
                        if (mapping && mapping.message_id) {
                            return { "email_field_id": fieldId, "message_id": mapping.message_id };
                        }
                    }).filter(Boolean);
                    return JSON.stringify(formattedArray);
                }
            } catch (e) {
                showItemError("' . esc_js($this->lang->getText('invalid_autoresponder_mapping')) . '", "griffinforms-map-autoresponder-button");
            }
        }
        return "";
    }';
    }
    
    public function getSaveEntries()
    {
        return 'function getSaveentries() {
                return $("#griffinforms-saveentries-selectfield").val();
        }';
    }
}
