<?php
declare(strict_types=1);

namespace App\Core;

use RuntimeException;

class View
{
    public static function render(string $view, array $data = []): string
    {
        $file = self::file($view);
        $config = $data['config'] ?? ($GLOBALS['zalorox_config'] ?? []);

        extract($data + ['config' => $config], EXTR_SKIP);

        ob_start();
        require $file;

        return (string) ob_get_clean();
    }

    public static function page(string $layout, string $view, array $data = []): string
    {
        $content = self::render($view, $data);

        return self::render('layouts/' . $layout, $data + ['content' => $content]);
    }

    public static function partial(string $partial, array $data = []): string
    {
        return self::render('partials/' . $partial, $data);
    }

    private static function file(string $view): string
    {
        if (str_contains($view, '..')) {
            throw new RuntimeException('Invalid view path.');
        }

        $base = ($GLOBALS['zalorox_config']['paths']['views'] ?? BASE_PATH . '/app/Views');
        $file = rtrim($base, '/\\') . '/' . ltrim($view, '/\\') . '.php';

        if (!is_file($file)) {
            throw new RuntimeException("View not found: {$view}");
        }

        return $file;
    }
}
