<?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase, WordPress.Files.FileName.InvalidClassFileName
/**
 * WordPress implementation of the Template Renderer.
 *
 * @package Autoship
 * @subpackage Templates
 * @since 2.13.0
 */

namespace Autoship\Services\Templates\Implementations;

use Autoship\Services\Templates\TemplateRendererInterface;

/**
 * WordPress implementation of the Template Renderer.
 *
 * Resolves a logical template name by first looking in the active
 * theme's `autoship-cloud/templates/` directory (filterable via
 * `autoship_theme_template`) and falling back to the plugin's bundled
 * template (filterable via `autoship_plugin_template`). Variables in
 * `$vars` are exposed to the template via PHP `extract()` so existing
 * template files referencing them by name continue to work.
 *
 * @package Autoship
 * @subpackage Templates
 * @since 2.13.0
 */
class WordPressTemplateRenderer implements TemplateRendererInterface {

	/**
	 * Render a template, with theme override support.
	 *
	 * @param string               $template Logical template name (e.g.
	 *                                       `scheduled-orders/snooze-form-template`).
	 * @param array<string, mixed> $vars     Variables to expose to the template.
	 *
	 * @return void
	 */
	public function render( string $template, array $vars = array() ): void {
		// phpcs:ignore WordPress.PHP.DontExtract.extract_extract
		extract( $vars );

		// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
		$theme_template = apply_filters(
			'autoship_theme_template',
			get_stylesheet_directory() . '/' . Autoship_Plugin_Folder_Name . '/templates/' . $template . '.php',
			$template,
			$vars
		);

		if ( file_exists( $theme_template ) ) {
			include $theme_template;
			return;
		}

		// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
		$plugin_template = apply_filters(
			'autoship_plugin_template',
			Autoship_Plugin_Dir . '/templates/' . $template . '.php',
			$template,
			$vars
		);

		include $plugin_template;
	}
}
