<?php
/**
 * WP PowerSuite Uninstall Handler
 *
 * When uninstalling, optionally delete all plugin data from the database.
 * Uses DataRegistry for comprehensive cleanup of module tables and data.
 *
 * @package WP_PowerSuite
 * @since 1.0.0
 */

// If uninstall not called from WordPress, then exit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

/**
 * Fallback table list when DataRegistry cannot be loaded.
 *
 * @return array<string>
 */
function wpps_get_fallback_module_tables(): array {
	global $wpdb;
	$tables = [
		'wpps_activity_log',
		'wpps_short_links',
		'wpps_short_links_analytics',
		'wpps_form_entries',
		'tl_temporary_logins',
		'tl_activity_logs',
		'wpps_404_logs',
		'wpps_login_attempts',
		'wpps_magic_links',
		'wpps_revisions',
		'wpps_redirects',
		'wpps_email_logs',
		'wpps_backup_logs',
	];
	return array_map( fn( $t ) => $wpdb->prefix . $t, $tables );
}

/**
 * Load DataRegistry for uninstall (lightweight bootstrap).
 */
function wpps_load_data_registry(): void {
	$registry_file = defined( 'WP_POWERSUITE_PLUGIN_DIR' )
		? WP_POWERSUITE_PLUGIN_DIR . 'src' . DIRECTORY_SEPARATOR . 'Core' . DIRECTORY_SEPARATOR . 'DataRegistry.php'
		: __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'Core' . DIRECTORY_SEPARATOR . 'DataRegistry.php';
	if ( $registry_file && file_exists( $registry_file ) ) {
		require_once $registry_file;
	}
}

/**
 * Load NetworkScope for uninstall (lightweight bootstrap).
 */
function wpps_load_network_scope(): void {
	$scope_file = defined( 'WP_POWERSUITE_PLUGIN_DIR' )
		? WP_POWERSUITE_PLUGIN_DIR . 'src' . DIRECTORY_SEPARATOR . 'Core' . DIRECTORY_SEPARATOR . 'NetworkScope.php'
		: __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'Core' . DIRECTORY_SEPARATOR . 'NetworkScope.php';
	if ( $scope_file && file_exists( $scope_file ) ) {
		require_once $scope_file;
	}
}

/**
 * Clear scheduled events that may remain after modules are disabled or removed.
 */
function wpps_clear_scheduled_hooks(): void {
	$hooks = class_exists( 'WP_PowerSuite\Core\DataRegistry' )
		? \WP_PowerSuite\Core\DataRegistry::getCronHooks()
		: [
			'wpps_dml_cleanup_expired_zips',
			'wpps_content_expiration_check',
			'wpps_br_scheduled_backup',
			'tl_cleanup_expired_logins',
			'tl_cleanup_activity_logs',
			'wpps_login_as_cleanup_sessions',
			'wpps_magic_links_cleanup',
			'wpps_track_404s_cleanup',
			'wpps_activity_log_cleanup',
			'wp_powersuite_license_recheck',
			'wpps_email_reports_daily',
			'wpps_email_reports_weekly',
			'wpps_email_reports_monthly',
			'wpps_email_logs_prune',
			'wpps_login_attempts_prune',
		];

	foreach ( $hooks as $hook ) {
		wp_clear_scheduled_hook( $hook );
	}
}

/**
 * Check if user wants to delete all plugin data.
 *
 * Uses the option set by UninstallHandler when user confirms delete on plugins page.
 * Default: preserve data (WordPress best practice).
 */
function wpps_should_delete_all_data() {
	wpps_load_network_scope();

	if ( class_exists( 'WP_PowerSuite\Core\NetworkScope' ) ) {
		return \WP_PowerSuite\Core\NetworkScope::shouldDeleteOnUninstall();
	}

	$delete_on_uninstall = get_option( 'wp_powersuite_delete_on_uninstall', false );
	return $delete_on_uninstall === 'yes' || $delete_on_uninstall === '1';
}

/**
 * Delete all WP PowerSuite data from the database
 */
function wpps_delete_all_plugin_data() {
	global $wpdb;

	wpps_load_data_registry();

	if ( class_exists( 'WP_PowerSuite\Core\DataRegistry' ) ) {
		\WP_PowerSuite\Core\DataRegistry::deleteAllPluginData();
		return;
	}

	wpps_clear_scheduled_hooks();

	// Delete main plugin option (contains all module settings)
	delete_option( 'wp_powersuite_settings' );
	delete_site_option( 'wp_powersuite_settings' ); // Multisite

	// Delete all transients related to WP PowerSuite (wp_powersuite_%, wpps_%, tl_%)
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} 
			WHERE option_name LIKE %s OR option_name LIKE %s 
			OR option_name LIKE %s OR option_name LIKE %s 
			OR option_name LIKE %s OR option_name LIKE %s",
			'_transient_wp_powersuite_%',
			'_transient_timeout_wp_powersuite_%',
			'_transient_wpps_%',
			'_transient_timeout_wpps_%',
			'_transient_tl_%',
			'_transient_timeout_tl_%'
		)
	);

	// Delete all site transients (multisite)
	if ( is_multisite() ) {
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} 
				WHERE option_name LIKE %s OR option_name LIKE %s 
				OR option_name LIKE %s OR option_name LIKE %s 
				OR option_name LIKE %s OR option_name LIKE %s",
				'_site_transient_wp_powersuite_%',
				'_site_transient_timeout_wp_powersuite_%',
				'_site_transient_wpps_%',
				'_site_transient_timeout_wpps_%',
				'_site_transient_tl_%',
				'_site_transient_timeout_tl_%'
			)
		);
	}

	// Delete plugin-specific options
	$plugin_options = [
		'wp_powersuite_delete_on_uninstall',
		'wp_powersuite_version',
		'wp_powersuite_db_version',
		'wpps_tl_db_ready',
		'tl_secret_key',
	];
	foreach ( $plugin_options as $option ) {
		delete_option( $option );
		delete_site_option( $option ); // Multisite
	}

	// Delete custom tables from DataRegistry (module tables)
	$custom_tables = class_exists( 'WP_PowerSuite\Core\DataRegistry' )
		? \WP_PowerSuite\Core\DataRegistry::getCustomTables()
		: wpps_get_fallback_module_tables();
	foreach ( $custom_tables as $table ) {
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
		if ( $table_exists ) {
			$wpdb->query( "DROP TABLE IF EXISTS `{$table}`" );
		}
	}

	// Delete user meta (wp_powersuite_% and _wpps_% used by modules)
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s",
			'wp_powersuite_%'
		)
	);
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s",
			'_wpps_%'
		)
	);

	// Delete post meta
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s",
			'wp_powersuite_%'
		)
	);
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s",
			'_wpps_%'
		)
	);

	// Delete comment meta
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->commentmeta} WHERE meta_key LIKE %s",
			'wp_powersuite_%'
		)
	);
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->commentmeta} WHERE meta_key LIKE %s",
			'_wpps_%'
		)
	);

	// Delete any remaining options with plugin prefixes
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} 
			WHERE option_name LIKE %s OR option_name LIKE %s",
			'wp_powersuite_%',
			'_wpps_%'
		)
	);
	if ( is_multisite() ) {
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->sitemeta} 
				WHERE meta_key LIKE %s OR meta_key LIKE %s",
				'wp_powersuite_%',
				'_wpps_%'
			)
		);
	}

	wp_cache_flush();
}

if ( ! defined( 'WP_POWERSUITE_PLUGIN_FILE' ) && wpps_should_delete_all_data() ) {
	wpps_delete_all_plugin_data();
}

