<?php
/// file: app/Core/View.php

declare(strict_types=1);

namespace App\Core;

final class View
{
    /** @param array<string, mixed> $data */
    public static function render(string $template, array $data, ?string $layout, App $app): string
    {
        $base = dirname(__DIR__, 1) . '/View/';
        $file = $base . str_replace('.', '/', $template) . '.php';
        if (! is_file($file)) {
            throw new \RuntimeException("View not found: {$template}");
        }
        $data['app'] = $app;
        extract($data, EXTR_SKIP);
        ob_start();
        include $file;
        $content = (string) ob_get_clean();
        if ($layout === null) {
            return $content;
        }
        $layoutFile = $base . str_replace('.', '/', $layout) . '.php';
        if (! is_file($layoutFile)) {
            return $content;
        }
        $data['content'] = $content;
        extract($data, EXTR_SKIP);
        ob_start();
        include $layoutFile;
        return (string) ob_get_clean();
    }

    public static function component(string $name, array $data = []): void
    {
        $path = dirname(__DIR__, 1) . '/Components/' . str_replace('.', '/', $name) . '.php';
        if (! is_file($path)) {
            return;
        }
        extract($data, EXTR_SKIP);
        include $path;
    }
}
