
window.mainwpVars = window.mainwpVars || {};

var dbupdater_bulkMaxThreads = 3;
var dbupdater_bulkTotalThreads = 0;
var dbupdater_bulkCurrentThreads = 0;
var dbupdater_bulkFinishedThreads = 0;
var websitesError = 0;

let currentThreads = 0;
let websitesLeft = 0;
let maxThreads = 3;
let websitesDone = 0;
let websitesTotal = 0;

mainwp_db_updater_updatesoverview_plugins_upgrade = function (slug, websiteid) {
    var msg = __('Are you sure you want to update the DB plugin on the selected site?');
    mainwp_confirm(msg, function () {
        return mainwp_db_updater_updatesoverview_plugins_upgrade_int(slug, websiteid);
    }, false, 1);
};


mainwp_db_updater_updatesoverview_plugins_upgrade_all = function (slug, pluginName, updatesSelected) {

    if (mainwpVars.bulkTaskRunning)
        return false;

    //Step 1: build form
    let sitesToUpdate = [];
    let siteNames = [];
    let foundChildren = [];

    if (typeof updatesSelected !== 'undefined' && updatesSelected) {
        jQuery('#mainwp-db-plugins-updates-table table[plugin_slug="' + slug + '"]').find('tr[updated="0"]').each(
            function () {
                if (jQuery(this).find('.child.checkbox').checkbox('is checked')) {
                    foundChildren.push(this);
                }
            }
        );
        if (foundChildren.length == 0) {
            mainwp_db_updater_updates_please_select_items_notice();
            return false;
        }
    } else {
        foundChildren = jQuery('#mainwp-db-plugins-updates-table table[plugin_slug="' + slug + '"]').find('tr[updated="0"]');
    }

    if (foundChildren.length == 0)
        return false;

    mainwpPopup('#mainwp-sync-sites-modal').clearList();

    for (var i = 0; i < foundChildren.length; i++) {
        if (limitUpdateAll > 0 && i >= limitUpdateAll) {
            continueUpdatesAll = 'plugins_upgrade_all';
            continueUpdatesSlug = slug;
            break;
        }
        var child = foundChildren[i];
        var siteId = jQuery(child).attr('site_id');
        var siteName = jQuery(child).attr('site_name');
        siteNames[siteId] = siteName;
        sitesToUpdate.push(siteId);
    }

    pluginName = decodeURIComponent(pluginName);
    pluginName = pluginName.replace(/\+/g, ' ');

    var _callback = function () {

        for (var i = 0; i < sitesToUpdate.length; i++) {
            mainwpPopup('#mainwp-sync-sites-modal').appendItemsList(decodeURIComponent(siteNames[sitesToUpdate[i]]), '<span class="updatesoverview-upgrade-status-wp" siteid="' + sitesToUpdate[i] + '">' + '<span data-inverted="" data-position="left center" data-tooltip="' + __('Pending', 'mainwp') + '"><i class="clock outline icon"></i></span> ' + '</span>');
        }

        var sitesCount = sitesToUpdate.length;

        updatesoverviewContinueAfterBackup = function (pSitesCount, pSlug, pSitesToUpdate) {
            return function () {

                var initData = {
                    title: __('Updating %1', decodeURIComponent(pluginName)),
                    progressMax: pSitesCount
                };
                mainwp_db_updater_updatesoverview_update_popup_init(initData);
                //Step 3: start updates
                mainwp_db_updater_updatesoverview_plugins_upgrade_all_int(pSlug, pSitesToUpdate);
                updatesoverviewContinueAfterBackup = undefined;
            }
        }(sitesCount, slug, sitesToUpdate);

        updatesoverviewContinueAfterBackup();
    }

    // new confirm message
    if (!continueUpdating) {
        if (siteNames.length > 0) {
            var sitesList = [];
            jQuery.each(siteNames, function (index, value) {
                if (value) { // to fix
                    sitesList.push(decodeURIComponent(value));
                }
            });
            var confirmMsg = __('You are about to update the %1 DB plugin on the following site(s): <br/><div class="ui message">%2</div> <strong>Do you want to proceed?</strong>', pluginName, sitesList.join('<br />'));
            mainwp_confirm(confirmMsg, _callback, false, 2);
        }
        return false;
    }
    _callback();
    return false;

};

