<?php
namespace App\Core;

class View
{
    public static function render(string $template, array $data = [], ?string $layout = 'layout/app'): void
    {
        $viewsPath = __DIR__ . '/../Views/';
        extract($data, EXTR_SKIP);
        $basePath = Request::basePath();

        $renderInner = function () use ($viewsPath, $template, $data) {
            extract($data, EXTR_SKIP);
            $file = $viewsPath . $template . '.php';
            if (!file_exists($file)) {
                throw new \RuntimeException("View not found: {$template}");
            }
            require $file;
        };

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

        $content = $renderInner;
        $layoutFile = $viewsPath . $layout . '.php';
        require $layoutFile;
    }

    public static function e(?string $value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }

    public static function url(string $path = ''): string
    {
        return Request::basePath() . '/' . ltrim($path, '/');
    }
}
