<?php

namespace GriffinForms\Admin\Js\Local;

class Message extends \GriffinForms\Admin\Js\Local\Single
{
    protected function localJs()
    {
        $js = parent::localJs();
        $js .= $this->mergeTokenBuilderJs() . PHP_EOL;
        return $js;
    }

    protected function getContent()
    {
        return 'function getContent(){
            let editorId = "griffinforms-content-richtext";
            fieldValue = wp.editor.getContent(editorId);
            return fieldValue;
        }';
    }

    protected function mergeTokenBuilderJs()
    {
        $nonce = wp_create_nonce('get_form_fields');

        $js = '
        function griffinformsMergeTokenInit() {
            var formSelect = $("#griffinforms-merge-form-context");
            var itemTypeSelect = $("#griffinforms-merge-item-type");
            var fieldSelect = $("#griffinforms-merge-field-select");
            var attrSelect = $("#griffinforms-merge-attr-select");
            var fallbackInput = $("#griffinforms-merge-fallback");
            var previewInput = $("#griffinforms-merge-token-preview");
            var insertBtn = $("#griffinforms-merge-token-insert");
            var fieldSpinner = $("#griffinforms-merge-field-spinner");
            var tokenSpinner = $("#griffinforms-merge-token-spinner");

            if (!formSelect.length) {
                return;
            }

            var formAttrs = [
                { value: "id", label: "' . esc_js($this->lang->getText('merge_attr_id_label')) . '" },
                { value: "name", label: "' . esc_js($this->lang->getText('merge_attr_name_label')) . '" },
                { value: "heading", label: "' . esc_js($this->lang->getText('merge_attr_heading_label')) . '" },
                { value: "description", label: "' . esc_js($this->lang->getText('merge_attr_description_label')) . '" }
            ];

            var fieldAttrs = [
                { value: "id", label: "' . esc_js($this->lang->getText('merge_attr_id_label')) . '" },
                { value: "name", label: "' . esc_js($this->lang->getText('merge_attr_name_label')) . '" },
                { value: "label", label: "' . esc_js($this->lang->getText('merge_attr_label_label')) . '" },
                { value: "value", label: "' . esc_js($this->lang->getText('merge_attr_value_label')) . '" },
                { value: "answer_count", label: "' . esc_js($this->lang->getText('merge_attr_answer_count_label')) . '" },
                { value: "description", label: "' . esc_js($this->lang->getText('merge_attr_helptext_label')) . '" }
            ];

            var submissionAttrs = [
                { value: "id", label: "' . esc_js($this->lang->getText('merge_attr_id_label')) . '" },
                { value: "position", label: "' . esc_js($this->lang->getText('merge_attr_position_label')) . '" },
                { value: "time", label: "' . esc_js($this->lang->getText('merge_attr_time_label')) . '" },
                { value: "data", label: "' . esc_js($this->lang->getText('merge_attr_data_label')) . '" },
                { value: "attachments_count", label: "' . esc_js($this->lang->getText('merge_attr_attachments_count_label')) . '" },
                { value: "attachments_size", label: "' . esc_js($this->lang->getText('merge_attr_attachments_size_label')) . '" },
                { value: "payment_total", label: "' . esc_js($this->lang->getText('merge_attr_payment_total_label')) . '" },
                { value: "payment_breakdown", label: "' . esc_js($this->lang->getText('merge_attr_payment_breakdown_label')) . '" },
                { value: "payment_status", label: "' . esc_js($this->lang->getText('merge_attr_payment_status_label')) . '" },
                { value: "edit_url", label: "' . esc_js($this->lang->getText('merge_attr_edit_url_label')) . '" }
            ];

            function populateAttrs(list, preferredValue) {
                attrSelect.empty();
                list.forEach(function(item) {
                    var option = $("<option>").val(item.value).text(item.label);
                    if (preferredValue && item.value === preferredValue) {
                        option.prop("selected", true);
                    }
                    attrSelect.append(option);
                });
            }

            function loadFields(formId) {
                fieldSelect.empty();
                fieldSelect.append($("<option>").val("").text("' . esc_js($this->lang->getText('select_field')) . '"));
                if (!formId) {
                    return;
                }

                fieldSpinner.css("visibility", "visible");
                tokenSpinner.css("visibility", "visible");
                insertBtn.prop("disabled", true);

                $.post(ajaxurl, {
                    action: "griffinforms_get_form_fields",
                    form_id: formId,
                    nonce: "' . esc_js($nonce) . '"
                }, function(response) {
                    if (typeof response !== "object") {
                        try {
                            response = JSON.parse(response);
                        } catch (e) {
                            return;
                        }
                    }
                    var fields = response.fields || (response.data && response.data.fields) || [];
                    if (!response || !response.success || !Array.isArray(fields)) {
                        return;
                    }
                    fields.forEach(function(field) {
                        var label = field.heading || field.name || ("Field " + field.id);
                        fieldSelect.append($("<option>").val(field.id).text(label));
                    });
                }).always(function() {
                    fieldSpinner.css("visibility", "hidden");
                    tokenSpinner.css("visibility", "hidden");
                    updatePreview();
                });
            }

            function toggleFieldSelect() {
                if (itemTypeSelect.val() === "form" || itemTypeSelect.val() === "submission") {
                    fieldSelect.prop("disabled", true);
                } else {
                    fieldSelect.prop("disabled", false);
                }
            }

            function toggleAttrSelect() {
                if (itemTypeSelect.val() === "form" || itemTypeSelect.val() === "submission") {
                    attrSelect.prop("disabled", false);
                    return;
                }
                var fieldId = parseInt(fieldSelect.val(), 10);
                attrSelect.prop("disabled", !(fieldId > 0));
            }

            function buildToken() {
                var itemType = itemTypeSelect.val();
                var attr = attrSelect.val();
                var fallback = $.trim(fallbackInput.val());
                var token = {
                    item_type: itemType,
                    attr: attr
                };

                if (itemType === "field") {
                    var fieldId = parseInt(fieldSelect.val(), 10);
                    if (fieldId > 0) {
                        token.item_id = fieldId;
                    }
                }

                if (fallback !== "") {
                    token.fallback = fallback;
                }

                return "{{json:" + JSON.stringify(token) + "}}";
            }

            function updatePreview() {
                previewInput.val(buildToken());
                toggleInsert();
                toggleAttrSelect();
            }

            function toggleInsert() {
                var itemType = itemTypeSelect.val();
                if (itemType === "form" || itemType === "submission") {
                    insertBtn.prop("disabled", !attrSelect.val());
                    return;
                }
                var fieldId = parseInt(fieldSelect.val(), 10);
                insertBtn.prop("disabled", !(fieldId > 0 && attrSelect.val()));
            }

            function insertToken() {
                var token = buildToken();
                var editorId = "griffinforms-content-richtext";
                if (window.wp && wp.editor && typeof wp.editor.insertContent === "function") {
                    wp.editor.insertContent(token);
                    return;
                }
                if (window.tinymce && tinymce.get(editorId)) {
                    tinymce.get(editorId).execCommand("mceInsertContent", false, token);
                    return;
                }
                var textarea = $("#" + editorId);
                if (textarea.length) {
                    var current = textarea.val();
                    textarea.val(current + token);
                }
            }

            formSelect.on("change", function() {
                loadFields($(this).val());
                updatePreview();
            });

            itemTypeSelect.on("change", function() {
                if ($(this).val() === "form") {
                    populateAttrs(formAttrs, "name");
                } else if ($(this).val() === "submission") {
                    populateAttrs(submissionAttrs, "id");
                } else {
                    populateAttrs(fieldAttrs, "value");
                }
                toggleFieldSelect();
                updatePreview();
            });

            fieldSelect.on("change", updatePreview);
            attrSelect.on("change", updatePreview);
            fallbackInput.on("input", updatePreview);
            insertBtn.on("click", insertToken);

            populateAttrs(fieldAttrs, "value");
            toggleFieldSelect();
            updatePreview();
        }

        griffinformsMergeTokenInit();
        ';

        return $js;
    }
}