mainwp_db_updater_updatesoverview_update_popup_init = function (data) {
    data = data || {};
    data.callback = function () {
        mainwpVars.bulkTaskRunning = false;
        window.location.href = location.href;
    };
    data.statusText = __('updated');
    mainwpPopup('#mainwp-sync-sites-modal').init(data);
}

mainwp_db_updater_updates_please_select_items_notice = function () {
    var msg = __('Please, select items to update.');
    jQuery('#mainwp-modal-confirm-select .content-massage').html(msg);
    jQuery('#mainwp-modal-confirm-select').modal('show');
    return false;
}

mainwp_db_updater_updatesoverview_plugins_upgrade_all_int = function (slug, websiteIds, sitesPluginSlugs) {
    currentPluginSlugToUpgrade = slug;
    websitesPluginSlugsToUpgrade = sitesPluginSlugs;
    websitesToUpdatePlugins = websiteIds;
    currentWebsite = 0;
    websitesDone = 0;
    websitesTotal = websitesLeft = websitesToUpdatePlugins.length;

    mainwpVars.bulkTaskRunning = true;

    console.log(websitesTotal, websitesLeft, websitesDone, currentWebsite);

    mainwp_db_updater_updatesoverview_plugins_upgrade_all_loop_next();
};

mainwp_db_updater_updatesoverview_plugins_upgrade_int = function (slug, websiteId, bulkMode) {
    updatesoverviewContinueAfterBackup = function (pSlug, pWebsiteId, pBulkMode) {
        return function () {
            var slugParts = pSlug.split(',');
            for (var i = 0; i < slugParts.length; i++) {
                var websiteHolder = jQuery('.plugins-bulk-updates[plugin_slug="' + slugParts[i] + '"] tr[site_id="' + pWebsiteId + '"]');
                if (!websiteHolder.exists()) {
                    websiteHolder = jQuery('.plugins-bulk-updates[site_id="' + pWebsiteId + '"] tr[plugin_slug="' + slugParts[i] + '"]');
                }
                websiteHolder.find('td:last-child').html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Updating...', 'mainwp') + '"><i class="notched circle loading icon"></i></span> ' + __('Updating. Please wait...'));
            }

            var data = mainwp_secure_data({
                action: 'mainwp_database_updater_update_db', // mainwp_upgradeplugintheme.
                websiteId: pWebsiteId,
                type: 'plugin',
                'slugs[]': [slugParts], // slug: pSlug.
            });
            jQuery.ajax({
                type: "POST",
                url: ajaxurl,
                data: data,
                success: function (pSlug, pWebsiteId, pBulkMode) {
                    return function (response) {
                        var slugParts = pSlug.split(',');
                        var slug = slugParts.length > 0 ? slugParts[0] : '';
                        var slug = decodeURIComponent(slug);
                        for (var i = 0; i < slugParts.length; i++) {
                            var websiteHolder = jQuery('.plugins-bulk-updates[plugin_slug="' + slugParts[i] + '"] tr[site_id="' + pWebsiteId + '"]');
                            if (!websiteHolder.exists()) {
                                websiteHolder = jQuery('.plugins-bulk-updates[site_id="' + pWebsiteId + '"] tr[plugin_slug="' + slugParts[i] + '"]');
                            }
                            if (response?.errorCode) {
                                websitesError++;
                                var extErr = mainwp_db_updater_getErrorMessageInfo(response, 'ui')
                                if (pBulkMode)
                                    mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_site_status(pWebsiteId, extErr);
                                websiteHolder.find('td:last-child').html(extErr);
                            } else if (response.error) {
                                websitesError++;
                                var extErr = mainwp_db_updater_getErrorMessageInfo(response.error, 'ui')
                                if (pBulkMode)
                                    mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_site_status(pWebsiteId, extErr);
                                websiteHolder.find('td:last-child').html(extErr);
                            } else {

                                var res = response?.result;
                                if (res[slugParts[i]]) {
                                    if (pBulkMode)
                                        mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_site_status(pWebsiteId, '<span data-inverted="" data-position="left center" data-tooltip="' + __('Update successful', 'mainwp') + '"><i class="green check icon"></i></span>' + ' ' + mainwp_links_visit_site_and_admin('', pWebsiteId));
                                    websiteHolder.attr('updated', 1);
                                    websiteHolder.find('td:last-child').html('<span data-inverted="" data-position="left center" data-tooltip="' + __('Update successful', 'mainwp') + '"><i class="green check icon"></i></span>' + ' ' + mainwp_links_visit_site_and_admin('', pWebsiteId));
                                } else {
                                    if (pBulkMode)
                                        mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_site_status(pWebsiteId, '<i class="red times icon"></i>');
                                    websiteHolder.find('td:last-child').html('<i class="red times icon"></i>');
                                }
                                if (pBulkMode) {
                                    mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_done();
                                }
                            }
                        }
                    }
                }(pSlug, pWebsiteId, pBulkMode),
                tryCount: 0,
                retryLimit: 3,
                endError: function (pSlug, pWebsiteId, pBulkMode) {
                    return function () {
                        var slugParts = pSlug.split(',');
                        for (var i = 0; i < slugParts.length; i++) {
                            //Siteview
                            var websiteHolder = jQuery('div[plugin_slug="' + slugParts[i] + '"] div[site_id="' + pWebsiteId + '"]');
                            if (!websiteHolder.exists()) {
                                websiteHolder = jQuery('div[site_id="' + pWebsiteId + '"] div[plugin_slug="' + slugParts[i] + '"]');
                            }

                            if (pBulkMode) {
                                mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_site_status(pWebsiteId, '<i class="red times icon"></i>');
                                mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_done();
                            }
                            websiteHolder.find('td:last-child').html('<i class="red times icon"></i>');
                        }
                    }
                }(pSlug, pWebsiteId, pBulkMode),
                error: function (xhr) {
                    this.tryCount++;
                    if (this.tryCount >= this.retryLimit) {
                        this.endError();
                        return;
                    }

                    var fnc = function (pRqst, pXhr) {
                        return function () {
                            if (pXhr.status == 404) {
                                //handle error
                                jQuery.ajax(pRqst);
                            } else if (pXhr.status == 500) {
                                //handle error
                            } else {
                                //handle error
                            }
                        }
                    }(this, xhr);
                    setTimeout(fnc, 500);
                },
                dataType: 'json'
            });

            updatesoverviewContinueAfterBackup = undefined;
        }
    }(slug, websiteId, bulkMode);
    updatesoverviewContinueAfterBackup();
};

mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_site_status = function (siteId, newStatus) {
    jQuery('.updatesoverview-upgrade-status-wp[siteid="' + siteId + '"]').html(newStatus);
};

mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_done = function () {
    currentThreads--;
    websitesDone++;

    mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(websitesDone);

    if (websitesDone == websitesTotal) {
        if (websitesError > 0) {
            return;
        } else {
            setTimeout(function () {
                window.location.href = 'admin.php?page=UpdatesManage&tab=plugin-db-updates';
            }, 2000);
        }
    }

    console.log(websitesTotal, websitesLeft, websitesDone, currentWebsite);

    mainwp_db_updater_updatesoverview_plugins_upgrade_all_loop_next();
};


mainwp_db_updater_updatesoverview_plugins_upgrade_all_loop_next = function () {
    while (mainwpVars?.bulkTaskRunning && (currentThreads < maxThreads) && (websitesLeft > 0)) {
        mainwp_db_updater_updatesoverview_plugins_upgrade_all_upgrade_next();
    }
};

mainwp_db_updater_updatesoverview_plugins_upgrade_all_upgrade_next = function () {
    currentThreads++;
    websitesLeft--;

    var websiteId = websitesToUpdatePlugins[currentWebsite++];

    mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_site_status(websiteId, '<i class="notched circle loading icon"></i>');

    var slugToUpgrade = currentPluginSlugToUpgrade;
    if (slugToUpgrade == undefined) {
        slugToUpgrade = websitesPluginSlugsToUpgrade[websiteId];
    }
    mainwp_db_updater_updatesoverview_plugins_upgrade_int(slugToUpgrade, websiteId, true, true);
};

