/**
 * Wuclean Users JavaScript
 * 
 * This file contains JavaScript functionality specific to the users cleanup page.
 */

// Initialize user cleanup functionality
function initUserCleanup() {
    function formatString(template) {
        var args = Array.prototype.slice.call(arguments, 1);
        return args.reduce(function(result, value) {
            return result.replace(/%[sd]/, value);
        }, template);
    }
    // Initialize the user scan with progress display (matching orders/products style)
    if (jQuery("#pt-start-user-scan").length > 0) {
        if (typeof initSearchProgress === 'function') {
            initSearchProgress({
                startButtonId: "#pt-start-user-scan",
                stopButtonId: "#pt-stop-user-scan",
                progressDivId: "#pt-user-scan-progress",
                progressBarId: "#pt-user-progress-bar",
                progressTextId: "#pt-user-progress-text",
                ajaxAction: "pt_wuclean_start_user_search",
                ajaxNonce: pt_wuclean_users_vars.user_scan_nonce,
                successMessage: function(progress) {
                    var newFlags = progress.flagged_count || 0;
                    var storedFlags = progress.stored_flagged_count || 0;
                    if (newFlags > 0) {
                        return formatString(pt_wuclean_users_vars.scan_completed_flagged, newFlags);
                    } else if (storedFlags > 0) {
                        // No new flags but existing flagged users exist - redirecting to show them
                        return pt_wuclean_users_vars.scan_completed_no_new_redirecting || 'Scan completed! No new customers match the current flagging criteria. Redirecting to show existing flagged customers...';
                    }
                    return pt_wuclean_users_vars.scan_completed_none;
                },
                redirectUrl: pt_wuclean_users_vars.flagged_users_url,
                otherButtonSelectors: "",
                useBatchProcessing: true
            });
        }
    }
    
    // Initialize orphaned customer data scan - using consolidated utility function with batch processing
    if (jQuery("#pt-start-orphaned-customer-scan").length > 0) {
        if (typeof initSearchProgress === 'function') {
            initSearchProgress({
                startButtonId: "#pt-start-orphaned-customer-scan",
                stopButtonId: "#pt-stop-orphaned-customer-scan",
                progressDivId: "#pt-orphaned-customer-scan-progress",
                progressBarId: "#pt-orphaned-customer-progress-bar",
                progressTextId: "#pt-orphaned-customer-progress-text",
                ajaxAction: "pt_wuclean_start_orphaned_customer_search",
                ajaxNonce: pt_wuclean_users_vars.orphaned_customer_scan_nonce,
                successMessage: function(progress) {
                    var totalFound = progress.total_found || 0;
                    if (totalFound > 0) {
                        return formatString(pt_wuclean_users_vars.scan_complete_found, totalFound);
                    } else {
                        return pt_wuclean_users_vars.scan_complete_none;
                    }
                },
                redirectUrl: pt_wuclean_users_vars.orphaned_customer_data_url,
                otherButtonSelectors: "#pt-start-user-scan",
                useBatchProcessing: true  // Enable batch-by-batch processing for shared hosting compatibility
            });
        }
    }
    
    // Initialize bulk selection for flagged users with retry mechanism
    function initBulkSelectionWithRetry() {
        const masterToggle = document.getElementById('ptac-master-toggle');
        const selectedCountSpan = document.getElementById('flagged-selected-count');
        
        if (masterToggle && selectedCountSpan) {
            if (typeof initBulkSelection === 'function') {
                initBulkSelection({
                    selectAllId: 'ptac-master-toggle',
                    checkboxesSelector: '.flagged-user-checkbox',
                    selectedCountId: 'flagged-selected-count'
                });
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    
    // Only initialize bulk selection if we're on the flagged users 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) {
        // Try to initialize immediately, then retry if needed
        if (!initBulkSelectionWithRetry()) {
            setTimeout(function() {
                if (!initBulkSelectionWithRetry()) {
                    setTimeout(initBulkSelectionWithRetry, 1000);
                }
            }, 500);
        }
    }
    
    // Note: Confirmation for unflag all users button is handled by inline onclick attribute in PHP
    
    
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    initUserCleanup();
});
