<?php

namespace HideWpVersion;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'hide-wp-version';
	private const MODULE_VERSION = '1.2.0';

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

	public function getName(): string {
		return __( 'Hide WP Version', 'wp-powersuite' );
	}

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

	public function getDescription(): string {
		return __( 'Removes WordPress version from public HTML generator tags, feed generator output, and the admin footer. Does not change ver= on script and style URLs.', 'wp-powersuite' );
	}

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

	protected function registerHooks(): void {
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
			return;
		}

		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
			return;
		}

		// No feeds, wp_head, or admin footer markup in REST responses.
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return;
		}

		if ( is_admin() ) {
			// admin-filters.php loads after plugins_loaded; unhook on admin_init.
			add_action( 'admin_init', [ $this, 'removeCoreUpdateFooter' ], 0 );
			return;
		}

		remove_action( 'wp_head', 'wp_generator' );
		add_filter( 'the_generator', [ $this, 'stripWpGeneratorTag' ], 10, 2 );
	}

	/**
	 * Remove WordPress version string from the admin footer without blanking other footer content.
	 */
	public function removeCoreUpdateFooter(): void {
		remove_filter( 'update_footer', 'core_update_footer' );
	}

	/**
	 * Strip WordPress.org generator markup for feeds and exports (preserves unrelated generator strings).
	 *
	 * @param mixed $generator Output passed through {@see 'the_generator'}.
	 */
	public function stripWpGeneratorTag( $generator, string $type ): mixed {
		if ( ! is_string( $generator ) || $generator === '' ) {
			return $generator;
		}

		// RSS 2.0 — <generator>https://wordpress.org/?v=x.y.z</generator>
		if ( str_contains( $generator, '<generator>https://wordpress.org/?v=' ) ) {
			return '';
		}

		// Atom — <generator uri="https://wordpress.org/" version="x.y.z">WordPress</generator>
		if ( str_contains( $generator, '<generator uri="https://wordpress.org/"' ) ) {
			return '';
		}

		// RDF / RSS 1.0 — admin:generatorAgent pointing at wordpress.org/?v=
		if ( str_contains( $generator, 'admin:generatorAgent' ) && str_contains( $generator, 'wordpress.org/?v=' ) ) {
			return '';
		}

		// Export WXR and legacy comment feeds — <!-- generator="WordPress/x.y.z" -->
		if ( str_contains( $generator, 'generator="WordPress/' ) ) {
			return '';
		}

		return $generator;
	}
}
