<?php

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

final class ConditionalLogicBtn extends \GriffinForms\Admin\App\Html\Widgets\TitleBar\Format
{
    public function getHtml()
    {
        echo '<div class="position-relative me-2">';
        $this->getSvgIcon();
        echo '</div>';
    }

    private function getSvgIcon() {
        $path = $this->config->getRootUrl() . 'admin/images/icons/conditional_logic.svg';
        echo '<button type="button" class="griffinforms-logic-toggle-btn components-button has-icon p-1" aria-label="Toggle Conditional Logic" data-bs-toggle="modal" data-bs-target="#griffinforms-builder-modal-conditionallogic">';
        echo '<img src="' . $path . '">';
        $this->countBadge();
        echo '</button>';
    }

    private function countBadge()
    {
        $form = $this->utility->getForm();
        if ($form) {
            echo '<span id="griffinforms-app-rules-btn-badge-count" class="position-absolute top-10 start-100 translate-middle badge small rounded-pill bg-dark text-white">';
            echo $form->getRulesCount();
            echo '<span class="visually-hidden">unread messages</span></span>';
        }
    }

    public function getJs()
    {
        $this->updateRulesBadgeCountJs();
        $this->updateRulesBadgeCountEventJs();
    }

    /**
     * Prints JS function that requests the current rule count via AJAX
     * and updates the badge element (#griffinforms-app-rules-btn-badge-count).
     */
    protected function updateRulesBadgeCountJs()
    {
        $nonce = wp_create_nonce('update_rules_badge_count');

        echo '
        function updateRulesBadgeCount() {
            const badge = document.getElementById("griffinforms-app-rules-btn-badge-count");
            const formId = ' . (int) $this->utility->getFormId() . ';
            if (!badge || !formId) {
                return;
            }

            const data = {
                // Hook in Admin/Ajax/Form
                action: "griffinformsGetRulesCount",
                form_id: formId,
                nonce: "' . esc_js($nonce) . '"
            };

            jQuery.post(ajaxurl, data)
                .done(function(response) {
                    if (response && typeof response === "object" && response.success) {
                        const count = parseInt(response.data.count || 0, 10);
                        badge.textContent = count;
                        badge.classList.toggle("d-none", count === 0);
                    } else {
                        console.warn("Unexpected response while updating rules badge:", response);
                    }
                })
                .fail(function(xhr, status, error) {
                    console.error("Failed to update rules badge count:", status, error);
                });
        }
        ';
        $this->updateRulesBadgeCountEventJs();
    }

    protected function updateRulesBadgeCountEventJs()
    {
        echo '
        jQuery(document).on("griffinforms:rule-saved griffinforms:rule-deleted", function() {
            if (typeof updateRulesBadgeCount === "function") {
                updateRulesBadgeCount();
            }
        });
        ';
    }
}