<?php

namespace GriffinForms\Admin\App\Html\Modals\FormThemes;

trait Requests
{
    /**
     * Outputs all AJAX request functions for the FormThemes modal.
     */
    protected function getRequestsJs()
    {
        $this->getFormThemeCategoriesJs();
        $this->getFormThemesByCategoryJs();
        $this->getApplyFormThemeJs();
    }

    /**
     * Outputs JavaScript function to fetch FormTheme categories.
     */
    protected function getFormThemeCategoriesJs()
    {
        $nonce = wp_create_nonce('get_form_theme_categories');

        echo '
        function griffinformsGetFormThemeCategories() {
            const wrapper = $("#griffinforms-formthemes-categories-container");
            if (!wrapper.length) {
                return;
            }

            const data = {
                action: "getFormThemeCategories",
                nonce: "' . esc_js($nonce) . '",
                active_category: window.griffinformsActiveThemeCategory || ""
            };

            griffinformsToggleModalSpinner();

            jQuery.post(ajaxurl, data)
                .done(function(response) {
                    griffinformsToggleModalSpinner();
                    if (response && response.success && response.data) {
                        const categoriesHtml = response.data.categories_html || "";
                        if (categoriesHtml) {
                            wrapper.html(categoriesHtml);
                        } else {
                            wrapper.html("<p class=\"text-muted small text-center\">' . esc_js(__('No theme categories available.', 'griffinforms-form-builder')) . '</p>");
                        }

                        const resolvedCategory = response.data.active_category || "";
                        window.griffinformsActiveThemeCategory = resolvedCategory || null;

                        if (resolvedCategory) {
                            griffinformsResetThemePagination(resolvedCategory);
                            if (typeof formthemesContentScroller !== "undefined" && formthemesContentScroller.length) {
                                formthemesContentScroller.scrollTop(0);
                            }
                            griffinformsGetFormThemesByCategory(resolvedCategory, { offset: 0 });
                        } else {
                            griffinformsResetThemePagination(null);
                            formthemesContentWrapper.html("<p class=\"text-muted text-center p-4\">' . esc_js(__('No themes found in this category.', 'griffinforms-form-builder')) . '</p>");
                        }
                    } else {
                        const errorMsg = response && response.data && response.data.msg
                            ? response.data.msg
                            : "' . esc_js(__('Failed to load categories.', 'griffinforms-form-builder')) . '";
                        wrapper.html("<p class=\"text-muted small text-center\">" + errorMsg + "</p>");
                        griffinformsShowFormThemeError(errorMsg);
                        window.griffinformsThemePagination = null;
                    }
                })
                .fail(function(xhr, status, error) {
                    griffinformsToggleModalSpinner();
                    console.error("Error fetching categories:", status, error);
                    wrapper.html("<p class=\"text-muted small text-center\">' . esc_js(__('Error loading categories.', 'griffinforms-form-builder')) . '</p>");
                    griffinformsShowFormThemeError("' . esc_js(__('Error loading categories.', 'griffinforms-form-builder')) . '");
                    window.griffinformsThemePagination = null;
                });
        }
        ' . "\n";
    }

