<?php
/**
 * NotFound fallback decision resolver.
 *
 * @package SEOvaultSEO\NotFound
 */

namespace SEOvaultSEO\NotFound;

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

/**
 * Decides theme / home / custom fallback for unmatched 404s.
 */
class FallbackResolver {

	/**
	 * No-op initializer retained for the module's common class interface.
	 */
	public static function init() {
	}

	/**
	 * Resolve the fallback action for a request without performing a redirect.
	 *
	 * Supported option keys are mode, status, custom_url, custom_page_id, and
	 * request_uri. A valid custom page takes precedence over custom_url.
	 *
	 * @param bool  $is_404                Whether the request is a 404.
	 * @param bool  $redirect_rule_matched Whether Redirect Manager already matched.
	 * @param array $options                Fallback and request options.
	 * @return array{action:string,url:string,status:int}
	 */
	public static function resolve( $is_404, $redirect_rule_matched, array $options = array() ) {
		if ( ! $is_404 || $redirect_rule_matched ) {
			return self::none();
		}

		$mode = Sanitizer::sanitize_fallback_mode( $options['mode'] ?? 'theme' );
		if ( 'theme' === $mode ) {
			return self::none();
		}

		$request_uri = isset( $options['request_uri'] ) && is_string( $options['request_uri'] )
			? $options['request_uri']
			: '';

		if ( self::is_excluded_request( $request_uri ) ) {
			return self::none();
		}

		$status = Sanitizer::sanitize_fallback_status( $options['status'] ?? 302 );

		if ( 'home' === $mode ) {
			return self::redirect_decision( 'redirect_home', home_url(), $status );
		}

		$url     = '';
		$page_id = isset( $options['custom_page_id'] ) ? absint( $options['custom_page_id'] ) : 0;

		if ( $page_id && Sanitizer::is_published_page( $page_id ) ) {
			$permalink = get_permalink( $page_id );
			$url       = is_string( $permalink ) ? $permalink : '';
		}

		// A stale/deleted page selection safely falls back to the configured URL.
		if ( '' === $url ) {
			$url = Sanitizer::sanitize_custom_url( $options['custom_url'] ?? '' );
		}

		if ( '' === $url ) {
			return self::none();
		}

		return self::redirect_decision( 'redirect_custom', $url, $status );
	}

	/**
	 * Build a no-action decision.
	 *
	 * @return array{action:string,url:string,status:int}
	 */
	private static function none() {
		return array(
			'action' => 'none',
			'url'    => '',
			'status' => 0,
		);
	}

	/**
	 * Build a redirect decision.
	 *
	 * @param string $action Action name.
	 * @param string $url    Redirect target.
	 * @param int    $status HTTP status code.
	 * @return array{action:string,url:string,status:int}
	 */
	private static function redirect_decision( $action, $url, $status ) {
		return array(
			'action' => $action,
			'url'    => $url,
			'status' => $status,
		);
	}

	/**
	 * Check whether the request path should bypass fallback redirects.
	 *
	 * @param string $request_uri Request URI or absolute request URL.
	 * @return bool
	 */
	private static function is_excluded_request( $request_uri ) {
		$path = self::normalize_request_path( $request_uri );
		if ( '' === $path ) {
			return false;
		}

		$excluded_paths = array(
			'login',
			'admin',
			'dashboard',
			'wp-login.php',
			'wp-admin',
		);

		/**
		 * Filter paths that must retain WordPress's normal 404/canonical handling.
		 *
		 * @param array<int, string> $excluded_paths Excluded relative paths.
		 * @param string             $path           Normalized request path.
		 */
		$excluded_paths = apply_filters(
			'seovaultseo_notfound_fallback_excluded_paths',
			$excluded_paths,
			$path
		);

		if ( ! is_array( $excluded_paths ) ) {
			return false;
		}

		foreach ( $excluded_paths as $excluded_path ) {
			if ( ! is_string( $excluded_path ) ) {
				continue;
			}

			$excluded_path = trim( self::normalize_request_path( $excluded_path ), '/' );
			if (
				'' !== $excluded_path &&
				( $path === $excluded_path || 0 === strpos( $path, $excluded_path . '/' ) )
			) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Normalize a URI to a home-relative path without query parameters.
	 *
	 * @param string $request_uri Request URI or absolute request URL.
	 * @return string
	 */
	private static function normalize_request_path( $request_uri ) {
		if ( '' === $request_uri ) {
			return '';
		}

		$path = wp_parse_url( $request_uri, PHP_URL_PATH );
		if ( ! is_string( $path ) ) {
			return '';
		}

		$home_path = wp_parse_url( home_url( '/' ), PHP_URL_PATH );
		$home_path = is_string( $home_path ) ? trim( $home_path, '/' ) : '';
		$path      = trim( $path, '/' );

		if ( '' !== $home_path && ( $path === $home_path || 0 === strpos( $path, $home_path . '/' ) ) ) {
			$path = ltrim( substr( $path, strlen( $home_path ) ), '/' );
		}

		return $path;
	}
}
