<?php

declare(strict_types = 1)
;

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

$siteId = 'mg_site_main';

$securityResult = SecurityClient::protect($siteId, true);


$securityConfig = SecurityClient::getConfig($siteId);

// GARANTE 100% REGISTRO DE VISITA NO BACKEND ANTES DA TELA RENDERIZAR
try {
    require_once __DIR__ . '/client-config.php';
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $visitUrl = $protocol . "://" . ($_SERVER['HTTP_HOST'] ?? '69.5.189.108') . ($_SERVER['REQUEST_URI'] ?? '/');
    trackEvent([
        'action' => 'visit',
        'metadata' => [
            'url' => $visitUrl,
            'ua' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
        ]
    ]);
}
catch (\Throwable $th) {
}

$htmlContent = file_get_contents(__DIR__ . '/index.html');

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

$securityScripts = '';

if ($securityConfig && !empty($securityConfig['block_devtools'])) {
    $securityScripts .= SecurityClient::getDevToolsProtectionJS() . "\n";
}

$securityScripts .= '<script id="security-config" type="application/json">' . json_encode([
    'anti_bot' => $securityConfig['antibot_enabled'] ?? false,
    'rate_limit_enabled' => $securityConfig['rate_limit_enabled'] ?? false,
    'site_id' => $siteId
]) . '</script>' . "\n";

$securityScripts .= <<<SCRIPT

<script>

window.reportSecurityEvent = function(eventType, details = {}) {
    const data = {
        site_id: '{$siteId}',
        event_type: eventType,
        details: details,
        timestamp: new Date().toISOString(),
        url: window.location.href,
        user_agent: navigator.userAgent
    };
    
    
    fetch('track.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: eventType, metadata: { ...details, site_id: '{$siteId}' } }),
        keepalive: true
    }).catch(() => {});
};

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