mainwp_db_updater_getErrorMessageInfo = function (repError, outputType) {
    var msg = '';
    var msgUI = '<i class="red times icon"></i>';

    if (repError.errorCode != undefined && repError.errorCode == 'SUSPENDED_SITE') {
        msg = __('Suspended site.');
        msgUI = '<span data-inverted="" data-position="left center" data-tooltip="' + __('Suspended site.') + '"><i class="pause circular yellow inverted icon"></i></span>';
    }

    if (msg == '') {
        msg = mainwp_db_updater_getErrorMessage(repError);
        if (msg != '') {
            msgUI = '<span data-inverted="" data-position="left center" data-tooltip="' + msg + '"><i class="red times icon"></i></span>';
        }
    }

    if (msg != '') {
        if (outputType != undefined && outputType == 'ui') {
            return msgUI;
        } else {
            return msg;
        }
    }

    return repError;
}

let mainwp_db_updater_getErrorMessage = function (pError, msgOnly) {
    if (pError.message == 'HTTPERROR') {
        return __('HTTP error') + '! ' + pError.extra;
    } else if (pError.message == 'NOMAINWP' || pError == 'NOMAINWP') {
        var error = '';
        if (pError.extra) {
            error = __('MainWP Child plugin not detected or could not be reached! Ensure the MainWP Child plugin is installed and activated on the child site, and there are no security rules blocking requests.  If you continue experiencing this issue, check the <a href="https://managers.mainwp.com/c/community-support/5">MainWP Community</a> for help.', pError.extra); // to fix incorrect encoding
        } else {
            error = __('MainWP Child plugin not detected or could not be reached! Ensure the MainWP Child plugin is installed and activated on the child site, and there are no security rules blocking requests.  If you continue experiencing this issue, check the <a href="https://managers.mainwp.com/c/community-support/5">MainWP Community</a> for help.');
        }

        return error;
    } else if (pError.message == 'ERROR') {
        return 'ERROR' + ((pError.extra != '') && (pError.extra != undefined) ? ': ' + pError.extra : '');
    } else if (pError.message == 'WPERROR') {
        var extrMsg = (pError.extra != '') && (pError.extra != undefined) ? pError.extra : '';
        if (msgOnly != undefined && msgOnly && extrMsg != '') {
            return extrMsg;
        } else {
            return __('ERROR on the child site') + ': ' + extrMsg;
        }

    } else if (pError.message != undefined && pError.message != '') {
        return pError.message;
    } else {
        return pError;
    }
};

/* eslint-disable complexity */
mainwp_database_updater_global_upgrade_all = function (which) { // @see updatesoverview_global_upgrade_all() in the file mainwp-updates.js (dashboard).

    if (mainwpVars?.bulkTaskRunning) {
        return false;
    }

    //Step 1: build form
    var sitesToUpdate = [];
    var sitesPluginSlugs = {};
    var siteNames = {};

    mainwpPopup('#mainwp-sync-sites-modal').clearList();

    var sitesCount = 0;
    var foundChildren = undefined;

    if (which == 'plugin_db') {
        //Find plugins to update
        foundChildren = jQuery('#wp_plugin_database_updater_db_upgrades').find('div[updated="0"]');
        if (foundChildren.length != 0) {
            for (var i = 0; i < foundChildren.length; i++) {
                var child = jQuery(foundChildren[i]);
                siteElement = child;

                var siteId = siteElement.attr('site_id');
                var siteName = siteElement.attr('site_name');
                var pluginSlug = siteElement.attr('plugin_db_slug');

                if (sitesToUpdate.indexOf(siteId) == -1) {
                    sitesCount++;
                    sitesToUpdate.push(siteId);
                    siteNames[siteId] = siteName;
                }

                if (sitesPluginSlugs[siteId] == undefined) {
                    sitesPluginSlugs[siteId] = pluginSlug;
                } else {
                    sitesPluginSlugs[siteId] += ',' + pluginSlug;
                }
            }
        }
    }

    var _callback = function () {
        //Build form
        for (var j = 0; j < sitesToUpdate.length; j++) {
            var siteId = sitesToUpdate[j];

            var whatToUpgrade = 'Database';

            if (sitesPluginSlugs[siteId] != undefined) {
                var updateCount = sitesPluginSlugs[siteId].match(/,/g);
                if (updateCount == null)
                    updateCount = 1;
                else
                    updateCount = updateCount.length + 1;

                if (whatToUpgrade != '')
                    whatToUpgrade += ', ';

                whatToUpgrade += '<span class="plugin">' + updateCount + ' plugin' + (updateCount > 1 ? 's' : '') + '</span>';
            }

            mainwpPopup('#mainwp-sync-sites-modal').appendItemsList(decodeURIComponent(siteNames[siteId]) + ' (' + whatToUpgrade + ')', '<span class="updatesoverview-upgrade-status-wp" siteid="' + siteId + '">' + '<i class="clock outline icon"></i> ' + '</span>');
        }

        updatesoverviewContinueAfterBackup = function (pSitesCount, pSitesToUpdate, pSitesPluginSlugs) {
            return function () {
                //Step 2: show form

                var initData = {
                    title: __('Updating Plugins Database'),
                    progressMax: pSitesCount
                };
                updatesoverview_update_popup_init(initData);

                //Step 3: start updates
                mainwp_database_updater_start_updatesoverview_upgrade_all_int(pSitesToUpdate, pSitesPluginSlugs);

                updatesoverviewContinueAfterBackup = undefined;
            };
        }(sitesCount, sitesToUpdate, sitesPluginSlugs);

        // call dashboard's method.
        return mainwp_updatesoverview_checkBackups(sitesToUpdate, siteNames);
    } // end _callback()

    // new confirm message
    if (jQuery(siteNames).length > 0) {
        var sitesList = [];
        jQuery.each(siteNames, function (index, value) {
            if (value) { // to fix
                sitesList.push(decodeURIComponent(value));
            }
        });

        var whichUpdates = __('plugins Database');
        var confirmMsg = __('You are about to update %1 on the following site(s): <br/><div class="ui message">%2</div> <strong>Do you want to proceed?</strong>', whichUpdates, sitesList.join('<br />'));

        mainwp_confirm(confirmMsg, _callback, false, 2);
        return false;
    } else {
        return false;
    }
}


