<?php

namespace GriffinForms\Admin\App\Html\Widgets\PresentationArea;

class FormsTable extends \GriffinForms\Admin\App\Html\Widgets\PresentationArea\Format
{

    public function getHtml()
    {
        echo '<div id="' . esc_attr($this->getHtmlId()) . '" data-gf-context="form-list">';
        echo '</div>';
    }

    public function getFormsTableContent()
    {
        if (empty($_POST['nonce'])) {
            $this->nonceError();
        }

        $nonce_status = wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'forms_table');
        
        if ($nonce_status === false) {
            $this->nonceError();
        }

        $forms = $this->sql->getItems('form');
        $this->formsTable($forms);
        wp_die();
    }

    protected function formsTable($forms)
    {
        $headings = array(
            __('ID', 'griffinforms-form-builder'),
            __('Name','griffinforms-form-builder'),
            __('Description','griffinforms-form-builder'),
        );

        echo '<table class="table table-hover table-borderless table-striped">';
        $this->tableHeader($headings);

        echo '<tbody>';
        foreach ($forms as $form) {
            echo '<tr data-gf-type="item" data-gf-item="form" data-gf-id="' . esc_attr($form->id) . '">';
            echo '<th scope="col">' . esc_html($form->id) . '</th>';
            echo '<td>' . esc_html($form->name) . '</td>';
            echo '<td>' . esc_html(substr($form->description, 0, 50)) . '</td>';
            echo '</tr>';
        }
        echo '</tbody>';
        echo '</table>';
    }

    public function getJs()
    {
        $this->getFormsTableJs();
        $this->makeTableRowsSelectable();
    }

    protected function getFormsTableJs()
    {
        $form_select_nonce = wp_create_nonce('forms_table');

        echo '
        document.addEventListener("form-list", () => {
                getFormsTableContent();
        });

        function getFormsTableContent() {
            const data = {
                "action": "getFormsTableContent",
                "nonce": "' . esc_js($form_select_nonce) . '"
            };

            $.post(ajaxurl, data, function(response) {
                $("#' . esc_attr($this->getHtmlId()) . '").html(response);
            });
        }';
    }

    private function makeTableRowsSelectable()
    {
        echo '
        let selectedForms = [];
        $("#' . esc_attr($this->getHtmlId()) . '").selectable({
            filter: "[data-gf-item=form]",
            appendTo: "#griffinforms-app-presentationarea",
            stop: function() {
                const formIds = [];
                $(".ui-selected", this).each(function() {
                  formIds.push($(this).attr("data-gf-id"));
                });
                if (formIds.length > 0) {
                    selectedForms = formIds;
                    document.dispatchEvent(formSelected);
                };
              },
            classes: {
                "ui-selected": "table-primary griffinforms-app-selectable-item"
              }
          });' . PHP_EOL;
    }

    public function __construct()
    {
        $this->setAll();
        add_action('wp_ajax_getFormsTableContent', array($this, 'getFormsTableContent'));
    }
}