<?php
/**
 * Uninstall routine for the F12 Floating Menu plugin.
 *
 * Removes all data created by the plugin: the global settings option,
 * every floating_menu post (including its meta), and orphaned theme mods.
 *
 * @package F12_Floating_Menu
 */

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

/**
 * Remove all plugin data for a single site.
 *
 * @return void
 */
function f12_floating_menu_uninstall_site(): void {
	// 1. Global settings option.
	delete_option( 'f12_floating_menu_settings' );

	// 2. All floating_menu posts + their meta, and orphaned theme mods.
	$menu_ids = get_posts( array(
		'post_type'        => 'floating_menu',
		'numberposts'      => -1,
		'post_status'      => 'any',
		'fields'           => 'ids',
		'suppress_filters' => true,
	) );

	foreach ( $menu_ids as $menu_id ) {
		$post = get_post( $menu_id );

		// Remove theme mods written per menu (prefixed with the post slug).
		if ( $post && ! empty( $post->post_name ) ) {
			$prefix    = $post->post_name . '_';
			$theme_mods = get_theme_mods();

			if ( is_array( $theme_mods ) ) {
				foreach ( array_keys( $theme_mods ) as $mod_key ) {
					if ( 0 === strpos( (string) $mod_key, $prefix ) ) {
						remove_theme_mod( $mod_key );
					}
				}
			}
		}

		// force-delete removes post meta (_floating_links, _floating_settings) too.
		wp_delete_post( $menu_id, true );
	}
}

// Run cleanup, multisite-aware.
if ( is_multisite() ) {
	$site_ids = get_sites( array( 'fields' => 'ids' ) );

	foreach ( $site_ids as $site_id ) {
		switch_to_blog( $site_id );
		f12_floating_menu_uninstall_site();
		restore_current_blog();
	}
} else {
	f12_floating_menu_uninstall_site();
}
