<?php
/**
 * Uninstall routine.
 *
 * Data is removed only when the site owner explicitly opted in through the
 * "Delete data on uninstall" setting, which is off by default.
 *
 * @package MenuVerse
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

/**
 * Removes every trace of MenuVerse from the current site.
 *
 * @return void
 */
function menuverse_uninstall_site() {
	$settings = get_option( 'menuverse_settings', array() );

	if ( ! is_array( $settings ) || empty( $settings['global']['delete_data_on_uninstall'] ) ) {
		return;
	}

	global $wpdb;

	delete_option( 'menuverse_settings' );
	delete_option( 'menuverse_state' );

	/*
	 * Per menu item extras. One bulk delete at uninstall time: WordPress has no
	 * API for removing a meta key across every post, and nothing is cached
	 * because the site is losing this data permanently.
	 */
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key
	$wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_menuverse_item' ) );

	// Mega menu panels stored as a private post type.
	$panels = get_posts(
		array(
			'post_type'      => 'menuverse_panel',
			'post_status'    => 'any',
			'posts_per_page' => -1,
			'fields'         => 'ids',
			'no_found_rows'  => true,
		)
	);

	foreach ( $panels as $panel_id ) {
		wp_delete_post( $panel_id, true );
	}

	// Capabilities.
	$roles = wp_roles();

	foreach ( array_keys( $roles->roles ) as $role_name ) {
		$role = get_role( $role_name );

		if ( $role instanceof WP_Role ) {
			$role->remove_cap( 'menuverse_manage' );
		}
	}

	wp_clear_scheduled_hook( 'menuverse_cleanup_panels' );
}

if ( is_multisite() ) {
	$menuverse_site_ids = get_sites(
		array(
			'fields'   => 'ids',
			'number'   => 0,
			'spam'     => 0,
			'deleted'  => 0,
			'archived' => 0,
		)
	);

	foreach ( $menuverse_site_ids as $menuverse_site_id ) {
		switch_to_blog( $menuverse_site_id );
		menuverse_uninstall_site();
		restore_current_blog();
	}

	unset( $menuverse_site_ids, $menuverse_site_id );
} else {
	menuverse_uninstall_site();
}
