<?php

namespace GriffinForms\Admin\Html\Modals;

class AttachChild extends \GriffinForms\Admin\Html\Modals\Format
{   
    protected function headerText()
    {
        $text = $this->lang->getText('add_formpage');
        return $text;
    }
    
    protected function modalContent()
    {
        echo '<div class="row px-3">';
        echo '<div class="col text-center">';
        echo '<span id="' . esc_attr($this->id) . '-status" class="text-muted">';
        echo 'Updating Pages...';
        echo '</span></div>';
        echo '</div>';        
        echo '<div id="griffinforms-modal-items" class="row d-flex row-cols-4 px-3 gx-2 gy-2 justify-content-between">';
        echo '</div>';
        
    }
    
    public function modalJs()
    {
        $nonce = wp_create_nonce('attachchild_html');
        
        ob_start();
        ?>
        jQuery(document).ready(function($) {
            var attachChildModal = document.getElementById("<?php echo esc_attr($this->id); ?>");
            attachChildModal.addEventListener("show.bs.modal", function (event) {
                var button, formId, parentId, childType, data;
                button = event.relatedTarget;
                formId = $("#griffinforms-form-id").val();
                parentId = $(button).attr("data-item-id");
                childType = $(button).attr("data-child-type");
                
                $("#griffinforms-modal-items").empty();
                $("#<?php echo esc_attr($this->id); ?>-status").text("<?php echo esc_js($this->lang->getText('updating_items')); ?>");
                
                data = {
                    "action": "getAttachChildHtml",
                    "form_id": formId,
                    "parent_id": parentId,
                    "child_type": childType,
                    "nonce": "<?php echo esc_js($nonce); ?>"
                };
                $.post(ajaxurl, data, function(response) {
                    $("#griffinforms-modal-items").html(response);
                    $("#<?php echo esc_attr($this->id); ?>-status").text("<?php echo esc_js($this->lang->getText('items_updated')); ?>");
                });
            });
        });
        <?php
        $inline_js = ob_get_clean();
        
        wp_add_inline_script('griffinforms-global-js', $inline_js);
    }
}