<?php

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

final class FrontendUrlList extends \GriffinForms\Admin\App\Html\Widgets\RightSidebar\Format
{
    protected $form;

    public function getHtml()
    {
        $title = __('Frontend URLs', 'griffinforms-form-builder');
        $this->accordionHtml($title);
    }

    protected function accordionBody()
    {
        echo $this->getPlaceholderHtml();
    }

    public function widgetJs()
    {
        $this->refreshWidgetJs();
    }

    protected function refreshWidgetJs()
    {
        $nonce = wp_create_nonce('frontend_url_list_widget');
        $placeholder = $this->getPlaceholderHtml();

        echo '
        const refreshFrontendUrlListWidget = () => {
            const formElement = $("#griffinforms-app-presentationarea").find("[data-gf-itemtype=form]");
            const formId = formElement.attr("data-gf-itemid");
            if (!formId) {
                $("#' . esc_attr($this->getHtmlId()) . '").hide();
                return;
            }

            $("#' . esc_attr($this->getHtmlId()) . '").show();
            $("#' . esc_attr($this->getHtmlId('spinner')) . '").show();
            $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html(`' . addslashes($placeholder) . '`);

            const data = {
                "action": "getFrontendUrlListWidgetContent",
                "form_id": formId,
                "nonce": "' . esc_js($nonce) . '"
            };

            $.post(ajaxurl, data, function(response) {
                $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html(response);
                $("#' . esc_attr($this->getHtmlId('spinner')) . '").hide();
            }).fail(function() {
                $("#' . esc_attr($this->getHtmlId('content')) . '").find(".accordion-body").html("<div class=\"gf-notice gf-notice-danger\">' . esc_js(__('Failed to load frontend URLs. Please try again.', 'griffinforms-form-builder')) . '</div>");
                $("#' . esc_attr($this->getHtmlId('spinner')) . '").hide();
            });
        };

        document.addEventListener("gf-rightsidebar-formtab-activated", () => {
            refreshFrontendUrlListWidget();
        });

        document.addEventListener("form-updated", () => {
            refreshFrontendUrlListWidget();
        });

        document.addEventListener("form-html-received", () => {
            refreshFrontendUrlListWidget();
        });

        refreshFrontendUrlListWidget();
        ' . PHP_EOL;
    }

    public function getFrontendUrlListWidgetContent()
    {
        $this->checkRequest('frontend_url_list_widget');

        $form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;
        if ($form_id < 1) {
            echo '<div class="gf-notice gf-notice-danger">' . esc_html__('Invalid form ID.', 'griffinforms-form-builder') . '</div>';
            wp_die();
        }

        $this->form = $this->sql->itemValues($form_id, 'form');
        if (!$this->form) {
            echo '<div class="gf-notice gf-notice-danger">' . esc_html__('Form not found.', 'griffinforms-form-builder') . '</div>';
            wp_die();
        }

        $urls = $this->normalizeUrls($this->form->frontend_url ?? '');
        if (empty($urls)) {
            echo '<div class="p-3 text-muted small">' . esc_html__('No frontend URLs have been recorded yet.', 'griffinforms-form-builder') . '</div>';
            wp_die();
        }

        echo '<div class="p-3">';
        echo '<div class="small text-muted mb-2">' . esc_html__('Recorded frontend publication locations for this form.', 'griffinforms-form-builder') . '</div>';
        echo '<ul class="list-unstyled mb-0">';
        foreach ($urls as $url) {
            echo '<li class="mb-2">';
            echo '<a href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($url) . '</a>';
            echo '</li>';
        }
        echo '</ul>';
        echo '</div>';

        wp_die();
    }

    protected function getPlaceholderHtml()
    {
        ob_start();
        echo '<div class="p-3">';
        for ($i = 0; $i < 3; $i++) {
            echo '<div class="mb-2">';
            echo '<span class="placeholder col-10 bg-secondary"></span>';
            echo '</div>';
        }
        echo '</div>';
        return ob_get_clean();
    }

    protected function normalizeUrls($raw): array
    {
        if (is_array($raw)) {
            $urls = $raw;
        } elseif (is_string($raw) && $raw !== '') {
            $maybe = maybe_unserialize($raw);
            if (is_array($maybe)) {
                $urls = $maybe;
            } else {
                $decoded = json_decode($raw, true);
                $urls = is_array($decoded) ? $decoded : [];
            }
        } else {
            $urls = [];
        }

        $urls = array_values(array_filter(array_map(static function ($item) {
            return esc_url_raw(trim((string) $item));
        }, $urls)));

        return array_values(array_unique($urls));
    }
}
