<?php
/**
 * Shared request URI / path helpers for redirect and 404 modules.
 *
 * @package WP_PowerSuite\Core
 * @since 1.1.0
 */

namespace WP_PowerSuite\Core;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Normalizes paths and query strings from REQUEST_URI.
 */
final class RequestPathHelper {

	/**
	 * Extract the path component from a request URI.
	 */
	public static function pathFromRequestUri( string $request_uri ): string {
		if ( $request_uri === '' ) {
			return '';
		}

		$path = wp_parse_url( $request_uri, PHP_URL_PATH );
		if ( $path === null || $path === false ) {
			return $request_uri;
		}

		return $path;
	}

	/**
	 * Extract the query string from a request URI.
	 */
	public static function queryFromRequestUri( string $request_uri ): string {
		if ( $request_uri === '' ) {
			return '';
		}

		$query = wp_parse_url( $request_uri, PHP_URL_QUERY );

		return is_string( $query ) ? $query : '';
	}

	/**
	 * Path only, or path plus query when requested.
	 */
	public static function pathWithOptionalQuery( string $request_uri, bool $include_query ): string {
		$path = self::pathFromRequestUri( $request_uri );
		if ( $path === '' || ! $include_query ) {
			return $path;
		}

		$query = self::queryFromRequestUri( $request_uri );
		if ( $query === '' ) {
			return $path;
		}

		return $path . '?' . $query;
	}

	/**
	 * Append a query string to a URL when present.
	 */
	public static function appendQueryString( string $url, string $query ): string {
		if ( $query === '' ) {
			return $url;
		}

		return $url . ( str_contains( $url, '?' ) ? '&' : '?' ) . $query;
	}

	/**
	 * Strip the site home path prefix (subdirectory installs).
	 *
	 * Example: home at /shop, request /shop/old-page → /old-page.
	 */
	public static function stripHomePath( string $path ): string {
		$home_path = wp_parse_url( home_url( '/' ), PHP_URL_PATH );
		$home_path = is_string( $home_path ) ? rtrim( $home_path, '/' ) : '';

		$normalized = $path === '' ? '/' : $path;

		if ( $home_path === '' || $home_path === '/' ) {
			return $normalized;
		}

		if ( rtrim( $normalized, '/' ) === $home_path ) {
			return '/';
		}

		if ( str_starts_with( $normalized, $home_path . '/' ) ) {
			$stripped = substr( $normalized, strlen( $home_path ) );

			return $stripped === '' ? '/' : $stripped;
		}

		return $normalized;
	}
}
