<?php
namespace Gestoreasy\Core\View;

use Gestoreasy\Core\Http\Response;

class View {
    public static function render(string $template, array $data = []): Response {
        $templatePath = __DIR__ . '/../../../views/' . $template . '.php';
        
        if (!file_exists($templatePath)) {
            return new Response(404, 'Template not found: ' . $template);
        }
        
        try {
            extract($data);
            ob_start();
            include $templatePath;
            $content = ob_get_clean();
            
            return new Response(200, $content, ['Content-Type' => 'text/html; charset=utf-8']);
        } catch (\Throwable $e) {
            return new Response(500, 'Template render error: ' . $e->getMessage());
        }
    }
    
    public static function renderWithLayout(string $template, array $data = [], string $layout = '_layout'): Response {
        $templatePath = __DIR__ . '/../../../views/' . $template . '.php';
        $layoutPath = __DIR__ . '/../../../views/' . $layout . '.php';
        
        if (!file_exists($templatePath)) {
            return new Response(404, 'Template not found: ' . $template);
        }
        
        if (!file_exists($layoutPath)) {
            return new Response(404, 'Layout not found: ' . $layout);
        }
        
        try {
            extract($data);
            
            // Renderizar o template primeiro
            ob_start();
            include $templatePath;
            $content = ob_get_clean();
            
            // Depois renderizar o layout com o conteúdo
            ob_start();
            include $layoutPath;
            $finalContent = ob_get_clean();
            
            return new Response(200, $finalContent, ['Content-Type' => 'text/html; charset=utf-8']);
        } catch (\Throwable $e) {
            return new Response(500, 'Template render error: ' . $e->getMessage());
        }
    }
}