<?php
declare(strict_types=1);

namespace App\Core;

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

    public function render(): string
    {
        return $this->html;
    }

    public static function make(string $template, array $data = [], string $layout = 'public/layout'): self
    {
        return new self(self::renderTemplate($template, $data, $layout));
    }

    public static function renderTemplate(string $template, array $data = [], string $layout = 'public/layout'): string
    {
        $templatePath = dirname(__DIR__) . '/templates/pages/' . $template . '.php';
        $layoutPath = dirname(__DIR__) . '/templates/pages/' . $layout . '.php';

        if (! is_file($templatePath) || ! is_file($layoutPath)) {
            abort(500, 'Template tidak ditemukan.');
        }

        extract($data, EXTR_SKIP);

        ob_start();
        require $templatePath;
        $content = ob_get_clean();

        ob_start();
        require $layoutPath;

        return (string) ob_get_clean();
    }
}
