<?php
/**
 * WordPress head cleanup optimizer.
 *
 * Removes unnecessary bloat from wp_head output: emoji scripts,
 * version meta tag, RSD, WLW, shortlinks, and REST API discovery.
 *
 * @package MonitorCat\Modules\Speed\Optimizer
 */

declare(strict_types=1);

namespace MonitorCat\Modules\Speed\Optimizer;

defined( 'ABSPATH' ) || exit;

use MonitorCat\Settings;

/**
 * Cleans up wp_head output by removing unnecessary tags and scripts.
 */
final class WPHeadOptimizer {

	/**
	 * Plugin settings.
	 *
	 * @var Settings
	 */
	private Settings $settings;

	/**
	 * Constructor.
	 *
	 * @param Settings $settings Plugin settings.
	 */
	public function __construct( Settings $settings ) {
		$this->settings = $settings;
	}

	/**
	 * Register hooks if the optimization is enabled.
	 */
	public function boot(): void {
		if ( ! $this->settings->get( 'speed.optimize_head_cleanup', true ) ) {
			return;
		}

		// Remove WordPress emoji scripts and styles.
		remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
		remove_action( 'wp_print_styles', 'print_emoji_styles' );
		remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
		remove_action( 'admin_print_styles', 'print_emoji_styles' );
		add_filter( 'wp_resource_hints', array( $this, 'remove_emoji_dns_prefetch' ), 10, 2 );
		add_filter( 'emoji_svg_url', '__return_false' );

		// Remove WordPress version meta tag.
		remove_action( 'wp_head', 'wp_generator' );

		// Remove RSD (Really Simple Discovery) link.
		remove_action( 'wp_head', 'rsd_link' );

		// Remove Windows Live Writer manifest link.
		remove_action( 'wp_head', 'wlwmanifest_link' );

		// Remove shortlink.
		remove_action( 'wp_head', 'wp_shortlink_wp_head', 10 );

		// Remove REST API link from head (API is still accessible).
		remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );

		// Remove oEmbed discovery links.
		remove_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 );

		// Disable self-pingbacks.
		add_action( 'pre_ping', array( $this, 'disable_self_pingbacks' ) );
	}

	/**
	 * Remove the emoji CDN from DNS prefetch hints.
	 *
	 * @param string[] $urls          Array of hint URLs.
	 * @param string   $relation_type The relation type (e.g. 'dns-prefetch').
	 * @return string[] Filtered URLs.
	 */
	public function remove_emoji_dns_prefetch( array $urls, string $relation_type ): array {
		if ( 'dns-prefetch' !== $relation_type ) {
			return $urls;
		}

		return array_filter(
			$urls,
			static function ( $url ): bool {
				return false === strpos( (string) $url, 'wp.org/images/core/emoji' );
			}
		);
	}

	/**
	 * Prevent WordPress from pinging its own URLs.
	 *
	 * @param string[] $links Array of URLs to ping.
	 */
	public function disable_self_pingbacks( array &$links ): void {
		$home_url = home_url();

		foreach ( $links as $key => $link ) {
			if ( str_starts_with( (string) $link, $home_url ) ) {
				unset( $links[ $key ] );
			}
		}
	}
}
