<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class CaptchaController extends Controller
{
    public function generate(Request $request)
    {
        // Image size
        $width = 150;
        $height = 50;

        // Create image
        $image = imagecreate($width, $height);

        // Background color
        $bgColor = imagecolorallocate($image, 255, 255, 255);

        // Random text color
        $textColor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));

        // Generate random captcha code
        $code = substr(str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZ23456789'), 0, 5);

        // Save code in session
        Session::put('captcha_code', $code);

        // Pick font (you need to have a .ttf file in public/fonts/)
        $font = public_path('fonts/arial.ttf');
        if (!file_exists($font)) {
            // fallback if font not found (still show text with imagestring)
            imagestring($image, 5, 40, 15, $code, $textColor);
        } else {
            // Use TTF font for better quality
            imagettftext($image, 22, rand(-10, 10), 30, 35, $textColor, $font, $code);
        }

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

        // Add noise dots
        for ($i = 0; $i < 100; $i++) {
            $dotColor = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
            imagesetpixel($image, rand(0, $width), rand(0, $height), $dotColor);
        }

        // Output the image
        header("Content-Type: image/png");
        imagepng($image);
        imagedestroy($image);
        exit;
    }
}
