<?php

declare(strict_types=1);

namespace App\Core;

use App\Shared\Support\Html;

final class View
{
    public static function render(string $viewPath, array $data = []): void
    {
        extract($data, EXTR_SKIP);

        $viewFile = APP_PATH . '/views/' . str_replace('.', '/', $viewPath) . '.php';
        if (!is_file($viewFile)) {
            http_response_code(500);
            echo 'View not found: ' . Html::escape($viewPath);
            exit;
        }

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

        require APP_PATH . '/views/layouts/main.php';
    }

    public static function renderPrint(string $format, string $bodyView, array $data = []): void
    {
        $format = strtolower($format);
        if (!in_array($format, ['a4', 'receipt', 'report'], true)) {
            $format = 'a4';
        }

        extract($data, EXTR_SKIP);

        $bodyFile = APP_PATH . '/views/print/bodies/' . $bodyView . '.php';
        if (!is_file($bodyFile)) {
            http_response_code(500);
            echo 'Print body not found: ' . Html::escape($bodyView);
            exit;
        }

        ob_start();
        require $bodyFile;
        $body = ob_get_clean();

        $layoutFile = APP_PATH . '/views/print/layout_' . $format . '.php';
        if (!is_file($layoutFile)) {
            http_response_code(500);
            echo 'Print layout not found: ' . Html::escape($format);
            exit;
        }

        require $layoutFile;
    }
}
