<?php
namespace Bookaro\Utils;

defined('ABSPATH') || exit;

/**
 * Utility class for loading template files.
 */
class TemplateLoader
{
    /**
     * Render a template located under includes/src/templates.
     *
     * @param string $relative Relative path inside the templates directory.
     * @param array  $vars     Variables to extract into the template scope.
     */
    public static function render(string $relative, array $vars = []): void
    {
        $file = bookaro_locate_template('templates/' . ltrim($relative, '/'));
        if ($file && file_exists($file)) {
            extract($vars, EXTR_SKIP); // phpcs:ignore WordPress.PHP.DontExtract.extract_extract -- Controlled view-var array: keys are developer-defined template variables (not user input), and EXTR_SKIP prevents clobbering any existing variable.
            include $file;
        }
    }

    /**
     * Capture a template output into a string.
     *
     * @param string $relative Relative path inside the templates directory.
     * @param array  $vars     Variables to extract into the template scope.
     * @return string Rendered template contents or empty string on failure.
     */
    public static function capture(string $relative, array $vars = []): string
    {
        ob_start();
        self::render($relative, $vars);
        return (string) ob_get_clean();
    }
}

