<?php
/**
 * JJ's Post and Product Scheduler uninstall handler.
 *
 * @package ScheduledChanges
 */

// phpcs:disable WordPress.DB -- Scheduler-owned custom tables require direct wpdb queries.
// phpcs:disable PluginCheck.Security.DirectDB -- Table names are resolved from scheduler-owned allowlists.

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

if ( 'yes' !== get_option( 'scheduled_changes_delete_data_on_uninstall', 'no' ) ) {
	return;
}

$scheduled_changes_autoload = __DIR__ . '/vendor/autoload.php';

if ( is_readable( $scheduled_changes_autoload ) ) {
	require_once $scheduled_changes_autoload;

	$scheduled_changes_uninstall_plan     = new ScheduledChanges\Extension\ModuleUninstallPlan();
	$scheduled_changes_cleanup_operations = $scheduled_changes_uninstall_plan->cleanupOperations();
	$scheduled_changes_options            = $scheduled_changes_uninstall_plan->options();
	$scheduled_changes_meta_keys          = $scheduled_changes_uninstall_plan->metaKeys();
	$scheduled_changes_action_hooks       = $scheduled_changes_uninstall_plan->actionHooks();
	$scheduled_changes_tables             = $scheduled_changes_uninstall_plan->tables();
} else {
	global $wpdb;

	$scheduled_changes_prefix             = $wpdb->prefix . 'scheduled_changes_';
	$scheduled_changes_cleanup_operations = array( 'roles-and-capabilities', 'recording-workspaces', 'scheduled-actions', 'transient-admin-notices', 'export-files' );
	$scheduled_changes_options            = array(
		'scheduled_changes_activated_at',
		'scheduled_changes_compatibility_telemetry',
		'scheduled_changes_delete_data_on_uninstall',
		'scheduled_changes_enable_raw_metadata',
		'scheduled_changes_last_queue_activity_utc',
		'scheduled_changes_migration_lock',
		'scheduled_changes_migration_status',
		'scheduled_changes_notification_preferences',
		'scheduled_changes_provider_cache_generation',
		'scheduled_changes_recording_cleanup_status',
		'scheduled_changes_schema_version',
		'scheduled_changes_snapshot_retention_purge_status',
		'scheduled_changes_version',
	);
	$scheduled_changes_meta_keys          = array(
		'_scheduled_changes_creation_operation_uuid',
		'_scheduled_changes_creation_request_hash',
		'_scheduled_changes_recorded_catalog_visibility',
		'_scheduled_changes_recorded_product_slug',
		'_scheduled_changes_recorded_product_status',
		'_scheduled_changes_recording_desired_status',
		'_scheduled_changes_recording_owner_id',
		'_scheduled_changes_recording_pending_term_assignments',
		'_scheduled_changes_recording_pending_terms',
		'_scheduled_changes_recording_session_uuid',
		'_scheduled_changes_recording_source_id',
		'_scheduled_changes_recording_workspace',
		'_scheduled_changes_recording_workspace_marker',
		'_scheduled_changes_shadow_product',
		'_scheduled_changes_source_object_id',
		'_scheduled_changes_source_object_type',
		'_scheduled_changes_source_product_id',
	);
	$scheduled_changes_action_hooks       = array( 'scheduled_changes_execute_launch' );
	$scheduled_changes_tables             = array(
		$scheduled_changes_prefix . 'snapshots',
		$scheduled_changes_prefix . 'run_operations',
		$scheduled_changes_prefix . 'operations',
		$scheduled_changes_prefix . 'launch_targets',
		$scheduled_changes_prefix . 'audit_events',
		$scheduled_changes_prefix . 'runs',
		$scheduled_changes_prefix . 'notifications',
		$scheduled_changes_prefix . 'recording_sessions',
		$scheduled_changes_prefix . 'locks',
		$scheduled_changes_prefix . 'launch_versions',
		$scheduled_changes_prefix . 'launches',
	);
}

$scheduled_changes_capabilities = array(
	'scheduled_changes_view_schedules',
	'scheduled_changes_edit_schedules',
	'scheduled_changes_create_schedules',
	'scheduled_changes_delete_schedules',
	'scheduled_changes_schedule_changes',
	'scheduled_changes_execute_schedules',
	'scheduled_changes_rollback_schedules',
	'scheduled_changes_view_logs',
	'scheduled_changes_manage_settings',
);

if ( in_array( 'roles-and-capabilities', $scheduled_changes_cleanup_operations, true ) ) {
	foreach ( array( 'administrator' ) as $scheduled_changes_role_name ) {
		$scheduled_changes_role = get_role( $scheduled_changes_role_name );

		if ( ! $scheduled_changes_role ) {
			continue;
		}

		foreach ( $scheduled_changes_capabilities as $scheduled_changes_capability ) {
			$scheduled_changes_role->remove_cap( $scheduled_changes_capability );
		}
	}
}

foreach ( $scheduled_changes_options as $scheduled_changes_option ) {
	delete_option( $scheduled_changes_option );
}

global $wpdb;

if ( in_array( 'recording-workspaces', $scheduled_changes_cleanup_operations, true ) ) {
	$scheduled_changes_shadow_ids = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT DISTINCT p.ID
			FROM {$wpdb->posts} p
			WHERE p.post_status IN (%s, %s)",
			'sc_recording',
			'scheduled_changes_recording'
		)
	);

	foreach ( is_array( $scheduled_changes_shadow_ids ) ? $scheduled_changes_shadow_ids : array() as $scheduled_changes_shadow_id ) {
		wp_delete_post( (int) $scheduled_changes_shadow_id, true );
	}
}

foreach ( $scheduled_changes_meta_keys as $scheduled_changes_meta_key ) {
	$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => $scheduled_changes_meta_key ), array( '%s' ) );
}

if ( in_array( 'transient-admin-notices', $scheduled_changes_cleanup_operations, true ) ) {
	$wpdb->query(
		$wpdb->prepare(
			"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
			$wpdb->esc_like( '_transient_scheduled_changes_admin_notice_' ) . '%',
			$wpdb->esc_like( '_transient_timeout_scheduled_changes_admin_notice_' ) . '%'
		)
	);
}

if ( function_exists( 'as_unschedule_all_actions' ) ) {
	foreach ( $scheduled_changes_action_hooks as $scheduled_changes_action_hook ) {
		as_unschedule_all_actions( $scheduled_changes_action_hook, array(), 'jjs-post-scheduler' );
	}
}

foreach ( $scheduled_changes_tables as $scheduled_changes_table ) {
	$wpdb->query( "DROP TABLE IF EXISTS `{$scheduled_changes_table}`" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
}
