<?php

declare(strict_types=1);

namespace App\Core;

class View
{
    public static function render(string $view, array $data = [], string $layout = 'layouts/app'): void
    {
        echo self::renderToString($view, $data, $layout);
    }

    public static function renderToString(string $view, array $data = [], ?string $layout = 'layouts/app'): string
    {
        $viewPath = base_path('app/views/' . $view . '.php');
        if (!is_file($viewPath)) {
            throw new \RuntimeException('Vista no encontrada: ' . $view);
        }

        extract($data, EXTR_SKIP);

        ob_start();
        include $viewPath;
        $content = (string) ob_get_clean();

        if ($layout === null || $layout === '') {
            return $content;
        }

        $layoutPath = base_path('app/views/' . $layout . '.php');
        if (!is_file($layoutPath)) {
            return $content;
        }

        ob_start();
        include $layoutPath;
        return (string) ob_get_clean();
    }
}
