<?php
namespace Modules\Ecommerce\Controllers;

use Gestoreasy\Core\Tenant\ConnectionManager;
use Gestoreasy\Core\Tenant\TenantContext;

class EcommerceTemplateRenderer {
    private function getTenantId(): string {
        return TenantContext::getTenantId();
    }

    public static function render(string $templateName, array $data = []): string {
        $templatePath = __DIR__ . '/../../../public/ecommerce/templates/' . $templateName . '/index.php';
        
        // Se o template não existir, usar o default
        if (!file_exists($templatePath)) {
            $templatePath = __DIR__ . '/../../../public/ecommerce/templates/default/index.php';
        }
        
        if (!file_exists($templatePath)) {
            return '<html><body><h1>Template não encontrado</h1></body></html>';
        }
        
        extract($data);
        ob_start();
        include $templatePath;
        return ob_get_clean();
    }

    public static function getTemplateId(): string {
        $pdo = ConnectionManager::forTenant();
        $tenantId = TenantContext::getTenantId();
        
        try {
            $stmt = $pdo->prepare('SELECT template_id FROM ecommerce_config WHERE tenant_id = ? LIMIT 1');
            $stmt->execute([$tenantId]);
            $config = $stmt->fetch();
            return $config['template_id'] ?? 'default';
        } catch (\Throwable $e) {
            return 'default';
        }
    }
}