mainwp_database_updater_start_updatesoverview_upgrade_all_int = function (pSitesToUpdate, pSitesPluginSlugs) {
    websitesToUpdate = pSitesToUpdate;
    websitesPluginSlugsToUpgrade = pSitesPluginSlugs;
    currentPluginSlugToUpgrade = undefined;
    currentWebsite = 0;
    websitesDone = 0;
    websitesTotal = websitesLeft = websitesToUpdate.length;
    mainwpVars.bulkTaskRunning = true;
    mainwp_database_updater_updatesoverview_upgrade_all_loop_next();
};

mainwp_database_updater_updatesoverview_upgrade_all_loop_next = function () {
    while (mainwpVars?.bulkTaskRunning && (currentThreads < maxThreads) && (websitesLeft > 0)) {
        mainwp_database_updater_updatesoverview_upgrade_all_upgrade_next();
    }
};

mainwp_database_updater_updatesoverview_upgrade_all_upgrade_next = function () {
    currentThreads++;
    websitesLeft--;
    var websiteId = websitesToUpdate[currentWebsite++];
    updatesoverview_upgrade_all_update_site_status(websiteId, '<i class="notched circle loading icon"></i>');
    var pluginSlugToUpgrade = websitesPluginSlugsToUpgrade[websiteId];
    mainwp_database_updater_updatesoverview_upgrade_int(websiteId, pluginSlugToUpgrade);
};

mainwp_database_updater_updatesoverview_upgrade_int = function (websiteId, pPluginSlugToUpgrade) {
    mainwp_database_updater_updatesoverview_upgrade_int_flow(websiteId, pPluginSlugToUpgrade, (pPluginSlugToUpgrade == undefined)); // update selected one, if pPluginSlugToUpgrade == undefined, will update next site.
    return false;
};

