/**
 * Wuclean Orders JavaScript - Order-specific functionality
 * 
 * This file contains JavaScript functionality specific to the orders cleanup page.
 */

jQuery(document).ready(function($) {
    function formatString(template) {
        var args = Array.prototype.slice.call(arguments, 1);
        return args.reduce(function(result, value) {
            return result.replace(/%[sd]/, value);
        }, template);
    }

    // Order Scan - using consolidated utility function with batch processing (matching products page style)
    if ($("#pt-start-order-scan").length > 0) {
        if (typeof initSearchProgress === 'function') {
            initSearchProgress({
                startButtonId: "#pt-start-order-scan",
                stopButtonId: "#pt-stop-order-scan",
                progressDivId: "#pt-order-scan-progress",
                progressBarId: "#pt-order-progress-bar",
                progressTextId: "#pt-order-progress-text",
                ajaxAction: "pt_wuclean_start_order_search",
                ajaxNonce: pt_wuclean_orders_vars.order_search_nonce,
                successMessage: function(progress) {
                    var newFlags = progress.flagged_count || 0;
                    var alreadyFlagged = progress.skipped_already_flagged || 0;
                    var storedFlags = progress.stored_flagged_count || 0;
                    if (newFlags > 0) {
                        return formatString(pt_wuclean_orders_vars.scan_completed_flagged, newFlags);
                    } else if (alreadyFlagged > 0) {
                        return formatString(pt_wuclean_orders_vars.scan_completed_already_flagged, alreadyFlagged);
                    } else if (storedFlags > 0) {
                        // No new flags but existing flagged orders exist - redirecting to show them
                        return pt_wuclean_orders_vars.scan_completed_no_new_redirecting || 'Scan completed! No new orders match the current flagging criteria. Redirecting to show existing flagged orders...';
                    } else {
                        return pt_wuclean_orders_vars.scan_completed_none;
                    }
                },
                redirectUrl: pt_wuclean_orders_vars.flagged_orders_url,
                otherButtonSelectors: "",
                useBatchProcessing: true  // Enable batch-by-batch processing for shared hosting compatibility
            });
        }
    }
    
    // Orphaned Meta Scan - using batch processing pattern like Products
    if ($("#pt-start-orphaned-meta-scan").length > 0) {
        if (typeof initSearchProgress === 'function') {
            initSearchProgress({
                startButtonId: "#pt-start-orphaned-meta-scan",
                stopButtonId: "#pt-stop-orphaned-meta-scan",
                progressDivId: "#pt-orphaned-meta-scan-progress",
                progressBarId: "#pt-orphaned-meta-progress-bar",
                progressTextId: "#pt-orphaned-meta-progress-text",
                ajaxAction: "pt_wuclean_start_orphaned_meta_scan",
                ajaxNonce: pt_wuclean_orders_vars.orphaned_meta_search_nonce,
                successMessage: function(progress) {
                    var orphanedCount = progress.total_found || 0;
                    if (orphanedCount > 0) {
                        return formatString(pt_wuclean_orders_vars.orphaned_scan_found, orphanedCount);
                    } else {
                        return pt_wuclean_orders_vars.orphaned_scan_none;
                    }
                },
                redirectUrl: pt_wuclean_orders_vars.orphaned_data_url,
                otherButtonSelectors: "#pt-start-order-scan",
                useBatchProcessing: true  // Match Products pattern for consistency
            });
        }
    }
    
    // Only initialize bulk selection if we're on the flagged orders tab
    // Check if we're on the flagged tab by looking for the bulk selection elements
    const isFlaggedTab = document.getElementById('ptac-master-toggle') !== null;
    
    if (isFlaggedTab) {
        // Initialize bulk selection for flagged orders
        if (typeof initBulkSelection === "function") {
            initBulkSelection({
                selectAllId: "ptac-master-toggle",
                checkboxesSelector: ".flagged-order-checkbox",
                selectedCountId: "flagged-selected-count"
            });
        }
        
        // Add confirmation for unflag button (only on flagged tab)
        var unflagBtn = document.querySelector("button[name='unflag_all_orders']");
        if (unflagBtn) {
            unflagBtn.addEventListener("click", function(e) {
                if (!confirm(pt_wuclean_orders_vars.confirm_unflag_all)) {
                    e.preventDefault();
                    return false;
                }
            });
        }
    }
});

