<?php

declare(strict_types=1);

namespace App\Core;

use RuntimeException;

final class View
{
    public function __construct(private string $basePath) {}

    public function render(string $view, array $data = [], ?string $layout = 'layouts/app'): string
    {
        $viewFile = $this->basePath . '/' . trim($view, '/') . '.php';
        if (!is_file($viewFile)) {
            throw new RuntimeException('View not found: ' . $view, 500);
        }

        $content = $this->includeFile($viewFile, $data);

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

        $layoutFile = $this->basePath . '/' . trim($layout, '/') . '.php';
        if (!is_file($layoutFile)) {
            throw new RuntimeException('Layout not found: ' . $layout, 500);
        }

        return $this->includeFile($layoutFile, $data + ['content' => $content]);
    }

    private function includeFile(string $file, array $data): string
    {
        extract($data, EXTR_SKIP);
        ob_start();
        require $file;
        return (string) ob_get_clean();
    }
}
