<?php
/**
 * Page renderer for admin templates.
 *
 * @package MonitorCat\Admin
 */

declare(strict_types=1);

namespace MonitorCat\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * Renders admin pages using template files with an optional layout wrapper.
 */
final class PageRenderer {

	/**
	 * Currently rendered template name.
	 *
	 * @var string
	 */
	private string $current_template = '';

	/**
	 * Render a template wrapped in the admin layout.
	 *
	 * @param string               $template Template name relative to templates/ (without .php).
	 * @param array<string, mixed> $data     Variables to extract into template scope.
	 */
	public function render( string $template, array $data = array() ): void {
		$file_path = MONITORCAT_DIR . 'templates/' . $template . '.php';

		if ( ! file_exists( $file_path ) ) {
			wp_die(
				esc_html(
					sprintf(
						/* translators: %s: template file path */
						__( 'Template not found: %s', 'monitor-cat' ),
						$template
					)
				)
			);
		}

		$this->current_template = $template;

		// phpcs:ignore WordPress.PHP.DontExtract.extract_extract -- Controlled extraction with EXTR_SKIP.
		extract( $data, EXTR_SKIP );

		include MONITORCAT_DIR . 'templates/admin/layout.php';
	}

	/**
	 * Render a partial template without the layout wrapper.
	 *
	 * @param string               $template Template name relative to templates/ (without .php).
	 * @param array<string, mixed> $data     Variables to extract into template scope.
	 */
	public function partial( string $template, array $data = array() ): void {
		$file_path = MONITORCAT_DIR . 'templates/' . $template . '.php';

		if ( ! file_exists( $file_path ) ) {
			return;
		}

		// phpcs:ignore WordPress.PHP.DontExtract.extract_extract -- Controlled extraction with EXTR_SKIP.
		extract( $data, EXTR_SKIP );

		include $file_path;
	}

	/**
	 * Get the name of the currently rendered template.
	 *
	 * @return string Template name.
	 */
	public function get_current_template(): string {
		return $this->current_template;
	}
}
