<?php
declare(strict_types=1);
namespace App\Security;
final class ChallengeService
{
    public function __construct(private readonly string $siteKey,private readonly string $secretKey){}
    public function enabled():bool{return trim($this->siteKey)!==''&&trim($this->secretKey)!=='';}
    public function siteKey():string{return $this->siteKey;}
    public function verify(string $token,string $remoteIp=''):bool
    {
        if(!$this->enabled())return true;if(trim($token)===''||!function_exists('curl_init'))return false;
        $ch=curl_init('https://challenges.cloudflare.com/turnstile/v0/siteverify');if($ch===false)return false;
        try{curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query(['secret'=>$this->secretKey,'response'=>$token,'remoteip'=>$remoteIp], '', '&', PHP_QUERY_RFC3986),CURLOPT_RETURNTRANSFER=>true,CURLOPT_CONNECTTIMEOUT=>3,CURLOPT_TIMEOUT=>6]);$raw=curl_exec($ch);if(!is_string($raw))return false;$json=json_decode($raw,true);return is_array($json)&&($json['success']??false)===true;}finally{curl_close($ch);}
    }
}
