<?php
/**
 * Sequensy Uninstall
 *
 * Fired when the plugin is uninstalled (deleted) from WordPress.
 * Cleans up all plugin data including database tables, options, transients,
 * scheduled cron events, and Action Scheduler jobs.
 *
 * @package Sequensy
 */

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

global $wpdb;

// Drop custom tables.
$sequensy_tables = [
	$wpdb->prefix . 'sequensy_workflows',
	$wpdb->prefix . 'sequensy_workflow_meta',
	$wpdb->prefix . 'sequensy_activity_log',
	$wpdb->prefix . 'sequensy_workflow_executions',
	$wpdb->prefix . 'sequensy_workflow_versions',
];

foreach ( $sequensy_tables as $sequensy_table ) {
	// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- Dropping plugin tables on uninstall.
	$wpdb->query( "DROP TABLE IF EXISTS {$sequensy_table}" );
}

// Delete known options.
delete_option( 'sequensy_settings' );
delete_option( 'sequensy_installed_packages' );
delete_option( 'sequensy_async_execution' );

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Bulk cleanup on uninstall requires direct queries.

// Delete wildcard options (integration connections, circuit breaker state).
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'sequensy\_integration\_connections\_%'" ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_option_name
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'sequensy\_circuit\_%'" ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_option_name

// Delete transients (both value and timeout entries).
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_sequensy\_%'" ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_option_name
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_timeout\_sequensy\_%'" ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_option_name

// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

// Clear scheduled cron events.
wp_clear_scheduled_hook( 'sequensy_cleanup' );

// Unschedule all pending Action Scheduler jobs.
if ( function_exists( 'as_unschedule_all_actions' ) ) {
	as_unschedule_all_actions( 'sequensy_execute_action' );
}
