<?php
// Clean all output buffers before starting
while (ob_get_level()) ob_end_clean();

// Start session with error handling
$session_ok = @session_start();
if (!$session_ok) {
    // Session failed - generate a simple image with error
    $img = imagecreatetruecolor(120, 40);
    $bg = imagecolorallocate($img, 255, 200, 200);
    $fg = imagecolorallocate($img, 200, 0, 0);
    imagefilledrectangle($img, 0, 0, 120, 40, $bg);
    imagestring($img, 5, 10, 12, 'ERROR', $fg);
    header('Content-Type: image/png');
    imagepng($img);
    imagedestroy($img);
    exit;
}

// Generate random 5-digit code
$code = '';
for ($i = 0; $i < 5; $i++) {
    $code .= rand(0, 9);
}
$_SESSION['captcha'] = $code;

// Create image
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);

// Colors
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$gray = imagecolorallocate($image, 200, 200, 200);

// Fill background
imagefilledrectangle($image, 0, 0, $width, $height, $white);

// Add noise lines
for ($i = 0; $i < 5; $i++) {
    imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $gray);
}

// Add text
$x = 5;
$y = 10;
foreach (str_split($code) as $char) {
    imagestring($image, 5, $x, rand(5, 15), $char, $black);
    $x += 20;
}

// Output - make sure no extra whitespace
header('Content-Type: image/png');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
imagepng($image);
imagedestroy($image);
exit;
?>
