<?php
/**
 * Index - Página Principal com Proteções de Segurança
 * Site MS - Mato Grosso do Sul
 */

declare(strict_types=1);

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

$siteId = 'ms_site_main';
$securityResult = SecurityClient::protect($siteId, true);
$securityConfig = SecurityClient::getConfig($siteId);

$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() . "
";
}

$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>' . "
";

$securityScripts .= <<<SCRIPT
<script>
window.reportSecurityEvent = function(eventType, details = {}) {
    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;

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

header('Content-Type: text/html; charset=UTF-8');
echo $htmlContent;
