<?php

namespace GriffinForms\Admin\Html\Modals;

class CreateMessage extends \GriffinForms\Admin\Html\Modals\Format
{
    protected $config;

    protected function headerText()
    {
        $text = $this->lang->getText('create_message');
        return $text;
    }

    protected function modalContent()
    {
        echo '<div class="container" id="griffinforms-modal-createmessage-wrap">';
        
        // Error message container (hidden by default)
        echo '<div id="griffinforms-createmessage-error" class="gf-notice gf-notice-danger" style="display: none;"></div>';
        
        $this->nameOption();
        $this->subjectOption(); // Add subject field
        $this->contentOption();
        echo '</div>';
    }

    protected function nameOption()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputText('message_name', '');
        echo '<div class="row my-5">';
        echo '<div class="col-md-3 text-end">';
        echo '<label class="me-4">' . esc_html($this->lang->getText('message_name_label')) . '</label>';
        echo '</div>';
        echo '<div class="col-md-9">';
        $field->html();
        echo '</div>';
        echo '</div>';
    }
    
    // New subjectOption method for message subject
    protected function subjectOption()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\InputText('message_subject', '');
        echo '<div class="row my-5">';
        echo '<div class="col-md-3 text-end">';
        echo '<label class="me-4">' . esc_html($this->lang->getText('message_subject_label')) . '</label>';
        echo '</div>';
        echo '<div class="col-md-9">';
        $field->html();
        echo '</div>';
        echo '</div>';
    }

    protected function contentOption()
    {
        $field = new \GriffinForms\Admin\Html\FormControls\RichText('message_content', '');
        echo '<div class="row my-5">';
        echo '<div class="col-md-3 text-end">';
        echo '<label class="me-4">' . esc_html($this->lang->getText('message_content_label')) . '</label>';
        echo '</div>';
        echo '<div class="col-md-9">';
        $field->html();
        echo '</div>';
        echo '</div>';
    }

    protected function actionBtn($text = 'save', $btn_class = 'primary')
    {
        $id = 'griffinforms-modalaction-' . strtolower($this->meta);
        $wp_class = $btn_class === 'primary' ? 'button button-primary' : 'button';
        echo '<button type="button" id="' . esc_attr($id) . '" class="' . esc_attr($wp_class) . '">';
        echo esc_html($this->lang->getText($text));
        echo '</button>';
    }

    public function modalJs()
    {
        $nonce = wp_create_nonce('create_item');
        
        ob_start();
        ?>
        jQuery(document).ready(function($) {
            
            $("#griffinforms-modalaction-createmessage").click(function() {
                var itemData, data;
                
                // Hide any previous error messages
                $("#griffinforms-createmessage-error").hide().text('');
                
                // Disable the button to prevent multiple submissions
                $(this).prop("disabled", true);
                
                // Trim the message name, subject, and get content
                itemData = {};
                itemData["name"] = $("#griffinforms-messagename-inputtext").val().trim();
                itemData["heading"] = $("#griffinforms-messagesubject-inputtext").val().trim(); // Get subject
                itemData["content"] = tinymce.get("griffinforms-messagecontent-richtext").getContent();
                
                // Validation
                if (!itemData["name"]) {
                    showErrorMessage("<?php esc_html_e('Please enter a message name.', 'griffinforms-form-builder'); ?>");
                    $(this).prop("disabled", false); // Re-enable the button
                    return;
                }
                
                if (!itemData["heading"]) {
                    showErrorMessage("<?php esc_html_e('Please enter a message subject.', 'griffinforms-form-builder'); ?>");
                    $(this).prop("disabled", false); // Re-enable the button
                    return;
                }
                
                if (!itemData["content"]) {
                    showErrorMessage("<?php esc_html_e('Please enter message content.', 'griffinforms-form-builder'); ?>");
                    $(this).prop("disabled", false); // Re-enable the button
                    return;
                }
                
                itemData = JSON.stringify(itemData);
                                    
                data = {
                    "action": "createItem",
                    "item_type": "message",
                    "item_data": itemData,
                    "nonce": "<?php echo esc_js($nonce); ?>"
                };
                
                $.post(ajaxurl, data, function(response) {
                    if (typeof response !== 'object') {
                        try {
                            response = JSON.parse(response);
                        } catch (e) {
                            showErrorMessage("<?php echo esc_html($this->lang->getText('network_error_message')); ?>");
                            $("#griffinforms-modalaction-createmessage").prop("disabled", false);
                            return;
                        }
                    }

                    if (response.success) {
                        resetCreateMessageModal();                            
                        $("#griffinforms-createmessage-modal").modal('hide');
                        $("#griffinforms-selectmessage-modal").data('triggeredFrom', 'newItem').modal('show');
                    } else {
                        let msg = response.msg || "<?php esc_html_e('Error creating message.', 'griffinforms-form-builder'); ?>";
                        showErrorMessage(msg);
                    }

                    $("#griffinforms-modalaction-createmessage").prop("disabled", false);
                }).fail(function() {
                    showErrorMessage("<?php esc_html_e('Error processing request.', 'griffinforms-form-builder'); ?>");
                    $("#griffinforms-modalaction-createmessage").prop("disabled", false);
                });
            });
    
            // Function to reset the modal fields
            function resetCreateMessageModal() {
                $("#griffinforms-messagename-inputtext").val('');
                $("#griffinforms-messagesubject-inputtext").val(''); // Reset subject field
                tinymce.get("griffinforms-messagecontent-richtext").setContent('');
            }
    
            // Function to show error messages inside the modal
            function showErrorMessage(message) {
                $("#griffinforms-createmessage-error").text(message).show();
            }
            
        });
        <?php
        $inline_js = ob_get_clean();
    
        wp_add_inline_script('griffinforms-global-js', $inline_js);
    }
}