<?php

namespace GriffinForms\Admin\Html\FormControls\Form;

class AutoResponder extends \GriffinForms\Admin\Html\FormControls\Form\Format
{   
    /**
     * Render the full autoresponder control including toggle, modals, and hidden storage field.
     */
    public function html()
    {
        echo '<div class="row">';
        echo '<div class="col-md-12 mb-3" id="griffinforms-toggleautoresponder-wrap">';
        $this->toggleAutoResponder();
        $this->printAutoresponderWarnings();
        echo '</div>';        
        echo '<div class="griffinforms-hidden-option col-md-12 mb-3" id="griffinforms-autoresponder-wrap">';
        $this->selectMessage();
        echo '</div>';
        echo '</div>';
        $this->printMappingStorageField();
    }
    
    /**
     * Render the toggle switch for enabling/disabling autoresponder functionality.
     */
    protected function toggleAutoResponder()
    {
        $value = 0;

        if (is_array($this->value) && !empty($this->value)) {
            $value = 1;
        } elseif (is_string($this->value) && !empty(trim($this->value))) {
            $value = 1;
        }

        $data = array('label' => $this->lang->getText('toggle_autoresponder_label'));
        $field = new \GriffinForms\Admin\Html\FormControls\ToggleCheckbox('toggle_autoresponder', $value, $data);
        $field->html();
    }
    
    /**
     * Render the button that opens the email field to message mapping modal.
     */
    protected function selectMessage()
    {
        $map_email_modal = $this->renderModals();
        $map_email_modal_id = '#' . $map_email_modal->getId();

        echo '<button type="button" class="button" id="griffinforms-map-autoresponder-button" data-bs-toggle="modal" data-bs-target="' . esc_attr($map_email_modal_id) . '">';
        echo esc_html($this->lang->getText('map_autoresponder_message'));
        echo '</button>';
    }

    /**
     * Render the modals for message selection and mapping.
     *
     * @return \GriffinForms\Admin\Html\Modals\MapEmailFields
     */
    protected function renderModals()
    {
        $create_message_modal = new \GriffinForms\Admin\Html\Modals\CreateMessage($this->lang);
        $create_message_modal->setCssClass('modal-lg');
        $create_message_modal->html();

        $map_email_modal = new \GriffinForms\Admin\Html\Modals\MapEmailFields($this->lang);
        $map_email_modal->setCssClass('modal-lg');
        $map_email_modal->html();

        $select_item_modal_data = array(
            'name' => 'message',
            'item_type' => 'message',
            'callback_id' => '#' . $map_email_modal->getId()
        );

        $select_item_modal = new \GriffinForms\Admin\Html\Modals\SelectItem($this->lang, $select_item_modal_data);
        $select_item_modal->setCssClass('modal-lg');
        $select_item_modal->html();

        return $map_email_modal;
    }

    /**
     * Render validation and network-related warning messages for the autoresponder section.
     */
    protected function printAutoresponderWarnings()
    {
        echo '<div id="griffinforms-autoresponder-nomsg" class="gf-text-danger small mt-1" style="display: none;">';
        echo esc_html($this->lang->getText('no_email_field_message'));
        echo '</div>';

        echo '<div id="griffinforms-autoresponder-networkerror" class="gf-text-danger small mt-1" style="display: none;">';
        echo esc_html($this->lang->getText('network_error_message'));
        echo '</div>';

        echo '<div id="griffinforms-autoresponder-verifying" class="text-muted small mt-1" style="display: none;">';
        echo esc_html($this->lang->getText('verifying_email_field_message'));
        echo '</div>';

        echo '<div class="d-flex align-items-center mt-1">';
        echo '<button type="button" class="button small" id="griffinforms-autoresponder-recheck" style="display: none;">' . esc_html__('Recheck for Email Field', 'griffinforms-form-builder') . '</button>';
        echo '<span class="spinner" id="griffinforms-autoresponder-spinner" style="float: none; display: none;"></span>';
        echo '</div>';
    }

    /**
     * Output a hidden field to store autoresponder mapping JSON for form submission.
     */
    protected function printMappingStorageField()
    {
        echo '<input type="hidden" id="griffinforms-emailfield-mappings" name="griffinforms_emailfield_mappings" value="' . esc_attr($this->getMappingStorageValue()) . '">';
    }

