<?php
namespace DisableAutoEmbeds;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'disable-auto-embeds';
	private const MODULE_VERSION = '1.4.1';

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

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

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

	public function getDescription(): string {
		return __( 'Stop WordPress from auto-embedding links and loading extra embed code. Ideal when you want faster pages and you handle media and links yourself.', 'wp-powersuite' );
	}

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

	protected function registerHooks(): void {
		remove_shortcode( 'embed' );
		add_filter( 'rewrite_rules_array', [ $this, 'removeEmbedRewriteRules' ], 999 );
		add_filter( 'rest_endpoints', [ $this, 'removeOembedRestEndpoint' ], 10, 1 );
		add_filter( 'tiny_mce_plugins', [ $this, 'removeTinyMceEmbedPlugin' ] );

		if ( is_admin() ) {
			return;
		}

		global $wp;
		if ( ! empty( $wp ) && isset( $wp->public_query_vars ) && is_array( $wp->public_query_vars ) ) {
			$wp->public_query_vars = array_values( array_diff( $wp->public_query_vars, [ 'embed' ] ) );
		}

		remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
		remove_action( 'wp_head', 'wp_oembed_add_host_js' );
		add_filter( 'embed_oembed_discover', '__return_false' );
		add_action( 'wp_default_scripts', [ $this, 'removeWpEmbedScript' ], 999 );
	}

	/**
	 * Drop core wp-embed on the public site only.
	 *
	 * @param \WP_Scripts $scripts Scripts registry.
	 */
	public function removeWpEmbedScript( $scripts ): void {
		if ( $scripts instanceof \WP_Scripts ) {
			$scripts->remove( 'wp-embed' );
		}
	}

	/**
	 * @param array<int, string> $plugins TinyMCE plugin slugs.
	 * @return array<int, string>
	 */
	public function removeTinyMceEmbedPlugin( array $plugins ): array {
		if ( is_admin() ) {
			return $plugins;
		}

		return array_values( array_diff( $plugins, [ 'wpembed' ] ) );
	}

	/**
	 * Unregister public oEmbed route; keep it for authenticated editors.
	 *
	 * @param array<string, mixed> $endpoints Registered REST routes.
	 * @return array<string, mixed>
	 */
	public function removeOembedRestEndpoint( array $endpoints ): array {
		if ( $this->shouldAllowOembedRestAccess() ) {
			return $endpoints;
		}

		unset( $endpoints['/oembed/1.0/embed'] );

		return $endpoints;
	}

	public function removeEmbedRewriteRules( array $rules ): array {
		foreach ( $rules as $rule => $rewrite ) {
			$r  = (string) $rule;
			$rw = (string) $rewrite;
			if ( str_contains( $rw, 'embed=true' ) || str_contains( $r, 'embed=true' ) || str_contains( $r, '/embed/' ) ) {
				unset( $rules[ $rule ] );
			}
		}

		return $rules;
	}

	private function shouldAllowOembedRestAccess(): bool {
		return is_user_logged_in() && current_user_can( 'edit_posts' );
	}
}
