<?php
declare(strict_types=1);

session_set_cookie_params([
    'httponly' => true,
    'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
    'samesite' => 'Strict',
]);
session_start();

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Content-Type: image/svg+xml; charset=UTF-8');
header('X-Content-Type-Options: nosniff');

do {
    $digits = range(0, 9);
    shuffle($digits);
    $digits = array_slice($digits, 0, 6);
    $positionConflict = false;

    foreach ($digits as $index => $digit) {
        if ($digit === ($index + 1)) {
            $positionConflict = true;
            break;
        }
    }
} while ($positionConflict);

$position = random_int(1, 6);
$_SESSION['captcha_answer'] = (string)$digits[$position - 1];
$_SESSION['captcha_created_at'] = time();
$_SESSION['captcha_attempts'] = (int)($_SESSION['captcha_attempts'] ?? 0);

$digitElements = [];
foreach ($digits as $index => $digit) {
    $x = 104 + ($index * 64) + random_int(-3, 3);
    $y = 73 + random_int(-4, 4);
    $rotation = random_int(-14, 14);
    $digitElements[] = sprintf(
        '<text x="%d" y="%d" transform="rotate(%d %d %d)" class="digit">%d</text>',
        $x,
        $y,
        $rotation,
        $x,
        $y,
        $digit
    );
}

$noiseLines = [];
for ($i = 0; $i < 10; $i++) {
    $noiseLines[] = sprintf(
        '<line x1="%d" y1="%d" x2="%d" y2="%d"/>',
        random_int(12, 505),
        random_int(18, 91),
        random_int(12, 505),
        random_int(18, 91)
    );
}

$question = 'Welche Ziffer steht an Stelle ' . $position . '?';
?>
<svg xmlns="http://www.w3.org/2000/svg" width="520" height="150" viewBox="0 0 520 150" role="img" aria-labelledby="title desc">
  <title id="title">Sicherheitsabfrage</title>
  <desc id="desc">Zahlenreihe mit einer Frage zur Position</desc>
  <rect width="520" height="150" rx="8" fill="#f6f0e2"/>
  <g stroke="#877657" stroke-opacity=".2" stroke-width="1">
    <?= implode("\n    ", $noiseLines) ?>
  </g>
  <text x="18" y="66" fill="#667063" font-family="Arial, sans-serif" font-size="18">Reihe:</text>
  <g fill="#304232" font-family="Arial, sans-serif" font-size="42" font-weight="700">
    <?= implode("\n    ", $digitElements) ?>
  </g>
  <text x="24" y="126" fill="#5f6b60" font-family="Arial, sans-serif" font-size="18"><?= htmlspecialchars($question, ENT_XML1 | ENT_QUOTES, 'UTF-8') ?></text>
</svg>
