<?php
declare(strict_types=1);

/**
 * 图片验证码：个位数加减法，比如 "3 + 5 = ?"
 * 答案存 $_SESSION，跟具体业务无关，哪个登录页都能用
 */
final class Captcha
{
    private const SESSION_KEY = 'captchaAnswer';

    /**
     * 生成一道题目并把答案存进 SESSION，返回 PNG 图片二进制内容
     */
    public static function render(): string
    {
        $a = random_int(1, 9);
        $b = random_int(1, 9);
        $op = random_int(0, 1) === 0 ? '+' : '-';

        if ($op === '-' && $a < $b) {
            [$a, $b] = [$b, $a]; // 保证减法结果不为负数
        }

        $_SESSION[self::SESSION_KEY] = $op === '+' ? $a + $b : $a - $b;

        $text = "{$a} {$op} {$b} = ?";

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

        $bg = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 0, 0, $bg);

        // 干扰线
        for ($i = 0; $i < 6; $i++) {
            $lineColor = imagecolorallocate($image, random_int(150, 200), random_int(150, 200), random_int(150, 200));
            imageline($image, random_int(0, $width), random_int(0, $height), random_int(0, $width), random_int(0, $height), $lineColor);
        }

        $textColor = imagecolorallocate($image, 30, 60, 120);
        imagestring($image, 5, 12, 12, $text, $textColor);

        ob_start();
        imagepng($image);
        $binary = ob_get_clean();
        imagedestroy($image);

        return $binary;
    }

    /**
     * 校验用户输入，校验后立即清空 SESSION 里的答案（一次性，防止重复提交复用同一道题）
     */
    public static function verify(mixed $input): bool
    {
        $answer = $_SESSION[self::SESSION_KEY] ?? null;
        unset($_SESSION[self::SESSION_KEY]);

        return $answer !== null && is_numeric($input) && (int) $input === (int) $answer;
    }
}
