<?php

namespace App\Core;

/**
 * Renderizador de views.
 * Separa completamente a lógica de apresentação do backend.
 */
class View
{
    /** @var string Diretório base das views */
    private static string $viewPath = '';

    // -------------------------------------------------------------------------
    // Configuração
    // -------------------------------------------------------------------------

    public static function setViewPath(string $path): void
    {
        self::$viewPath = rtrim($path, '/\\');
    }

    // -------------------------------------------------------------------------
    // Renderização
    // -------------------------------------------------------------------------

    /**
     * Renderiza uma view com layout opcional.
     *
     * @param string $view   Caminho relativo ao diretório de views (ex: 'home/index')
     * @param array  $data   Variáveis disponíveis na view
     * @param string $layout Layout a envolver a view (vazio = sem layout)
     */
    public static function render(string $view, array $data = [], string $layout = 'layouts/main'): void
    {
        // Garante UTF-8 em todas as respostas HTML
        if (!headers_sent()) {
            header('Content-Type: text/html; charset=UTF-8');
            // Não cachear páginas HTML no navegador: conteúdo dinâmico (permissões, menus,
            // dados por loja). O cache do browser já causou "a mudança não aparece" pós-deploy.
            // Assets (css/js) são servidos pelo Apache e não passam por aqui.
            header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
            header('Pragma: no-cache');
        }

        // Captura o conteúdo da view em buffer
        $content = self::capture($view, $data);

        if ($layout === '') {
            echo $content;
            return;
        }

        // Injeta o conteúdo capturado no layout
        $data['content'] = $content;
        self::capture($layout, $data, output: true);
    }

    /**
     * Captura ou imprime uma view em buffer.
     */
    private static function capture(string $view, array $data, bool $output = false): string
    {
        $file = self::$viewPath . DIRECTORY_SEPARATOR
              . str_replace('/', DIRECTORY_SEPARATOR, $view) . '.php';

        if (!file_exists($file)) {
            throw new \RuntimeException("View não encontrada: {$file}");
        }

        // Extrai variáveis para o escopo da view
        extract($data, EXTR_SKIP);

        if ($output) {
            require $file;
            return '';
        }

        ob_start();
        require $file;
        return ob_get_clean() ?: '';
    }

    // -------------------------------------------------------------------------
    // Utilitários de segurança para uso nas views
    // -------------------------------------------------------------------------

    /**
     * Escapa HTML para evitar XSS.
     */
    public static function e(mixed $value): string
    {
        return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}
