<?php
namespace RemoveQueryStrings;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'remove-query-strings';
	private const MODULE_VERSION = '1.2.0';

	private ?string $site_host = null;

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

	public function getName(): string {
		return __( 'Remove Query Strings', 'wp-powersuite' );
	}

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

	public function getDescription(): string {
		return __( 'Removes version query parameters from local CSS and JS on the front end for leaner HTML. Does not strip other query args or third-party assets.', 'wp-powersuite' );
	}

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

	protected function registerHooks(): void {
		add_filter( 'script_loader_src', [ $this, 'removeVersionQueryArg' ], 15, 1 );
		add_filter( 'style_loader_src', [ $this, 'removeVersionQueryArg' ], 15, 1 );
	}

	public function removeVersionQueryArg( string $src ): string {
		if ( $src === '' || strpos( $src, 'ver=' ) === false ) {
			return $src;
		}

		if ( ! $this->isLocalStaticAssetUrl( $src ) ) {
			return $src;
		}

		return remove_query_arg( 'ver', $src );
	}

	private function isLocalStaticAssetUrl( string $src ): bool {
		$site_host = $this->getSiteHost();
		if ( $site_host === '' ) {
			return false;
		}

		$parts = wp_parse_url( $src );
		if ( ! is_array( $parts ) ) {
			return false;
		}

		if ( ! empty( $parts['host'] ) && strcasecmp( (string) $parts['host'], $site_host ) !== 0 ) {
			return false;
		}

		$path = isset( $parts['path'] ) ? (string) $parts['path'] : '';
		if ( $path === '' ) {
			return false;
		}

		$path_lower = strtolower( $path );

		return str_contains( $path_lower, 'wp-content' ) || str_contains( $path_lower, 'wp-includes' );
	}

	private function getSiteHost(): string {
		if ( $this->site_host !== null ) {
			return $this->site_host;
		}

		$host = wp_parse_url( home_url(), PHP_URL_HOST );

		return $this->site_host = is_string( $host ) ? $host : '';
	}
}
