<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Uninstall cleanup for QuantumCache.
 *
 * Drops plugin-owned tables and options per site.
 */

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

if ( apply_filters( 'quantumcache_preserve_data_on_uninstall', false ) ) {
	return;
}

/**
 * Drop QC tables and delete QC options for the CURRENT site.
 *
 * Notes:
 * - We derive table names from $wpdb->prefix and validate them (alnum + underscore)
 *   before interpolating into SQL.
 * - Direct schema changes during uninstall are intentional and safe here.
 *
 * @phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
 * @phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
 * @phpcs:disable WordPress.DB.DirectDatabaseQuery.SchemaChange
 * @phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
 */
function quantumcache_uninstall_current_site(): void {
	global $wpdb;

		$entries_raw = (string) $wpdb->prefix . 'qc_entries';
		$tagmap_raw  = (string) $wpdb->prefix . 'qc_tagmap';

	// Defensive: ensure identifiers are sane before interpolation.
	foreach ( array( $entries_raw, $tagmap_raw ) as $tbl ) {
		if ( 1 !== preg_match( '/^[A-Za-z0-9_]+$/', $tbl ) ) {
			// If the prefix looks odd, bail rather than attempting a DROP.
			return;
		}
	}
		// esc_sql() is used here to satisfy tooling; identifiers are still validated above.
		$entries = esc_sql( $entries_raw );
		$tagmap  = esc_sql( $tagmap_raw );
	$wpdb->query( "DROP TABLE IF EXISTS `{$entries}`" );
	$wpdb->query( "DROP TABLE IF EXISTS `{$tagmap}`" );

	foreach ( array(
		'quantumcache_auto_fragments',
		'quantumcache_debug_headers',
		'quantumcache_debug_markers',
		'quantumcache_store_mode',
		'quantumcache_redis_host',
		'quantumcache_redis_port',
		'quantumcache_redis_db',
		'quantumcache_query_ttl',
		'quantumcache_query_stale_ttl',
		'quantumcache_min_archive_ids',
		'quantumcache_fragment_ttl',
		'quantumcache_fragment_stale_ttl',
	) as $opt ) {
		delete_option( $opt );
	}
}
/** @phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery */
/** @phpcs:enable WordPress.DB.DirectDatabaseQuery.NoCaching */
/** @phpcs:enable WordPress.DB.DirectDatabaseQuery.SchemaChange */
/** @phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared */

if ( function_exists( 'is_multisite' ) && is_multisite() ) {
		$quantumcache_site_ids = get_sites( array( 'fields' => 'ids' ) );
	foreach ( $quantumcache_site_ids as $blog_id ) {

		switch_to_blog( (int) $blog_id );
		quantumcache_uninstall_current_site();
		restore_current_blog();
	}
} else {
	quantumcache_uninstall_current_site();
}
