<?php
/**
 * Shared TutorHelper email placeholder handling.
 *
 * @package TutorHelper_Bookings
 */

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

/**
 * Safely replaces registered email placeholders.
 */
final class TutorHelper_Email_Placeholders {

	/**
	 * Replace allowed placeholders in template content.
	 *
	 * @param string $content      Template content.
	 * @param array  $values       Placeholder/value map.
	 * @param array  $allowed      Allowed placeholder names.
	 *
	 * @return string
	 */
	public static function replace(
		$content,
		$values,
		$allowed = array()
	) {
		$content =
			(string) $content;

		$values =
			is_array( $values )
				? $values
				: array();

		$allowed =
			is_array( $allowed )
				? $allowed
				: array();

		$replacements = array();

		foreach (
			$allowed
			as $placeholder
		) {
			$placeholder =
				trim(
					(string) $placeholder
				);

			if (
				! self::is_valid_placeholder(
					$placeholder
				)
			) {
				continue;
			}

			if (
				! array_key_exists(
					$placeholder,
					$values
				)
			) {
				continue;
			}

			$replacements[
				$placeholder
			] =
				self::normalise_value(
					$values[
						$placeholder
					]
				);
		}

		return strtr(
			$content,
			$replacements
		);
	}

	/**
	 * Add shared TutorHelper placeholder values.
	 *
	 * Module-specific values remain the responsibility of the module.
	 *
	 * @param array $values Existing values.
	 *
	 * @return array
	 */
	public static function add_shared_values(
		$values
	) {
		$values =
			is_array( $values )
				? $values
				: array();

		if (
			! array_key_exists(
				'{site_name}',
				$values
			)
		) {
			$values[
				'{site_name}'
			] =
				wp_specialchars_decode(
					get_bloginfo( 'name' ),
					ENT_QUOTES
				);
		}

		return $values;
	}

	/**
	 * Determine whether a placeholder name is valid.
	 *
	 * @param string $placeholder Placeholder name.
	 *
	 * @return bool
	 */
	private static function is_valid_placeholder(
		$placeholder
	) {
		return 1 === preg_match(
			'/^\{[a-z0-9_]+\}$/',
			(string) $placeholder
		);
	}

	/**
	 * Convert a placeholder value to safe plain text.
	 *
	 * @param mixed $value Raw value.
	 *
	 * @return string
	 */
	private static function normalise_value(
		$value
	) {
		if (
			is_scalar( $value )
			|| null === $value
		) {
			return (string) $value;
		}

		return '';
	}
}
