<?php

/**
 * Plugin glomex_oEmbed
 *
 * Fired when the plugin is uninstalled.
 *
 * When populating this file, consider the following flow
 * of control:
 *
 * - This method should be static
 * - Check if the $_REQUEST content actually is the plugin name
 * - Run an admin referrer check to make sure it goes through authentication
 * - Verify the output of $_GET makes sense
 * - Repeat with other user roles. Best directly by using the links/query string parameters.
 * - Repeat things for multisite. Once for a single site in the network, once sitewide.
 *
 * @package   glomex_oEmbed
 * @author    glomex <info@glomex.com>
 * @copyright 2022 glomex
 * @license   Apache-2.0
 * @link      https://glomex.com
 */

// If uninstall not called from WordPress, then exit.
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

if ( !defined( 'GLOMEX_OEMBED_PLUGIN_ROOT' ) ) {
	define( 'GLOMEX_OEMBED_PLUGIN_ROOT', plugin_dir_path( __FILE__ ) );
}

if ( !defined( 'GLOMEX_OEMBED_TEXTDOMAIN' ) ) {
	define( 'GLOMEX_OEMBED_TEXTDOMAIN', 'glomex-oembed' );
}

/**
 * Loop for uninstall
 *
 * @return void
 */
function glomex_oembed_uninstall_multisite() {
	if ( is_multisite() ) {
		/** @var array<\WP_Site> $blogs */
		$blogs = get_sites();

		if ( !empty( $blogs ) ) {
			foreach ( $blogs as $blog ) {
				switch_to_blog( (int) $blog->blog_id );
				glomex_oembed_uninstall();
				restore_current_blog();
			}

			return;
		}
	}

	glomex_oembed_uninstall();
}

/**
 * @return void
 */
function glomex_oembed_reset_pointers() {
	$pointers_list = array(
		GLOMEX_OEMBED_TEXTDOMAIN . '_glomex_oembed_to_plugin_settings',
		GLOMEX_OEMBED_TEXTDOMAIN . '_configure_structured_data',
		GLOMEX_OEMBED_TEXTDOMAIN . '_set_up_integration_id',
	);

	$users = get_users(
		array(
			// phpcs:ignore
			'meta_query' => array(
				array(
					'key'     => 'dismissed_wp_pointers',
					'compare' => 'EXISTS',
				),
			),
		)
	);

	if ( empty( $users ) ) {
		return;
	}

	foreach ( $users as $user ) {
		/**
		 * @var \WP_User $user
		 */
		$pointers = get_user_meta( $user->ID, 'dismissed_wp_pointers', true );

		if ( empty( $pointers ) ) {
			continue;
		}

		// @phpstan-ignore-next-line
		$pointers_arr = explode( ',', $pointers );
		$diff         = array_diff( $pointers_arr, $pointers_list );

		$result = '';

		if ( !empty( $diff ) ) {
			$result = implode( ',', $diff );
		}

		update_user_meta( $user->ID, 'dismissed_wp_pointers', $result );
	}
}

/**
 * What happens on uninstall?
 *
 * @global WP_Roles $wp_roles
 * @return void
 */
function glomex_oembed_uninstall() { // phpcs:ignore
	delete_option( GLOMEX_OEMBED_TEXTDOMAIN . '-settings' );
	glomex_oembed_reset_pointers();
}

glomex_oembed_uninstall_multisite();
