<?php

global $wpdb;

$tables = $wpdb->get_col( "SHOW TABLES LIKE '%actionscheduler_logs%'" );

$as_plugins = [
	'easy-wp-smtp/easy-wp-smtp.php',
	'event-tickets/event-tickets.php',
	'pdf-embedder/pdf_embedder.php',
	'the-events-calendar/the-events-calendar.php',
	'widget-for-eventbright-api/widget-for-eventbright-api.php',
];

foreach ( $tables as $table ) {
	$matched = preg_match( '/^' . $wpdb->base_prefix . '([0-9]+)_/', $table, $matches );

	if ( ! $matched ) {
		continue;
	}

	$site_id = (int) $matches[1];

	$needs_as_tables = false;

	switch_to_blog( $site_id );

	foreach ( $as_plugins as $as_plugin ) {
		if ( is_plugin_active( $as_plugin ) ) {
			$needs_as_tables = true;
			break;
		}
	}

	restore_current_blog();

	if ( ! $needs_as_tables ) {
		WP_CLI::log( "Dropping Action Scheduler tables for site ID {$site_id}." );
	} else {
		WP_CLI::log( "Keeping Action Scheduler tables for site ID {$site_id}." );
	}
}
