/**
 * Wuclean Products JavaScript - Product-specific functionality
 * 
 * This file contains JavaScript functionality specific to the products cleanup page.
 */

jQuery(document).ready(function($) {

    function replaceIndexedPlaceholders(template, values) {
        return template.replace(/%(\d+)\$d/g, function(match, index) {
            var value = values[parseInt(index, 10) - 1];
            return typeof value !== "undefined" ? value : match;
        });
    }

    function productString(key, fallback) {
        if (typeof pt_wuclean_products_vars === "undefined") {
            return fallback;
        }
        return Object.prototype.hasOwnProperty.call(pt_wuclean_products_vars, key) ? pt_wuclean_products_vars[key] : fallback;
    }

    function updatePaginationCount(itemsDeleted) {
        if (!itemsDeleted) {
            return;
        }
        $(".pt-wuclean-pagination").each(function() {
            var $el = $(this);
            var template = $el.data("template");
            var start = parseInt($el.data("start"), 10) || 0;
            var end = parseInt($el.data("end"), 10) || 0;
            var total = parseInt($el.data("total"), 10) || 0;

            var newEnd = Math.max(start, end - itemsDeleted);
            var newTotal = Math.max(0, total - itemsDeleted);

            $el.data("end", newEnd);
            $el.data("total", newTotal);

            if (template) {
                $el.text(replaceIndexedPlaceholders(template, [start, newEnd, newTotal]));
            }
        });
    }

    // Product Issues Search - using consolidated utility function with batch processing
    initSearchProgress({
        startButtonId: "#pt-start-product-search",
        stopButtonId: "#pt-stop-product-search",
        progressDivId: "#pt-search-progress",
        progressBarId: "#pt-progress-bar",
        progressTextId: "#pt-progress-text",
        ajaxAction: "pt_wuclean_start_product_search",
        ajaxNonce: pt_wuclean_products_vars.product_search_nonce,
        successMessage: function(progress) {
            return productString('search_completed_product_issues', 'Search completed. Redirecting to Product Issues tab...');
        },
        redirectUrl: pt_wuclean_products_vars.product_issues_url,
        otherButtonSelectors: "#pt-start-orphaned-search, #pt-start-unused-attributes-search",
        useBatchProcessing: true  // Enable batch-by-batch processing for shared hosting compatibility
    });
    
    // Orphaned Data Search - using consolidated utility function with batch processing
    initSearchProgress({
        startButtonId: "#pt-start-orphaned-search",
        stopButtonId: "#pt-stop-orphaned-search",
        progressDivId: "#pt-orphaned-search-progress",
        progressBarId: "#pt-orphaned-progress-bar",
        progressTextId: "#pt-orphaned-progress-text",
        ajaxAction: "pt_wuclean_start_orphaned_search",
        ajaxNonce: pt_wuclean_products_vars.orphaned_search_nonce,
        successMessage: function(progress) {
            return productString('search_completed_orphaned', 'Search completed. Redirecting to Orphaned Data tab...');
        },
        redirectUrl: pt_wuclean_products_vars.orphaned_data_url,
        otherButtonSelectors: "#pt-start-product-search, #pt-start-unused-attributes-search",
        useBatchProcessing: true  // Enable batch-by-batch processing for shared hosting compatibility
    });
    
    // Unused Attributes Search - using consolidated utility function with batch processing
    initSearchProgress({
        startButtonId: "#pt-start-unused-attributes-search",
        stopButtonId: "#pt-stop-unused-attributes-search",
        progressDivId: "#pt-unused-attributes-search-progress",
        progressBarId: "#pt-unused-attributes-progress-bar",
        progressTextId: "#pt-unused-attributes-progress-text",
        ajaxAction: "pt_wuclean_start_unused_attributes_search",
        ajaxNonce: pt_wuclean_products_vars.unused_attributes_nonce,
        successMessage: function(progress) {
            return productString('search_completed_unused', 'Search completed. Redirecting to Unused Attributes tab...');
        },
        redirectUrl: pt_wuclean_products_vars.unused_attributes_url,
        otherButtonSelectors: "#pt-start-product-search, #pt-start-orphaned-search",
        useBatchProcessing: true  // Enable batch-by-batch processing for shared hosting compatibility
    });
    
    
    
    // Initialize bulk selection for all tabs
    initBulkSelection({
        selectAllId: "select-all-orphaned",
        checkboxesSelector: "input[name='select_orphaned[]']",
        selectedCountId: "orphaned-selected-count"
    });
    
    initBulkSelection({
        selectAllId: "select-all-products",
        checkboxesSelector: "input[name='select_products[]']",
        selectedCountId: "product-issues-selected-count"
    });
    
    initBulkSelection({
        selectAllId: "unused-attributes-select-all-checkbox",
        checkboxesSelector: ".unused-attribute-checkbox",
        selectedCountId: "unused-attributes-selected-count"
    });

    // Product issue recheck handler
    $(document).on("click", ".pt-wuclean-recheck-product", function() {
        var $button = $(this);
        var productId = $button.data("product-id");
        var $row = $button.closest("tr");
        var originalHtml = $button.html();
        var nonce = $("#pt_wuclean_recheck_product_nonce").val();
        var ajaxEndpoint = typeof window.ajaxurl !== "undefined" ? window.ajaxurl : "";

        if (!nonce || !ajaxEndpoint) {
            console.error("Recheck cannot proceed: missing nonce or AJAX URL.");
            return;
        }

        $button.prop("disabled", true).html("⏳ " + pt_wuclean_products_vars.recheck_checking_text);

        $.ajax({
            url: ajaxEndpoint,
            type: "POST",
            data: {
                action: "pt_wuclean_recheck_single_product",
                nonce: nonce,
                product_id: productId
            }
        }).done(function(response) {
            if (!response) {
                alert(pt_wuclean_products_vars.recheck_error_label + " " + pt_wuclean_products_vars.recheck_unknown_error);
                return;
            }

            if (response.success) {
                if (response.data && response.data.has_issues) {
                    var issues = response.data.issues || {};
                    $row.find("td:nth-child(3)").text(issues.missing_category ? "X" : "");
                    $row.find("td:nth-child(4)").text(issues.missing_type ? "X" : "");
                    $row.find("td:nth-child(5)").text(issues.missing_price ? "X" : "");
                    $row.find("td:nth-child(6)").text(issues.missing_image ? "X" : "");
                    $row.find("td:nth-child(7)").text(issues.missing_stock ? "X" : "");
                    $row.find("td:nth-child(8)").text(issues.missing_variants ? "X" : "");
                    $row.find("td:nth-child(9)").text(issues.missing_parent ? "X" : "");
                    $row.find("td:nth-child(10)").text(issues.missing_sku ? "X" : "");
                    $row.find("td:nth-child(11)").text(issues.missing_description ? "X" : "");

                    $button
                        .html("✓ " + pt_wuclean_products_vars.recheck_updated_text)
                        .css({ background: "#46b450", borderColor: "#46b450", color: "#fff" });

                    setTimeout(function() {
                        $button
                            .html(originalHtml)
                            .css({ background: "", borderColor: "", color: "" })
                            .prop("disabled", false);
                    }, 2000);
                } else {
                    $row.fadeOut(400, function() {
                        $(this).remove();
                        if ($("#product-issues-form tbody tr").length === 0) {
                            window.location.reload();
                        }
                    });
                }
            } else {
                var errorMessage = response.data;
                if (typeof errorMessage === "object" && errorMessage !== null) {
                    errorMessage = errorMessage.message || pt_wuclean_products_vars.recheck_unknown_error;
                }
                if (!errorMessage) {
                    errorMessage = pt_wuclean_products_vars.recheck_unknown_error;
                }
                alert(pt_wuclean_products_vars.recheck_error_label + " " + errorMessage);
                $button.prop("disabled", false).html(originalHtml);
            }
        }).fail(function(xhr, status, error) {
            console.error("Recheck AJAX failed", status, error, xhr);
            alert(pt_wuclean_products_vars.recheck_failed_generic);
            $button.prop("disabled", false).html(originalHtml);
        });
    });
});