<?php
if (session_status() === PHP_SESSION_NONE) session_start();

// Generate random 5-char alphanumeric string
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$code = '';
for ($i = 0; $i < 5; $i++) {
    $code .= $chars[random_int(0, strlen($chars) - 1)];
}
$_SESSION['captcha_code'] = $code;

$width  = 160;
$height = 60;
$img    = imagecreatetruecolor($width, $height);

// Background color (dark green-ish to match theme)
$bg = imagecolorallocate($img, 30, 50, 10);
imagefilledrectangle($img, 0, 0, $width, $height, $bg);

// Add noise dots
for ($i = 0; $i < 800; $i++) {
    $nc = imagecolorallocate($img, rand(40, 120), rand(60, 140), rand(10, 60));
    imagesetpixel($img, rand(0, $width), rand(0, $height), $nc);
}

// Add noise lines
for ($i = 0; $i < 6; $i++) {
    $lc = imagecolorallocate($img, rand(50, 130), rand(80, 160), rand(20, 80));
    imageline($img, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lc);
}

// Draw each character with random color, angle, and position
$colors = [
    imagecolorallocate($img, 200, 240, 100),
    imagecolorallocate($img, 255, 220, 80),
    imagecolorallocate($img, 100, 220, 180),
    imagecolorallocate($img, 255, 160, 80),
    imagecolorallocate($img, 180, 255, 120),
];

$charWidth = 26;
$totalWidth = strlen($code) * $charWidth;
$startX = (int)(($width - $totalWidth) / 2);

$x = $startX;
for ($i = 0; $i < strlen($code); $i++) {
    $y     = rand(28, 36);
    $color = $colors[$i % count($colors)];
    $font  = 5;
    imagestring($img, $font, $x + rand(-2, 2), $y + rand(-4, 4), $code[$i], $color);
    $x += $charWidth;
}

// Wavy distortion
$distorted = imagecreatetruecolor($width, $height);
$bg2 = imagecolorallocate($distorted, 30, 50, 10);
imagefilledrectangle($distorted, 0, 0, $width, $height, $bg2);
for ($x = 0; $x < $width; $x++) {
    for ($y = 0; $y < $height; $y++) {
        $sx = $x + (int)(sin($y / 5.0) * 3);
        $sy = $y + (int)(sin($x / 5.0) * 2);
        if ($sx >= 0 && $sx < $width && $sy >= 0 && $sy < $height) {
            $color = imagecolorat($img, $sx, $sy);
            imagesetpixel($distorted, $x, $y, $color);
        }
    }
}

// Border
$border = imagecolorallocate($distorted, 80, 130, 30);
imagerectangle($distorted, 0, 0, $width - 1, $height - 1, $border);

header('Content-Type: image/png');
header('Cache-Control: no-cache, no-store, must-revalidate');
imagepng($distorted);
imagedestroy($img);
imagedestroy($distorted);
