<?php

declare(strict_types=1);

namespace Core;

use RuntimeException;

final class View
{
    public static function render(string $view, array $data = [], string $layout = 'app'): void
    {
        extract($data, EXTR_SKIP);
        $viewPath = self::resolveViewPath($view);
        $layoutPath = self::resolveLayoutPath($layout);

        ob_start();
        require $viewPath;
        $content = ob_get_clean();
        require $layoutPath;
    }

    public static function renderToString(string $view, array $data = []): string
    {
        extract($data, EXTR_SKIP);
        $viewPath = self::resolveViewPath($view);
        ob_start();
        require $viewPath;
        return (string) ob_get_clean();
    }

    private static function resolveViewPath(string $view): string
    {
        $path = dirname(__DIR__) . '/app/Views/' . ltrim($view, '/') . '.php';
        if (!is_file($path)) {
            throw new RuntimeException('View não encontrada: ' . $view);
        }

        return $path;
    }

    private static function resolveLayoutPath(string $layout): string
    {
        $path = dirname(__DIR__) . '/app/Views/layouts/' . ltrim($layout, '/') . '.php';
        if (!is_file($path)) {
            throw new RuntimeException('Layout não encontrado: ' . $layout);
        }

        return $path;
    }
}
