<?php
/**
 * Speedlyst uninstall handler.
 *
 * Data is retained unless each blog explicitly opted into deletion.
 *
 * @package MarketingConsole
 */

if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

/**
 * Delete plugin options only for an opted-in current blog.
 *
 * @return bool True when this blog opted in and its plugin data was removed.
 */
function speedlyst_uninstall_current_blog(): bool {
	if ( '1' !== get_option( 'speedlyst_delete_on_uninstall', '0' ) ) {
		return false;
	}

	$options = array(

		'speedlyst_free_speed_history',
		'speedlyst_free_speed_history_lock',
		'speedlyst_free_psi_history_lock',
		'speedlyst_free_psi_api_key',
		'speedlyst_free_psi_result',
		'speedlyst_free_psi_last_error',
		'speedlyst_free_psi_history',
		'speedlyst_free_psi_nonce',
		'speedlyst_free_psi_quota',
		'speedlyst_free_psi_quota_lock',
		'speedlyst_free_psi_quota_measure',
		'speedlyst_free_request_profile',
		'speedlyst_delete_on_uninstall',
	);

	foreach ( $options as $option ) {
		delete_option( $option );
	}

	wp_clear_scheduled_hook( 'speedlyst_free_daily_snapshot' );

	return true;
}

/**
 * Remove the language choice stored network-wide in user meta.
 *
 * It is not reached by the per-blog option loop and is deleted once after the
 * loop, only when at least one blog opted in.
 *
 * @return void
 */
function speedlyst_uninstall_network_wide(): void {
	delete_metadata( 'user', 0, 'speedlyst_locale', '', true );
}

$speedlyst_any_opt_in = false;

if ( is_multisite() ) {
	$speedlyst_site_ids = get_sites(
		array(
			'fields' => 'ids',
			'number' => 0,
		)
	);

	foreach ( $speedlyst_site_ids as $speedlyst_site_id ) {
		switch_to_blog( (int) $speedlyst_site_id );
		$speedlyst_any_opt_in = speedlyst_uninstall_current_blog() || $speedlyst_any_opt_in;
		restore_current_blog();
	}
} else {
	$speedlyst_any_opt_in = speedlyst_uninstall_current_blog();
}

if ( $speedlyst_any_opt_in ) {
	speedlyst_uninstall_network_wide();
}
