<?php
session_start();

include_once("config.php");

$subject = 'Booking/contact Form';

$captchaText = generateCaptchaText();
$image = generateCaptchaImg($captchaText);

$_SESSION['captcha_attempts'] = 0; 
$_SESSION['captcha_hash'] = hash('sha256', strtolower($captchaText) . $salt);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);


function generateCaptchaText($length = 6) {
    $characters = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $captchaText = '';
    for ($i = 0; $i < $length; $i++) {
        $captchaText .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $captchaText;
}


function generateCaptchaImg($captchaText){
  $image = imagecreatetruecolor(150, 50); // create a new image size
  $background = imagecolorallocate($image, 200, 185, 185);
  $textColor = imagecolorallocate($image, 10, 90, 90);
  imagefilledrectangle($image, 0, 0, 150, 50, $background);

  // Density and color of background noise 
  for ($i = 0; $i < 6000; $i++) {
      $x = rand(0, 192);
      $y = rand(0, 200);
      $noiseColor = imagecolorallocate($image, rand(0, 50), rand(0, 20), rand(0, 20)); // Noise color
      imagesetpixel($image, $x, $y, $noiseColor);
  }

  //Text distortion
  $font = getcwd().'\RobotoMono-Bold.ttf';
  $fontSize = 22; // Adjust font size
  $x = 10;
  for ($i = 0; $i < strlen($captchaText); $i++) {
      $letter = $captchaText[$i];
      $angle = rand(-45, 45); // Random rotation
      $y = 35 + rand(-5, 5); // Random vertical pos
      $fontSize = rand(18, 22);
    
      imagettftext($image, $fontSize, $angle, $x, $y, $textColor, $font, $letter);
      $x += 22; // Letters spaces
  }

  // Línes to enmascarate text
  for ($i = 0; $i < 3; $i++) {
      $lineColor = imagecolorallocate($image, rand(150, 250), rand(150, 250), rand(150, 250));
      $x1 = rand(0, 150);
      $y1 = rand(0, 50);
      $x2 = rand(0, 150);
      $y2 = rand(0, 100);
      for($e =0; $e < 2; $e++){
        imageline($image, $x1+$e, $y1+$e, $x2+$e, $y2+$e, $lineColor);
      }
  }
  return $image;
}
?>
