<?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 ===

// 0. Open Graph + Title - Buscar configs do banco e injetar server-side
$ogConfig = [
    'frontend_site_name' => '',
    'og_description' => '',
    'og_image' => '',
    'og_enabled' => '1',
    'frontend_logo_main' => '',
];

try {
    if (isset($pdo)) {
        $ogKeys = ['frontend_site_name', 'og_description', 'og_image', 'og_enabled', 'frontend_logo_main'];
        $ogPh = implode(',', array_fill(0, count($ogKeys), '?'));
        $ogStmt = $pdo->prepare("SELECT config_key, config_value FROM system_config WHERE config_key IN ($ogPh)");
        $ogStmt->execute($ogKeys);
        foreach ($ogStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            if (!empty($row['config_value'])) {
                $ogConfig[$row['config_key']] = $row['config_value'];
            }
        }
    }
} catch (Exception $e) {
    error_log("OG Config Error: " . $e->getMessage());
}

$ogSiteName = $ogConfig['frontend_site_name'] ?: 'IceJogo';
$ogDescription = $ogConfig['og_description'] ?: $ogSiteName . ' - Jogos Online';
$ogImage = $ogConfig['og_image'] ?: ($ogConfig['frontend_logo_main'] ?: '/pwa-icon-512.png');

// Substituir <title> hardcoded do tema pelo nome configurado
$html = preg_replace('/<title>[^<]*<\/title>/', '<title>' . htmlspecialchars($ogSiteName) . '</title>', $html);

// Injetar Open Graph tags se habilitado
if ($ogConfig['og_enabled'] === '1') {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $siteUrl = $protocol . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
    // Tornar og:image URL absoluta
    $ogImageUrl = (strpos($ogImage, 'http') === 0) ? $ogImage : $siteUrl . $ogImage;

    $ogTags = "\n    <!-- Open Graph -->\n";
    $ogTags .= '    <meta property="og:type" content="website">' . "\n";
    $ogTags .= '    <meta property="og:title" content="' . htmlspecialchars($ogSiteName) . '">' . "\n";
    $ogTags .= '    <meta property="og:description" content="' . htmlspecialchars($ogDescription) . '">' . "\n";
    $ogTags .= '    <meta property="og:image" content="' . htmlspecialchars($ogImageUrl) . '">' . "\n";
    $ogTags .= '    <meta property="og:url" content="' . htmlspecialchars($siteUrl) . '/">' . "\n";
    $ogTags .= '    <meta property="og:site_name" content="' . htmlspecialchars($ogSiteName) . '">' . "\n";
    $ogTags .= '    <!-- Twitter Card -->' . "\n";
    $ogTags .= '    <meta name="twitter:card" content="summary_large_image">' . "\n";
    $ogTags .= '    <meta name="twitter:title" content="' . htmlspecialchars($ogSiteName) . '">' . "\n";
    $ogTags .= '    <meta name="twitter:description" content="' . htmlspecialchars($ogDescription) . '">' . "\n";
    $ogTags .= '    <meta name="twitter:image" content="' . htmlspecialchars($ogImageUrl) . '">' . "\n";
    $ogTags .= '    <meta name="description" content="' . htmlspecialchars($ogDescription) . '">';

    $html = str_replace('</head>', $ogTags . "\n</head>", $html);
}

// 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. PWA - Buscar configurações do banco e injetar condicionalmente
$pwaEnabled = false;
$pwaConfig = [
    'pwa_app_name' => 'IceJogo',
    'pwa_banner_title' => 'Instalar IceJogo',
    'pwa_banner_subtitle' => 'Acesse mais rápido direto da sua tela inicial',
];

try {
    if (isset($pdo)) {
        $pwaKeys = ['pwa_enabled', 'pwa_app_name', 'pwa_banner_title', 'pwa_banner_subtitle'];
        $ph = implode(',', array_fill(0, count($pwaKeys), '?'));
        $pwaStmt = $pdo->prepare("SELECT config_key, config_value FROM system_config WHERE config_key IN ($ph)");
        $pwaStmt->execute($pwaKeys);
        foreach ($pwaStmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            if ($row['config_key'] === 'pwa_enabled') {
                $pwaEnabled = $row['config_value'] === '1';
            } elseif (!empty($row['config_value'])) {
                $pwaConfig[$row['config_key']] = $row['config_value'];
            }
        }
    }
} catch (Exception $e) {
    error_log("PWA Config Error: " . $e->getMessage());
}

if ($pwaEnabled) {
    // Injetar manifest link no <head>
    if (strpos($html, 'manifest') === false) {
        $manifestTag = '<link rel="manifest" href="/manifest.php">';
        $html = preg_replace('/<head([^>]*)>/', '<head$1>' . "\n    " . $manifestTag, $html);
    }

    // Escapar textos para JS
    $jsTitle = addslashes($pwaConfig['pwa_banner_title']);
    $jsSubtitle = addslashes($pwaConfig['pwa_banner_subtitle']);

    $pwaScript = '
<script>
if ("serviceWorker" in navigator) {
    navigator.serviceWorker.register("/sw.js").catch(function(e) {
        console.log("SW registration failed:", e);
    });
}
let deferredPrompt;
window.addEventListener("beforeinstallprompt", function(e) {
    e.preventDefault();
    deferredPrompt = e;
    if (localStorage.getItem("pwa-dismissed")) {
        var dismissed = parseInt(localStorage.getItem("pwa-dismissed"));
        if (Date.now() - dismissed < 86400000) return;
    }
    var banner = document.createElement("div");
    banner.id = "pwa-install-banner";
    banner.innerHTML = \'<div style="display:flex;align-items:center;gap:12px;flex:1"><img src="/pwa-icon-192.png" style="width:48px;height:48px;border-radius:12px"><div><div style="font-weight:bold;font-size:15px">' . $jsTitle . '</div><div style="font-size:12px;opacity:.7">' . $jsSubtitle . '</div></div></div><div style="display:flex;gap:8px"><button id="pwa-dismiss" style="background:transparent;color:#fff;border:1px solid rgba(255,255,255,.3);padding:8px 16px;border-radius:8px;font-size:14px;cursor:pointer">Agora não</button><button id="pwa-install" style="background:#2563eb;color:#fff;border:none;padding:8px 20px;border-radius:8px;font-size:14px;font-weight:bold;cursor:pointer">Instalar</button></div>\';
    banner.style.cssText = "position:fixed;bottom:0;left:0;right:0;background:rgba(20,20,20,.95);backdrop-filter:blur(10px);color:#fff;padding:16px;display:flex;align-items:center;gap:12px;z-index:99999;font-family:-apple-system,BlinkMacSystemFont,sans-serif;box-shadow:0 -2px 20px rgba(0,0,0,.5);animation:slideUp .3s ease";
    var style = document.createElement("style");
    style.textContent = "@keyframes slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}";
    document.head.appendChild(style);
    document.body.appendChild(banner);
    document.getElementById("pwa-install").addEventListener("click", function() {
        deferredPrompt.prompt();
        deferredPrompt.userChoice.then(function(result) {
            deferredPrompt = null;
            banner.remove();
        });
    });
    document.getElementById("pwa-dismiss").addEventListener("click", function() {
        localStorage.setItem("pwa-dismissed", Date.now().toString());
        banner.remove();
    });
});
</script>';
    $html = str_replace('</body>', $pwaScript . "\n</body>", $html);
}

// 7. 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;