<?php
/**
 * Keep in sync with NeurogenesisTheme\Core\Admin\Actions\PortableInternalNavigation (expand side only).
 *
 * @package ThemeExport
 */

defined( 'ABSPATH' ) || exit;

class NeurogenesisThemePortableNavPlaceholders {

	public const HOME_TOKEN      = '[NEURO_HOME]';
	public const PAGE_PREFIX     = '[NEURO_PAGE_URI:';
	public const PAGE_SUFFIX     = ']';
	public const POST_PREFIX     = '[NEURO_POST_URI:';
	public const POST_SUFFIX     = ']';

	/**
	 * @param array<string, string> $page_uri_to_permalink
	 * @param array<string, string> $post_slug_to_permalink
	 */
	public static function expand( string $content, array $page_uri_to_permalink, array $post_slug_to_permalink = array() ): string {
		if ( '' === $content || false === strpos( $content, '[NEURO_' ) ) {
			return $content;
		}

		$home_url = home_url( '/' );
		if ( false !== strpos( $content, self::HOME_TOKEN ) ) {
			$content = str_replace( self::HOME_TOKEN, self::permalink_json_escape( $home_url ), $content );
		}

		if ( ! empty( $post_slug_to_permalink ) ) {
			$slugs = array_keys( $post_slug_to_permalink );
			usort(
				$slugs,
				static function ( $a, $b ) {
					return strlen( (string) $b ) <=> strlen( (string) $a );
				}
			);
			foreach ( $slugs as $slug ) {
				$url = isset( $post_slug_to_permalink[ $slug ] ) ? (string) $post_slug_to_permalink[ $slug ] : '';
				if ( '' === $url ) {
					continue;
				}
				$content = str_replace(
					self::POST_PREFIX . $slug . self::POST_SUFFIX,
					self::permalink_json_escape( $url ),
					$content
				);
			}
		}

		if ( ! empty( $page_uri_to_permalink ) ) {
			$uris = array_keys( $page_uri_to_permalink );
			usort(
				$uris,
				static function ( $a, $b ) {
					return strlen( (string) $b ) <=> strlen( (string) $a );
				}
			);
			foreach ( $uris as $uri ) {
				$url = isset( $page_uri_to_permalink[ $uri ] ) ? (string) $page_uri_to_permalink[ $uri ] : '';
				if ( '' === $url ) {
					continue;
				}
				$content = str_replace(
					self::PAGE_PREFIX . $uri . self::PAGE_SUFFIX,
					self::permalink_json_escape( $url ),
					$content
				);
			}
		}

		return $content;
	}

	private static function permalink_json_escape( string $url ): string {
		$url = str_replace( '\\', '\\\\', $url );
		return str_replace( '"', '\\"', $url );
	}
}
