<?php
/**
 * Uninstall cleanup for the Wohno plugin.
 *
 * Runs only when the user deletes the plugin via the WordPress admin. Removes
 * the plugin's options and cached transients (multisite-aware).
 *
 * @package Wohno\Plugin
 */

declare(strict_types=1);

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

/**
 * Delete the plugin's options and listing transients for the current site.
 *
 * @return void
 */
function wohno_uninstall_cleanup(): void {
	global $wpdb;

	$wohno_options = array(
		'wohno_api_key',
		'wohno_cache_ver',
		'wohno_contract_mismatch',
		'wohno_known_queries',
		'wohno_default_layout',
		'wohno_default_columns',
		'wohno_accent_color',
		'wohno_card_radius',
		'wohno_show_attribution',
		'wohno_installed_at',
		'wohno_review_dismissed',
	);
	foreach ( $wohno_options as $wohno_option ) {
		delete_option( $wohno_option );
	}
	delete_transient( 'wohno_test_result' );

	// Remove any leftover scheduled events.
	wp_clear_scheduled_hook( 'wohno_prewarm' );
	wp_clear_scheduled_hook( 'wohno_refresh_query' );
	wp_clear_scheduled_hook( 'wohno_refresh_listing' );

	// Remove namespaced listing transients (+ their timeouts) — covers both the
	// collection (`wohno_listings_`) and single-listing (`wohno_listing_`) caches.
	// Direct query is the standard approach in uninstall routines.
	$like    = $wpdb->esc_like( '_transient_wohno_listing' ) . '%';
	$like_to = $wpdb->esc_like( '_transient_timeout_wohno_listing' ) . '%';
	// phpcs:disable WordPress.DB.DirectDatabaseQuery
	$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $like ) );
	$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $like_to ) );
	// phpcs:enable WordPress.DB.DirectDatabaseQuery
}

if ( is_multisite() ) {
	$wohno_site_ids = get_sites( array( 'fields' => 'ids' ) );
	foreach ( $wohno_site_ids as $wohno_site_id ) {
		switch_to_blog( (int) $wohno_site_id );
		wohno_uninstall_cleanup();
		restore_current_blog();
	}
} else {
	wohno_uninstall_cleanup();
}
