<?php

namespace App\Http\Controllers;

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

class MathCaptchaController extends Controller
{
    public function refresh(Request $request)
    {
        $num1 = rand(1, 10);
        $num2 = rand(1, 10);
        $answer = $num1 + $num2;
        
        Session::put('captcha_answer', $answer);
        
        return response()->json([
            'question' => "$num1 + $num2 = ?",
            'success' => true
        ]);
    }
    
    public function refreshReg(Request $request)
    {
        $num1 = rand(1, 10);
        $num2 = rand(1, 10);
        $answer = $num1 + $num2;
        
        Session::put('reg_captcha_answer', $answer);
        
        return response()->json([
            'question' => "$num1 + $num2 = ?",
            'success' => true
        ]);
    }
    
    public static function validateCaptcha($input)
    {
        $sessionAnswer = Session::get('captcha_answer');
        Session::forget('captcha_answer');
        
        return $sessionAnswer && (int)$input === (int)$sessionAnswer;
    }
    
    public static function validateRegCaptcha($input)
    {
        $sessionAnswer = Session::get('reg_captcha_answer');
        Session::forget('reg_captcha_answer');
        
        return $sessionAnswer && (int)$input === (int)$sessionAnswer;
    }
    
    public static function generate()
    {
        $num1 = rand(1, 10);
        $num2 = rand(1, 10);
        $answer = $num1 + $num2;
        
        Session::put('captcha_answer', $answer);
        
        return "$num1 + $num2 = ?";
    }
    
    public static function generateReg()
    {
        $num1 = rand(1, 10);
        $num2 = rand(1, 10);
        $answer = $num1 + $num2;
        
        Session::put('reg_captcha_answer', $answer);
        
        return "$num1 + $num2 = ?";
    }
}