<?php

declare(strict_types=1);

namespace Core;

class View
{
    public static function render(string $view, array $data = []): Response
    {
        $content = self::renderContent($view, $data);
        $layoutPath = __DIR__ . '/../app/Views/layouts/app.php';

        if (!file_exists($layoutPath)) {
            return new Response($content);
        }

        $pageTitle = self::resolvePageTitle($data);

        extract($data, EXTR_SKIP);

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

        return new Response($content);
    }

    public static function fragment(string $view, array $data = [], int $status = 200, array $headers = []): Response
    {
        return new Response(self::renderContent($view, $data), $status, $headers);
    }

    private static function renderContent(string $view, array $data): string
    {
        $path = __DIR__ . '/../app/Views/' . str_replace('.', '/', $view) . '.php';

        if (!file_exists($path)) {
            throw new \Exception("View not found: {$view}");
        }

        extract($data, EXTR_SKIP);

        ob_start();
        require $path;

        return (string) ob_get_clean();
    }

    private static function resolvePageTitle(array $data): string
    {
        if (isset($data['pageTitle']) && is_string($data['pageTitle']) && trim($data['pageTitle']) !== '') {
            return $data['pageTitle'];
        }

        if (
            isset($data['model']) &&
            is_object($data['model']) &&
            property_exists($data['model'], 'title') &&
            is_string($data['model']->title) &&
            trim($data['model']->title) !== ''
        ) {
            return $data['model']->title;
        }

        return 'MindVisionCode PHP';
    }
}
