<?php
/**
 * Helper class for Cloudflare Turnstile CAPTCHA
 */
class TurnstileHelper {
    private $siteSettings;

    public function __construct() {
        $this->siteSettings = new SiteSettings();
    }

    /**
     * Check if Turnstile is enabled
     *
     * @return bool True if Turnstile is enabled, false otherwise
     */
    public function isEnabled() {
        return $this->siteSettings->getSetting('enable_turnstile') === '1';
    }

    /**
     * Get the Turnstile site key
     *
     * @return string The Turnstile site key
     */
    public function getSiteKey() {
        return $_ENV['TURNSTILE_SITE_KEY'] ?? '';
    }

    /**
     * Get the Turnstile secret key
     *
     * @return string The Turnstile secret key
     */
    private function getSecretKey() {
        return $_ENV['TURNSTILE_SECRET_KEY'] ?? '';
    }

    /**
     * Render the Turnstile widget
     *
     * @return string The HTML for the Turnstile widget
     */
    public function renderWidget() {
        if (!$this->isEnabled() || empty($this->getSiteKey())) {
            return '';
        }

        $siteKey = $this->getSiteKey();

        return <<<HTML
        <div class="cf-turnstile mb-4" data-sitekey="{$siteKey}" data-theme="dark"></div>
        <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
HTML;
    }

    /**
     * Validate a Turnstile response
     *
     * @param string $token The Turnstile response token
     * @return bool True if the response is valid, false otherwise
     */
    public function validateResponse($token) {
        // If Turnstile is disabled, always return true
        if (!$this->isEnabled()) {
            return true;
        }

        // If no token is provided, return false
        if (empty($token)) {
            return false;
        }

        $secretKey = $this->getSecretKey();

        // If no secret key is configured, return false
        if (empty($secretKey)) {
            return false;
        }

        // Prepare the request data
        $data = [
            'secret' => $secretKey,
            'response' => $token,
            'remoteip' => $_SERVER['REMOTE_ADDR'] ?? ''
        ];

        // Initialize cURL
        $ch = curl_init('https://challenges.cloudflare.com/turnstile/v0/siteverify');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

        // Execute the request
        $response = curl_exec($ch);
        curl_close($ch);

        // Parse the response
        $result = json_decode($response, true);

        // Return true if the response is valid, false otherwise
        return isset($result['success']) && $result['success'] === true;
    }
}
