<?php

namespace App\Services;

class TurnstileService
{
    /**
     * Validar token Cloudflare Turnstile.
     */
    public static function verify(?string $token): bool
    {
        $secret = config('services.turnstile.secret_key');

        if (empty($secret) || empty($token)) {
            return false;
        }

        try {
            $response = file_get_contents('https://challenges.cloudflare.com/turnstile/v0/siteverify', false, stream_context_create([
                'http' => [
                    'method' => 'POST',
                    'header' => 'Content-Type: application/x-www-form-urlencoded',
                    'content' => http_build_query([
                        'secret' => $secret,
                        'response' => $token,
                        'remoteip' => request()->ip(),
                    ]),
                    'timeout' => 5,
                ],
            ]));

            if ($response) {
                $data = json_decode($response, true);
                return $data['success'] ?? false;
            }
        } catch (\Exception $e) {
            \Log::warning('Turnstile verification failed: ' . $e->getMessage());
        }

        return false;
    }
}
