<?php

namespace GriffinForms\Admin\Html\Modals;

/**
 * Modal for mapping autoresponder messages to email fields on the form.
 * Allows selecting specific messages for each email field.
 */
class MapEmailFields extends \GriffinForms\Admin\Html\Modals\Format
{   
    /**
     * Provides the modal header text.
     *
     * @return string Modal header text.
     */
    protected function headerText()
    {
        $text = $this->lang->getText('map_email_fields_header');
        return $text;
    }
    
    /**
     * Renders the modal content, including informational notice and table layout.
     */
    protected function modalContent()
    {
        echo '<div class="gf-notice gf-notice-info small mb-3">';
        echo esc_html__('Map specific autoresponder messages to each email field on your form. This lets you personalize messages for different recipients — a unique capability of GriffinForms.', 'griffinforms-form-builder');
        echo '</div>';
        $this->printTableLayout();
    }

    /**
     * Outputs the table structure used to map email fields to autoresponder messages.
     */
    protected function printTableLayout()
    {
        echo '<div class="gf-mapemailfields-scrollarea my-2" style="max-height: 320px; overflow-y: auto;">';
        echo '<table class="table m-0 small">';
        echo '<thead><tr>';
        echo '<th>' . esc_html($this->lang->getText('email_field_label')) . '</th>';
        echo '<th class="text-center">' . esc_html($this->lang->getText('map_to_label')) . '</th>';
        echo '<th class="text-end"></th>';
        echo '<th class="text-start">' . esc_html($this->lang->getText('message_label')) . '</th>';
        echo '</tr></thead>';
        echo '<tbody></tbody>';
        echo '</table>';
        echo '</div>';
    }
    
    /**
     * Renders the modal footer with a Done button.
     */
    protected function modalFooter()
    {   
        echo '<div class="modal-footer border-top-0 gap-2">';
        $this->ActionBtn('Done');
        echo '</div>';  
    }

    /**
     * Injects JavaScript to handle dynamic mapping of email fields to messages.
     * - Populates the table on modal show.
     * - Restores existing mappings if available.
     * - Provides button and selected message cell rendering.
     */
    public function modalJs()
    {
        $js = '
        const GRIFFINFORMS_SELECT_LABEL = "' . esc_js($this->lang->getText('select_message_label')) . '";
        const GRIFFINFORMS_CHANGE_LABEL = "' . esc_js($this->lang->getText('change_message_label')) . '";
        const GRIFFINFORMS_REMOVE_LABEL = "' . esc_js($this->lang->getText('remove_message_label')) . '";

        jQuery(document).ready(function($) {
            function truncate(text) {
                return text.length > 40 ? text.substring(0, 37) + "..." : text;
            }

            /**
             * Creates a remove button to clear the mapping for a specific field.
             * 
             * @param {Object} field - The field object.
             * @param {jQuery} selectButton - The corresponding select button to reset its label after removal.
             * @returns {jQuery} - The remove button element.
             */
            function createRemoveButton(field, selectButton) {
                return $("<button>").addClass("button small btn-sm ms-2")
                    .text(GRIFFINFORMS_REMOVE_LABEL)
                    .on("click", function() {
                        delete window.griffinformsEmailFieldMappings[field.id];
                        $("#griffinforms-emailfield-mappings").val(JSON.stringify(window.griffinformsEmailFieldMappings)).trigger("change");
                        // Clear the mapped message cell and remove the "Remove" button itself
                        $(this).closest("tr").find("td.gf-mapped-message-cell").html("");
                        // Reset button label to "Select" after removal
                        selectButton.text(GRIFFINFORMS_SELECT_LABEL);
                        $(this).remove();
                    });
            }

            function createMappingButton(field, mapping) {
                var label = mapping ? GRIFFINFORMS_CHANGE_LABEL : GRIFFINFORMS_SELECT_LABEL;
                var selectButton = $("<button>").addClass("button small btn-sm")
                    .text(label)
                    .attr("data-bs-dismiss", "modal")
                    .on("click", function() {
                        var targetModal = $("#griffinforms-selectmessage-modal");
                        targetModal.data("gf-trigger", "map_email_message")
                                   .data("gf-parentmodalid", "#' . esc_js($this->getId()) . '")
                                   .data("gf-email-field-id", field.id);
                        targetModal.modal("show");
                    });
                var container = $("<div>").append(selectButton);

                if (mapping) {
                    container.append(createRemoveButton(field, selectButton));
                }

                return container;
            }

            function getSelectedMessageCell(fieldId) {
                var parsedMappings = window.griffinformsEmailFieldMappings;

                if (Object.keys(parsedMappings).length === 0) {
                    var storedMappings = $("#griffinforms-emailfield-mappings").val();
                    if (storedMappings) {
                        try {
                            parsedMappings = JSON.parse(storedMappings);
                        } catch (e) {
                            console.error("Failed to parse stored mappings:", e);
                        }
                    }
                }

                var fieldMapping = parsedMappings[fieldId];
                if (fieldMapping) {
                    var content = "<span>" + truncate(fieldMapping.message_name) + "</span><br><span class=\'text-muted small\'>" + truncate(fieldMapping.message_heading) + "</span>";
                    return $("<td>").addClass("text-start gf-mapped-message-cell").html(content);
                }

                return $("<td>").addClass("text-start gf-mapped-message-cell").html("");
            }

            function restoreEmailFieldMappings() {
                // =======================================================
                // Restore existing mappings from hidden field to memory. Ensures previously saved mappings are not lost when remapping fields.
                // =======================================================
                window.griffinformsEmailFieldMappings = {};
                var storedMappings = $("#griffinforms-emailfield-mappings").val();
                if (storedMappings) {
                    try {
                        window.griffinformsEmailFieldMappings = JSON.parse(storedMappings);
                    } catch (e) {
                        console.error("Failed to parse stored mappings on modal open:", e);
                    }
                }
            }

            $("#griffinforms-mapemailfields-modal").on("show.bs.modal", function() {
                restoreEmailFieldMappings();
                var tbody = $(this).find(".gf-mapemailfields-scrollarea tbody");
                tbody.empty();
                if (!Array.isArray(window.griffinformsEmailFields)) return;

                window.griffinformsEmailFields.forEach(function(field) {
                    var row = $("<tr>");
                    var left = $("<td>").html("<span>" + truncate(field.heading) + "</span><br><span class=\'text-muted small\'>" + truncate(field.name) + "</span>");
                    var arrow = $("<td>").addClass("text-center text-muted align-middle fs-6").html("&rArr;");
                    var mapping = window.griffinformsEmailFieldMappings && window.griffinformsEmailFieldMappings[field.id];
                    var button = createMappingButton(field, mapping);
                    var right = $("<td>").addClass("text-start align-middle").append(button);
                    var selectedCell = getSelectedMessageCell(field.id);

                    row.append(left, arrow, right, selectedCell);
                    tbody.append(row);
                });
            });
        });';

        wp_add_inline_script('griffinforms-global-js', $js);
    }
}