<?php
/**
 * Uninstall — Clean removal of all CapiFlow plugin data.
 *
 * Runs ONLY when the plugin is completely deleted via WordPress admin
 * (not on deactivation). User data is preserved by default — use
 * capiflow_keep_data_on_uninstall option to control this.
 *
 * @package CapiFlow
 */

// WordPress security check — prevents direct execution.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	die;
}

global $wpdb;

// Respect user's data retention preference (default: keep data).
// Administrators can set this to false in Advanced settings.
$capiflow_keep_data = get_option( 'capiflow_keep_data_on_uninstall', true );

if ( $capiflow_keep_data ) {
	// User wants to keep data — only clean up transients (not persistent data).
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( $wpdb->prepare(
		"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
		$wpdb->esc_like( '_transient_capiflow_' ) . '%',
		$wpdb->esc_like( '_transient_timeout_capiflow_' ) . '%'
	) );

	// Unschedule AS tasks (so they don't fire for a deleted plugin).
	if ( function_exists( 'as_unschedule_all_actions' ) ) {
		foreach ( array(
			'capiflow_process_queue',
			'capiflow_daily_maintenance',
			'capiflow_scan_abandoned_carts',
			'capiflow_fetch_dataset_quality',
			'capiflow_record_purchase_analytics',
		) as $capiflow_hook ) {
			as_unschedule_all_actions( $capiflow_hook );
		}
	}

	wp_cache_flush();
	return; // Exit — preserve all other data.
}

// ─────────────────────────────────────────────────────────────────────────
// Full cleanup — user opted to remove all data.
// ─────────────────────────────────────────────────────────────────────────

// ── Remove all capiflow_ plugin options ──────────────────────────────────
$capiflow_options = $wpdb->get_col( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
	$wpdb->esc_like( 'capiflow_' ) . '%'
) );
foreach ( $capiflow_options as $capiflow_option ) {
	delete_option( $capiflow_option );
}

// ── Remove all capiflow_ transients ──────────────────────────────────────
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query( $wpdb->prepare(
	"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
	$wpdb->esc_like( '_transient_capiflow_' ) . '%',
	$wpdb->esc_like( '_transient_timeout_capiflow_' ) . '%'
) );

// ── Drop Core custom tables ───────────────────────────────────────────────
// phpcs:disable WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'capiflow_events' ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'capiflow_analytics' ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

// Also drop old (renamed) tables if still exists (migration safety net).
$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'woo_capi_events' ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
// phpcs:enable

// ── Remove order meta (HPOS-compatible) ──────────────────────────────────
$capiflow_hpos_meta_table = $wpdb->prefix . 'wc_orders_meta';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $capiflow_hpos_meta_table ) ) === $capiflow_hpos_meta_table ) {
	$wpdb->query( $wpdb->prepare( "DELETE FROM {$capiflow_hpos_meta_table} WHERE meta_key LIKE %s", '_capiflow_%' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
}

// Legacy CPT order meta.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query( $wpdb->prepare(
	"DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s",
	$wpdb->esc_like( '_capiflow_' ) . '%'
) );

// ── Remove log files ─────────────────────────────────────────────────────
$capiflow_upload_dir = wp_upload_dir();
$capiflow_log_dir    = trailingslashit( $capiflow_upload_dir['basedir'] ) . 'capiflow-logs/';

if ( is_dir( $capiflow_log_dir ) ) {
	$capiflow_files = glob( $capiflow_log_dir . '*' );
	if ( is_array( $capiflow_files ) ) {
		foreach ( $capiflow_files as $capiflow_file ) {
			if ( is_file( $capiflow_file ) ) {
				wp_delete_file( $capiflow_file );
			}
		}
	}
	rmdir( $capiflow_log_dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
}

// ── Unschedule all Action Scheduler tasks ────────────────────────────────
if ( function_exists( 'as_unschedule_all_actions' ) ) {
	foreach ( array(
		'capiflow_process_queue',
		'capiflow_daily_maintenance',
		'capiflow_scan_abandoned_carts',
		'capiflow_fetch_dataset_quality',
		'capiflow_record_purchase_analytics',
	) as $capiflow_hook ) {
		as_unschedule_all_actions( $capiflow_hook );
	}
}

// ── Allow Pro plugin to clean up its own data ────────────────────────────
// Pro plugin uses: add_action('capiflow_uninstall', [$proClass, 'cleanup']);
do_action( 'capiflow_uninstall' );

// ── Clear object cache ───────────────────────────────────────────────────
wp_cache_flush();