mainwp_database_updater_updatesoverview_upgrade_int_flow = function (pWebsiteId, pPluginSlugToUpgrade, pPluginDone, pErrorMessage) {
    if (!pPluginDone) {
        var data = mainwp_secure_data({
            action: 'mainwp_database_updater_update_db',
            websiteId: pWebsiteId,
            type: 'plugin',
            'slugs[]': [pPluginSlugToUpgrade]
        });

        jQuery.ajax({
            type: "POST",
            url: ajaxurl,
            data: data,
            success: function (pWebsiteId, pSlug, pErrorMessage) {
                return function (response) {
                    var slugParts = pSlug.split(',');
                    for (var i = 0; i < slugParts.length; i++) {
                        var result;
                        var websiteHolder = jQuery('div[plugin_db_slug="' + slugParts[i] + '"] div[site_id="' + pWebsiteId + '"]');
                        if (!websiteHolder.exists()) {
                            websiteHolder = jQuery('div[site_id="' + pWebsiteId + '"] div[plugin_db_slug="' + slugParts[i] + '"]');
                        }
                        if (response?.errorCode) {
                            websitesError++;
                            var extErr = mainwp_db_updater_getErrorMessageInfo(response, 'ui')
                            if (pBulkMode)
                                mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_site_status(pWebsiteId, extErr);
                            websiteHolder.find('td:last-child').html(extErr);
                        } else if (response?.error) {
                            result = getErrorMessage(response.error);
                            pErrorMessage = result;
                            var extErr = mainwp_db_updater_getErrorMessageInfo(response.error, 'ui')
                            if (pBulkMode)
                                mainwp_db_updater_updatesoverview_plugins_upgrade_all_update_site_status(pWebsiteId, extErr);
                            websiteHolder.find('td:last-child').html(extErr);
                        } else {
                            var res = response?.result;   // result is an object
                            var res_error = response?.result_error;
                            if (res[encodeURIComponent(slugParts[i])]) {
                                websiteHolder.attr('updated', 1);
                            } else if (res_error[encodeURIComponent(slugParts[i])]) {
                                pErrorMessage = res_error[encodeURIComponent(slugParts[i])];
                            } else {
                                result = __('Update failed!');
                                pErrorMessage = result;
                            }
                        }
                    }
                    updatesoverview_upgrade_all_update_site_bold(pWebsiteId, 'plugin');
                    //done for this site: continue next site: by pPluginDone = 'true';
                    mainwp_database_updater_updatesoverview_upgrade_int_loop_flow(pWebsiteId, pSlug, true, pErrorMessage);
                }
            }(pWebsiteId, pPluginSlugToUpgrade, pErrorMessage),
            tryCount: 0,
            retryLimit: 3,
            endError: function (pWebsiteId, pPluginSlugToUpgrade) {
                return function () {
                    mainwp_database_updater_updatesoverview_upgrade_int_loop_flow(pWebsiteId, pPluginSlugToUpgrade, true, 'Error processing request');
                }
            }(pWebsiteId, pPluginSlugToUpgrade),
            error: function (xhr) {
                this.tryCount++;
                if (this.tryCount >= this.retryLimit) {
                    this.endError();
                    return;
                }

                var fnc = function (pRqst, pXhr) {
                    return function () {
                        if (pXhr.status == 404) {
                            //handle error
                            jQuery.ajax(pRqst);
                        } else if (pXhr.status == 500) {
                            //handle error
                        } else {
                            //handle error
                        }
                    }
                }(this, xhr);
                setTimeout(fnc, 1000);
            },
            dataType: 'json'
        });
    } else {
        if ((pErrorMessage != undefined) && (pErrorMessage != '')) {
            updatesoverview_upgrade_all_update_site_status(pWebsiteId, '<i class="red times icon"></i>');
        } else {
            updatesoverview_upgrade_all_update_site_status(pWebsiteId, '<i class="green check icon"></i>');
        }
        mainwp_database_updater_updatesoverview_upgrade_all_update_done();

        return false;
    }
};

mainwp_database_updater_updatesoverview_upgrade_int_loop_flow = function (pWebsiteId, pPluginSlugToUpgrade, pPluginDone, pErrorMessage) {
    mainwp_database_updater_updatesoverview_upgrade_int_flow(pWebsiteId, pPluginSlugToUpgrade, pPluginDone, pErrorMessage); // bulk update. if pPluginDone == true, will update next site.
    return false;
};

mainwp_database_updater_updatesoverview_upgrade_all_update_done = function () {
    currentThreads--;

    websitesDone++;

    mainwpPopup('#mainwp-sync-sites-modal').setProgressSite(websitesDone);

    if (websitesDone == websitesTotal) {
        setTimeout(function () {
            mainwpVars.bulkTaskRunning = false;
            // close and refresh page
            mainwpPopup('#mainwp-sync-sites-modal').close(true);
        }, 3000);
        return;
    }

    mainwp_database_updater_updatesoverview_upgrade_all_loop_next();
};

