<?php
/**
 * OAuth URL helper (redirect URIs, safe redirects, validation).
 *
 * @package WP_PowerSuite\OAuth\Helpers
 */

namespace WP_PowerSuite\OAuth\Helpers;

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

/**
 * Central callback query parameter: ?wpps_auth=google|facebook|github
 */
final class UrlHelper {

	public const AUTH_QUERY_PARAM = 'wpps_auth';

	/**
	 * Public OAuth callback URL (register this in all providers).
	 */
	public static function callbackUrl( string $provider_slug, bool $is_legacy_admin_ajax = false, ?string $legacy_action = null ): string {
		$provider_slug = sanitize_key( $provider_slug );
		if ( $is_legacy_admin_ajax && $legacy_action ) {
			return add_query_arg( 'action', $legacy_action, admin_url( 'admin-ajax.php' ) );
		}
		return add_query_arg( self::AUTH_QUERY_PARAM, $provider_slug, home_url( '/' ) );
	}

	/**
	 * Validate post-login URL (no open redirect).
	 * If core rejects a URL, allow same-site URLs (fixes WooCommerce /my-account/... edge cases, http/https).
	 */
	public static function safeLoginRedirect( string $url, string $default ): string {
		$url = trim( $url );
		if ( $url === '' ) {
			return $default;
		}
		$validated = wp_validate_redirect( $url, false );
		if ( is_string( $validated ) && $validated !== '' ) {
			return $validated;
		}
		if ( self::isSameSiteUrl( $url ) ) {
			return esc_url_raw( $url );
		}
		return $default;
	}

	/**
	 * True if $url is under this site (path-relative to home, or same host as home/siteurl).
	 */
	public static function isSameSiteUrl( string $url ): bool {
		$url  = trim( $url );
		if ( $url === '' || ! str_starts_with( $url, 'http' ) ) {
			return false;
		}
		$u_host = wp_parse_url( $url, PHP_URL_HOST );
		if ( ! is_string( $u_host ) || $u_host === '' ) {
			return false;
		}
		$h = function ( $base ) use ( $u_host ): bool {
			$host = wp_parse_url( $base, PHP_URL_HOST );
			return is_string( $host ) && $host !== '' && strcasecmp( (string) $u_host, (string) $host ) === 0;
		};
		if ( $h( home_url( '/' ) ) || $h( site_url( '/' ) ) ) {
			return true;
		}
		$allowed = (array) apply_filters( 'wpps_allowed_oauth_redirect_hosts', [] );
		foreach ( $allowed as $host ) {
			$host = (string) $host;
			if ( $host !== '' && strcasecmp( $u_host, $host ) === 0 ) {
				return true;
			}
		}
		return false;
	}
}
