<?php

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

final class FrontendUrls 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 '<div class="p-3 text-muted small">';
        echo esc_html__('Loading frontend URLs...', 'griffinforms-form-builder');
        echo '</div>';
    }

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

    private function refreshFrontendUrlsJs()
    {
        $nonce = wp_create_nonce('frontend_urls_widget');
        $placeholder = '<div class="p-3 text-muted small">' . esc_html__('Loading frontend URLs...', 'griffinforms-form-builder') . '</div>';

        echo '
        const refreshFrontendUrlsWidget = () => {
            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": "getFrontendUrlsWidgetContent",
                "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", () => {
            refreshFrontendUrlsWidget();
        });

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

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

        refreshFrontendUrlsWidget();
        ' . PHP_EOL;
    }

    public function getFrontendUrlsWidgetContent()
    {
        $this->checkRequest('frontend_urls_widget');

        $form_id = isset($_POST['form_id']) ? absint(wp_unslash($_POST['form_id'])) : 0;
        if (!$form_id) {
            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->getFrontendUrls();
        if (empty($urls)) {
            echo '<div class="gf-log-empty text-muted small p-3">';
            echo esc_html__('No frontend URLs recorded for this form yet.', 'griffinforms-form-builder');
            echo '</div>';
            wp_die();
        }

        echo '<div class="list-group small m-3">';
        foreach ($urls as $url) {
            echo '<a class="list-group-item list-group-item-action px-3 py-2 text-decoration-none" href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">';
            echo esc_html($url);
            echo '</a>';
        }
        echo '</div>';

        wp_die();
    }

    private function getFrontendUrls()
    {
        $stored = $this->form->frontend_url ?? '';
        if (is_array($stored)) {
            $urls = $stored;
        } else {
            $urls = [];
            if (is_string($stored) && $stored !== '') {
                $decoded = maybe_unserialize($stored);
                if (is_array($decoded)) {
                    $urls = $decoded;
                } else {
                    $json = json_decode($stored, true);
                    if (json_last_error() === JSON_ERROR_NONE && is_array($json)) {
                        $urls = $json;
                    } else {
                        $urls = array($stored);
                    }
                }
            }
        }

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

        return array_values(array_unique($urls));
    }

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