<?php
/**
 * Theme Loader - Sistema de Multi-Temas
 * Carrega o tema ativo dinamicamente sem rebuild
 */

// Conectar ao banco de dados
require_once __DIR__ . '/config/database.php';

// Por padrão, usar tema diadasbruxas
$activeTheme = 'diadasbruxas';

try {
    // Tentar conectar ao banco e buscar o tema ativo
    if (defined('DB_HOST') && defined('DB_NAME') && defined('DB_USER') && defined('DB_PASS')) {
        $pdo = new PDO(
            "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
            DB_USER,
            DB_PASS,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
        );

        // Verificar se a coluna theme_name existe
        $stmt = $pdo->query("SHOW COLUMNS FROM site_config LIKE 'theme_name'");
        if ($stmt->rowCount() > 0) {
            // Buscar tema ativo do banco
            $stmt = $pdo->query("SELECT theme_name FROM site_config WHERE id = 1");
            $config = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($config && !empty($config['theme_name'])) {
                $activeTheme = $config['theme_name'];
            }
        }
    }
} catch (Exception $e) {
    // Em caso de erro, usar tema padrão
    error_log("Theme Loader Error: " . $e->getMessage());
}

// Validar tema (prevenir path traversal e verificar se existe)
// Remove caracteres perigosos para prevenir path traversal
$activeTheme = preg_replace('/[^a-zA-Z0-9_-]/', '', $activeTheme);

// Verificar se o tema existe no diretório themes
$themesDir = __DIR__ . '/themes';
if (!is_dir($themesDir . '/' . $activeTheme) || empty($activeTheme)) {
    // Se o tema não existe, buscar o primeiro tema disponível
    $availableThemes = array_diff(scandir($themesDir), ['.', '..']);
    $availableThemes = array_filter($availableThemes, function($item) use ($themesDir) {
        return is_dir($themesDir . '/' . $item);
    });

    if (count($availableThemes) > 0) {
        $activeTheme = reset($availableThemes); // Pega o primeiro tema disponível
    } else {
        // Se não houver nenhum tema, erro fatal
        http_response_code(500);
        die("Erro: Nenhum tema encontrado no diretório /themes/");
    }
}

// Definir paths
$themePath = __DIR__ . '/themes/' . $activeTheme;
$indexFile = $themePath . '/index.html';

// Verificar se tema existe
if (!file_exists($indexFile)) {
    // Tentar tema padrão
    $activeTheme = 'diadasbruxas';
    $themePath = __DIR__ . '/themes/' . $activeTheme;
    $indexFile = $themePath . '/index.html';

    if (!file_exists($indexFile)) {
        http_response_code(500);
        die("Erro: Nenhum tema encontrado. Verifique a instalação.");
    }
}

// Ler o arquivo index.html do tema
$html = file_get_contents($indexFile);

// === TRANSFORMAÇÕES DINÂMICAS ===

// 1. Reescrever paths de assets para incluir prefixo do tema
// Isso transformará: href="css/xxx.css" em href="/themes/[tema]/css/xxx.css"
$html = preg_replace_callback(
    '/(href|src)=["\'](?!http|\/\/|\/themes\/|\/api|#)(css|js|images|img|fonts)\/([^"\']+)["\']/',
    function($matches) use ($activeTheme) {
        $attr = $matches[1];
        $type = $matches[2];
        $path = $matches[3];
        return $attr . '="/themes/' . $activeTheme . '/' . $type . '/' . $path . '"';
    },
    $html
);

// 2. Injetar API interceptor (se não existir)
if (strpos($html, 'api-interceptor.js') === false) {
    $interceptorTag = '<script src="/api-interceptor.js?v=' . time() . '"></script>';
    // Injetar depois do <head>
    $html = preg_replace('/<head([^>]*)>/', '<head$1>' . "\n    " . $interceptorTag, $html);
}

// 3. Adicionar cache busting para todos os assets
$cacheVersion = filemtime($indexFile);
$html = preg_replace_callback(
    '/(href|src)=["\']([^"\']+\.(css|js))(?:\?v=[0-9]+)?["\']/',
    function($matches) use ($cacheVersion) {
        $attr = $matches[1];
        $path = $matches[2];
        // Não adicionar cache busting para URLs externas
        if (strpos($path, 'http') === 0 || strpos($path, '//') === 0) {
            return $matches[0];
        }
        return $attr . '="' . $path . '?v=' . $cacheVersion . '"';
    },
    $html
);

// 4. Adicionar meta tag com tema ativo (útil para debugging)
$themeMeta = '<meta name="active-theme" content="' . $activeTheme . '">' . "\n";
$html = preg_replace('/<head([^>]*)>/', '<head$1>' . "\n    " . $themeMeta, $html);

// 5. Injetar script de customização dinâmica
$customizationTag = '<script src="/theme-customization.js?v=' . time() . '"></script>';
$html = str_replace('</body>', "\n    " . $customizationTag . "\n</body>", $html);

// 6. Adicionar comentário de debug
$debugComment = "\n<!-- Theme Loader Active: $activeTheme -->\n";
$html = str_replace('<html', $debugComment . '<html', $html);

// Servir HTML processado
header('Content-Type: text/html; charset=utf-8');
header('X-Active-Theme: ' . $activeTheme);

// Prevenir cache para facilitar desenvolvimento
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

echo $html;