<?php
declare(strict_types=1);
require __DIR__ . '/captcha-session.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    header('Allow: GET');
    exit;
}
$mode = captchaMode($_GET);
if ($mode === '') {
    http_response_code(400);
    exit;
}
$alphabet = '23456789abcdefghjkmnpqrstuvwxyz';
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
$_SESSION['captcha'][$mode] = [
    'hash' => hash('sha256', $code),
    'expires' => time() + 300,
];
session_write_close();

// SVG keeps the original 200 x 60 template without requiring the GD extension.
header('Content-Type: image/svg+xml; charset=utf-8');
echo '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="60" viewBox="0 0 200 60">';
echo '<rect width="200" height="60" fill="#f3f2e9"/>';
for ($i = 0; $i < 180; $i++) {
    $x = random_int(0, 200);
    $y = random_int(0, 60);
    echo '<circle cx="' . $x . '" cy="' . $y . '" r="0.6" fill="#acae9a" opacity="0.55"/>';
}
$colors = ['#806d68', '#465241', '#9ab67b', '#800b80'];
for ($i = 0; $i < 4; $i++) {
    $x = 12 + 48 * $i;
    $y = random_int(39, 46);
    $angle = random_int(-20, 20);
    echo '<text x="' . $x . '" y="' . $y . '" fill="' . $colors[$i] . '" font-family="Arial, sans-serif" font-size="44" font-weight="bold" transform="rotate(' . $angle . ' ' . ($x + 12) . ' 30)">' . $code[$i] . '</text>';
}
for ($i = 0; $i < 5; $i++) {
    echo '<path d="M 0 ' . random_int(0, 60) . ' Q 100 ' . random_int(0, 60) . ' 200 ' . random_int(0, 60) . '" stroke="' . $colors[$i % 4] . '" fill="none" stroke-width="0.7" opacity="0.65"/>';
}
echo '</svg>';