    protected function getFormThemesByCategoryJs()
    {
        $nonce = wp_create_nonce('get_form_themes_by_category');

        echo '
        function griffinformsGetFormThemesByCategory(category, options) {
            const wrapper = $("#griffinforms-formthemes-content-container");
            if (!wrapper.length) {
                return;
            }

            const settings = typeof options === "object" && options !== null ? options : {};
            const trimmedCategory = typeof category === "string" ? category.trim() : "";
            if (trimmedCategory === "") {
                return;
            }

            const currentState = griffinformsGetThemePagination();
            const isNewCategory = currentState.category !== trimmedCategory;
            const requestedOffset = settings.offset !== undefined
                ? Math.max(0, parseInt(settings.offset, 10) || 0)
                : (isNewCategory ? 0 : currentState.offset);
            const append = settings.append === true && requestedOffset > 0;

            if (isNewCategory || !append) {
                griffinformsResetThemePagination(trimmedCategory);
            }

            const state = griffinformsGetThemePagination();
            state.category = trimmedCategory;

            if (state.loading) {
                return;
            }

            if (append && !state.hasMore) {
                return;
            }

            const offset = append ? requestedOffset : 0;
            const limit = state.limit || themePageSize;
            const formId = griffinformsResolveActiveFormId();

            state.loading = true;

            if (append) {
                const grid = wrapper.find(".griffinforms-theme-grid");
                if (grid.length) {
                    grid.append(griffinformsRenderThemePlaceholderItems(limit));
                } else {
                    wrapper.html(griffinformsRenderThemePlaceholders(limit));
                }
            } else {
                wrapper.html(griffinformsRenderThemePlaceholders(limit));
                if (typeof formthemesContentScroller !== "undefined" && formthemesContentScroller.length) {
                    formthemesContentScroller.scrollTop(0);
                }
            }

            const data = {
                action: "getFormThemesByCategory",
                category: trimmedCategory,
                nonce: "' . esc_js($nonce) . '",
                form_id: formId || 0,
                offset: offset,
                limit: limit
            };

            griffinformsToggleModalSpinner();

            jQuery.post(ajaxurl, data)
                .done(function(response) {
                    griffinformsToggleModalSpinner();
                    const payload = response && response.data ? response.data : {};
                    const themesHtml = payload.themes_html || "";
                    const activeThemeId = payload.active_theme_id ? parseInt(payload.active_theme_id, 10) : 0;
                    const loadedCount = payload.loaded_count ? parseInt(payload.loaded_count, 10) : 0;
                    const hasMore = payload.has_more === true;
                    const message = payload.message || "";
                    const paginationState = griffinformsGetThemePagination();

                    griffinformsRemoveThemePlaceholders();
                    paginationState.loading = false;

                    if (response && response.success) {
                        if (offset === 0) {
                            if (themesHtml) {
                                wrapper.html(themesHtml);
                            } else {
                                const displayMessage = message || "' . esc_js(__('No themes found in this category.', 'griffinforms-form-builder')) . '";
                                wrapper.html("<p class=\"text-muted text-center p-4\">" + displayMessage + "</p>");
                            }
                        } else if (themesHtml) {
                            // Append cards directly to the existing grid instead of wrapping in a new grid
                            const grid = wrapper.find(".griffinforms-theme-grid");
                            if (grid.length) {
                                grid.append(themesHtml);
                            } else {
                                // Fallback if grid not found
                                wrapper.append(themesHtml);
                            }
                        }

                        paginationState.offset = offset + loadedCount;
                        paginationState.hasMore = hasMore;
                        if (hasMore && loadedCount === 0) {
                            paginationState.hasMore = false;
                        }

                        if (!themesHtml && loadedCount === 0 && offset === 0 && message === "") {
                            wrapper.html("<p class=\"text-muted text-center p-4\">' . esc_js(__('No themes found in this category.', 'griffinforms-form-builder')) . '</p>");
                            paginationState.hasMore = false;
                        }

                        griffinformsSyncThemeButtons();

                        if (activeThemeId > 0) {
                            griffinformsMarkAppliedTheme(activeThemeId);
                        }

                        // Re-attach scroll handler after themes are loaded
                        const contentScroller = $("#griffinforms-formthemes-select-theme .griffinforms-formthemes-content");
                        if (contentScroller.length) {
                            const el = contentScroller.get(0);

                            contentScroller.off("scroll", griffinformsMaybeLoadMoreThemes);
                            contentScroller.on("scroll", function(e) {
                                griffinformsMaybeLoadMoreThemes();
                            });

                            // Check if we should immediately load more themes (content doesn\'t fill the viewport)
                            if (el.scrollHeight <= el.clientHeight && paginationState.hasMore && !paginationState.loading) {
                                setTimeout(function() {
                                    griffinformsMaybeLoadMoreThemes();
                                }, 100);
                            }
                        }
                    } else {
                        const errorMsg = (payload && payload.msg)
                            ? payload.msg
                            : "' . esc_js(__('Failed to load themes.', 'griffinforms-form-builder')) . '";
                        if (offset === 0) {
                            wrapper.html("<p class=\"text-muted text-center p-4\">" + errorMsg + "</p>");
                        }
                        paginationState.hasMore = false;
                        griffinformsShowFormThemeError(errorMsg);
                    }
                })
                .fail(function(xhr, status, error) {
                    griffinformsToggleModalSpinner();
                    griffinformsRemoveThemePlaceholders();
                    const paginationState = griffinformsGetThemePagination();
                    paginationState.loading = false;
                    console.error("Error fetching themes:", status, error);
                    if (offset === 0) {
                        wrapper.html("<p class=\"text-muted text-center p-4\">' . esc_js(__('Error loading themes.', 'griffinforms-form-builder')) . '</p>");
                    }
                    griffinformsShowFormThemeError("' . esc_js(__('Error loading themes.', 'griffinforms-form-builder')) . '");
                });
        }
        ' . "\n";
    }

    protected function getApplyFormThemeJs()
    {
        $nonce = wp_create_nonce('apply_form_theme');

        echo '
        function griffinformsApplyFormTheme(formId, themeId) {
            return jQuery.post(ajaxurl, {
                action: "applyFormTheme",
                form_id: formId,
                theme_id: themeId,
                nonce: "' . esc_js($nonce) . '"
            });
        }
        ' . "\n";
    }
}
