<?php
/**
 * Shared guards for frontend 404 logging and catch-all redirects.
 *
 * @package WP_PowerSuite\Core
 * @since 1.1.0
 */

namespace WP_PowerSuite\Core;

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

/**
 * Determines when public 404 handlers should not run.
 */
final class FrontendRequestGuard {

	/**
	 * Skip 404 redirect/logging for non-page request contexts.
	 */
	public static function shouldSkipPublic404Action(): bool {
		if ( ( defined( 'DOING_AJAX' ) && DOING_AJAX )
			|| ( defined( 'REST_REQUEST' ) && REST_REQUEST )
			|| ( defined( 'DOING_CRON' ) && DOING_CRON )
			|| ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) ) {
			return true;
		}

		if ( function_exists( 'is_feed' ) && is_feed() ) {
			return true;
		}

		return false;
	}

	/**
	 * Skip 404 redirect/logging for system routes and static assets.
	 */
	public static function shouldSkip404Path( string $path ): bool {
		if ( $path === '' ) {
			return true;
		}

		if ( self::isStaticAssetPath( $path ) ) {
			return true;
		}

		/**
		 * Allow modules (e.g. Change Login URL) to opt paths out of catch-all 404 redirects/logging.
		 *
		 * @param bool   $skip Skip this path.
		 * @param string $path Request path (may include leading slash).
		 */
		if ( apply_filters( 'wp_powersuite_skip_404_path', false, $path ) ) {
			return true;
		}

		return self::isSystemPath( $path );
	}

	public static function isStaticAssetPath( string $path ): bool {
		return (bool) preg_match(
			'#\.(?:css|js|map|jpe?g|png|gif|svg|webp|avif|ico|woff2?|ttf|eot|pdf|zip|xml|json|txt|php\d?)(?:\?|$)#i',
			$path
		);
	}

	public static function isSystemPath( string $path ): bool {
		$lower = strtolower( $path );

		if ( $lower === '/robots.txt' || str_ends_with( $lower, '/robots.txt' ) ) {
			return true;
		}

		if ( str_contains( $lower, 'wp-sitemap' ) || preg_match( '#sitemap[^/]*\.xml#i', $path ) ) {
			return true;
		}

		if ( preg_match( '#/(feed|rdf|rss|rss2|atom)/?$#i', $path ) || str_ends_with( $lower, '/feed' ) ) {
			return true;
		}

		if ( str_contains( $lower, 'wp-login.php' ) || str_contains( $lower, 'wp-admin' ) ) {
			return true;
		}

		return false;
	}
}
