<?php
namespace DisableEmojis;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'disable-emojis';
	private const MODULE_VERSION = '1.3.1';

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Disable WordPress Emojis', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Uses the visitor’s device for emoji instead of WordPress’s add-on scripts, so pages start a bit faster.', 'wp-powersuite' );
	}

	public function getContext(): array {
		return [ 'admin', 'frontend' ];
	}

	protected function registerHooks(): void {
		remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
		remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
		remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
		add_filter( 'emoji_svg_url', '__return_false' );
		add_filter( 'wp_resource_hints', [ $this, 'removeEmojiDnsPrefetch' ], 10, 2 );

		if ( is_admin() ) {
			return;
		}

		remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
		remove_action( 'wp_print_styles', 'print_emoji_styles' );
		if ( function_exists( 'wp_enqueue_emoji_styles' ) ) {
			remove_action( 'wp_enqueue_scripts', 'wp_enqueue_emoji_styles' );
		}
	}

	/**
	 * @param array<int, string>|array<string, string> $urls URLs to print for resource hints.
	 * @return array<int, string>|array<string, string>
	 */
	public function removeEmojiDnsPrefetch( array $urls, string $relation_type ): array {
		if ( $relation_type !== 'dns-prefetch' || $urls === [] ) {
			return $urls;
		}

		$emoji_base = 'https://s.w.org/images/core/emoji/';
		foreach ( $urls as $key => $url ) {
			if ( is_string( $url ) && str_contains( $url, $emoji_base ) ) {
				unset( $urls[ $key ] );
			}
		}

		return $urls;
	}
}
