<?php
/**
 * Validates outbound / sideload URLs for admin import flows.
 *
 * @package WP_PowerSuite\Core
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core;

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

final class RemoteUrlValidator {

	/**
	 * Allow HTTP/HTTPS URLs whose host matches this WordPress site.
	 */
	public static function isSameSiteUrl( string $url ): bool {
		$url = trim( $url );
		if ( $url === '' || ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
			return false;
		}

		$parts = wp_parse_url( $url );
		if ( ! is_array( $parts ) || empty( $parts['scheme'] ) || empty( $parts['host'] ) ) {
			return false;
		}

		$scheme = strtolower( (string) $parts['scheme'] );
		if ( ! in_array( $scheme, [ 'http', 'https' ], true ) ) {
			return false;
		}

		$host = strtolower( (string) $parts['host'] );
		if ( $host === 'localhost' || $host === '127.0.0.1' || $host === '::1' ) {
			return false;
		}

		$site_host = strtolower( (string) wp_parse_url( home_url( '/' ), PHP_URL_HOST ) );
		if ( $site_host === '' || $host !== $site_host ) {
			return false;
		}

		/**
		 * Filter same-site URL validation for import/sideload helpers.
		 *
		 * @since 1.0.0
		 * @param bool   $allowed Whether the URL is allowed.
		 * @param string $url     Requested URL.
		 */
		return (bool) apply_filters( 'wp_powersuite_remote_url_is_same_site', true, $url );
	}
}
