<?php

declare(strict_types=1);

namespace App\Core;

use RuntimeException;

/**
 * Moteur de gabarits PHP simple, avec layout optionnel.
 * Les templates vivent dans `/templates` et reçoivent les données par extraction.
 */
final class View
{
    /** @param array<string,mixed> $data */
    public static function render(string $template, array $data = [], ?string $layout = 'layouts/base'): string
    {
        $content = self::renderFile($template, $data);

        if ($layout !== null) {
            $content = self::renderFile($layout, array_merge($data, ['content' => $content]));
        }

        return $content;
    }

    /** @param array<string,mixed> $data */
    private static function renderFile(string $template, array $data): string
    {
        $file = BASE_PATH . '/templates/' . $template . '.php';

        if (!is_file($file)) {
            throw new RuntimeException("Template introuvable : {$template}");
        }

        extract($data, EXTR_SKIP);

        ob_start();
        include $file;

        return (string) ob_get_clean();
    }
}
