<?php
/**
 * Replace {{site.*}} tokens inside template documents.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Templates;


use AuraBuilder\Support\Json;
final class TemplateTokens {

	/**
	 * @return array<string, string>
	 */
	public static function map(): array {
		$logo = '';
		if ( function_exists( 'has_custom_logo' ) && has_custom_logo() ) {
			$logo_id = (int) get_theme_mod( 'custom_logo' );
			if ( $logo_id ) {
				$url = wp_get_attachment_image_url( $logo_id, 'medium' );
				if ( is_string( $url ) ) {
					$logo = $url;
				}
			}
		}
		return array(
			'{{site.name}}'     => (string) get_bloginfo( 'name' ),
			'{{site.tagline}}'  => (string) get_bloginfo( 'description' ),
			'{{site.home}}'     => (string) home_url( '/' ),
			'{{site.logo}}'     => $logo,
			'{{site.email}}'    => (string) get_bloginfo( 'admin_email' ),
		);
	}

	/**
	 * @param array<string, mixed> $data
	 * @return array<string, mixed>
	 */
	public static function apply( array $data ): array {
		$json = Json::encode( $data, '' );
		if ( ! is_string( $json ) ) {
			return $data;
		}
		$map = self::map();
		$json = str_replace( array_keys( $map ), array_values( $map ), $json );
		$out  = json_decode( $json, true );
		return is_array( $out ) ? $out : $data;
	}
}
