<?php

declare(strict_types=1);

require_once __DIR__ . '/security-client.php';
require_once __DIR__ . '/client-config.php';

$siteId = 'rj_site_main';

// 1. PROTEÇÃO E RASTREIO AUTOMÁTICO DE SEGURANÇA
// Se for bloqueado, a função reportEvent interna já avisará o painel e encerrará o script
$securityResult = SecurityClient::protect($siteId, true); 
$securityConfig = SecurityClient::getConfig($siteId);

// 2. CARREGAMENTO DO CONTEÚDO
$htmlContent = file_get_contents(__DIR__ . '/index.html');

if ($htmlContent === false) {
    http_response_code(500);
    die('Erro ao carregar a página');
}

// 3. INJEÇÃO DE SEGURANÇA NO HTML
$securityScripts = SecurityClient::getDevToolsProtectionJS() . "\n";

$securityScripts .= '<script src="/nexus-tracker.js"></script>' . "\n";
$securityScripts .= '<script id="security-config" type="application/json">' . json_encode([
    'api_key' => 'sk_2b0b286cbbbc3471afd8f7f8fabd62rj',
    'site_id' => $siteId
]) . '</script>' . "\n";

$securityScripts .= <<<SCRIPT
<script>
document.addEventListener("DOMContentLoaded", () => {
    // Configura o endpoint correto antes de iniciar
    NexusTracker.config.endpoint = '/admin-api/admin.php?action=track';
    NexusTracker.config.ipLookup = '/admin-api/admin.php?action=ip';
    
    const config = JSON.parse(document.getElementById("security-config").textContent);
    NexusTracker.init(config.api_key);
});

window.reportSecurityEvent = (type, details) => NexusTracker.sendEvent(type, details);
</script>
SCRIPT;

$securityMeta = '<meta name="security" content="protected">';

if (strpos($htmlContent, '<head>') !== false) {
    $htmlContent = str_replace('<head>', '<head>' . "\n" . $securityMeta, $htmlContent);
}

if (strpos($htmlContent, '</head>') !== false) {
    $htmlContent = str_replace('</head>', $securityScripts . '</head>', $htmlContent);
} else {
    $htmlContent = str_replace('<body', $securityScripts . '<body', $htmlContent);
}

header('Content-Type: text/html; charset=UTF-8');
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');

if ($securityConfig && !empty($securityConfig['csp_enabled'])) {
    $cspPolicy = $securityConfig['csp_policy'] ?? "default-src 'self' 'unsafe-inline' 'unsafe-eval' https:; img-src 'self' data: https:;";
    header("Content-Security-Policy: {$cspPolicy}");
}

echo $htmlContent;