    /**
     * Return a JSON-encoded version of $this->value for mapping storage.
     * Converts stored array format to modal-friendly keyed object format.
     */
    protected function getMappingStorageValue()
    {
        if (is_array($this->value)) {
            $formatted = array();
            foreach ($this->value as $mapping) {
                if (isset($mapping['email_field_id'], $mapping['message_id'])) {
                    $email_field_id = absint($mapping['email_field_id']);
                    $message_id = absint($mapping['message_id']);

                    if ($email_field_id > 0 && $message_id > 0) {
                        $message = $this->sql->itemValues($message_id, 'message', ['name', 'heading']);
                        $field = $this->sql->itemExists('field', $email_field_id);

                        // Skip if message does not exist
                        if ($message && $field) {
                            $message_name = !empty($message->name) ? $message->name : 'Message ID ' . $message_id;
                            $formatted[$email_field_id] = array(
                                'message_id' => (string) $message_id,
                                'message_name' => $message_name,
                                'message_heading' => $message->heading ?? ''
                            );
                        }
                    }
                }
            }
            $formatted_json = !empty($formatted) ? json_encode($formatted) : '{}';
            return esc_attr($formatted_json);
        }
        return '';
    }

    /**
     * Inject JavaScript to handle AJAX-based validation of email fields,
     * and manage the state of the autoresponder toggle and mapping functionality.
     */
    public function fieldJs()
    {
        $form_id = (int) $_GET['id'];
        $nonce = wp_create_nonce('check_email_field');
        $js  = 'jQuery(document).ready(function($) {' . PHP_EOL;
        $js .= '    function griffinformsCheckEmailField() {' . PHP_EOL;
        $js .= '        var toggle = $("#griffinforms-toggleautoresponder-togglecheckbox");' . PHP_EOL;
        $js .= '        var msg = $("#griffinforms-autoresponder-nomsg");' . PHP_EOL;
        $js .= '        var neterror = $("#griffinforms-autoresponder-networkerror");' . PHP_EOL;
        $js .= '        var verifying = $("#griffinforms-autoresponder-verifying");' . PHP_EOL;
        $js .= '        var spinner = $("#griffinforms-autoresponder-spinner");' . PHP_EOL;
        $js .= '        var recheck = $("#griffinforms-autoresponder-recheck");' . PHP_EOL;
        $js .= '        recheck.prop("disabled", true);' . PHP_EOL;
        $js .= '        toggle.prop("disabled", true);' . PHP_EOL;
        $js .= '        msg.hide(); neterror.hide(); verifying.show(); spinner.show();' . PHP_EOL;
        $js .= '        $.ajax({' . PHP_EOL;
        $js .= '            url: ajaxurl,' . PHP_EOL;
        $js .= '            method: "POST",' . PHP_EOL;
        $js .= '            dataType: "json",' . PHP_EOL;
        $js .= '            data: {' . PHP_EOL;
        $js .= '                action: "checkEmailField",' . PHP_EOL;
        $js .= '                form_id: ' . absint($form_id) . ',' . PHP_EOL;
        $js .= '                nonce: "' . esc_js($nonce) . '"' . PHP_EOL;
        $js .= '            },' . PHP_EOL;
        $js .= '            success: function(response) {;' . PHP_EOL;
        $js .= '                if (!response.success || !Array.isArray(response.email_fields) || response.email_fields.length === 0) {' . PHP_EOL;
        $js .= '                    toggle.prop("checked", false); msg.show(); recheck.show();' . PHP_EOL;
        $js .= '                } else {' . PHP_EOL;
        $js .= '                    window.griffinformsEmailFields = response.email_fields;' . PHP_EOL;
        $js .= '                    toggle.prop("disabled", false); recheck.hide();' . PHP_EOL;
        $js .= '                }' . PHP_EOL;
        $js .= '                verifying.hide(); spinner.hide();' . PHP_EOL;
        $js .= '                recheck.prop("disabled", false);' . PHP_EOL;
        $js .= '            },' . PHP_EOL;
        $js .= '            error: function(xhr, status, error) {' . PHP_EOL;
        $js .= '                console.error("AJAX request failed:", status, error);' . PHP_EOL;
        $js .= '                neterror.show(); recheck.show();' . PHP_EOL;
        $js .= '                verifying.hide(); spinner.hide();' . PHP_EOL;
        $js .= '                recheck.prop("disabled", false);' . PHP_EOL;
        $js .= '            }' . PHP_EOL;
        $js .= '        });' . PHP_EOL;
        $js .= '    }' . PHP_EOL;
        $js .= '    griffinformsCheckEmailField();' . PHP_EOL;
        $js .= '    $(document).on("click", "#griffinforms-autoresponder-recheck", griffinformsCheckEmailField);' . PHP_EOL;
        // Save field mapping and trigger change event after updating the hidden mapping field
        $js .= '    window.saveEmailFieldMapping = function(serializedMappings) {' . PHP_EOL;
        $js .= '        $("#griffinforms-emailfield-mappings").val(serializedMappings).trigger("change");' . PHP_EOL;
        $js .= '    };' . PHP_EOL;
        $js .= '});';

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