<?php

namespace GriffinForms\Frontend\Html\Security\Captcha;

/**
 * Cloudflare Turnstile frontend adapter.
 */
class Turnstile extends Format
{
    private $token_key = 'turnstile';

    public function isEnabled(): bool
    {
        return !empty($this->options['enable_turnstile']);
    }

    public function renderField(string $position): string
    {
        if (!$this->isEnabled()) {
            return '';
        }

        $html  = '<div class="griffinform-turnstile-container d-flex justify-content-center">';
        $html .= '<div class="cf-turnstile" data-sitekey="' . esc_attr($this->options['turnstile_site_key'] ?? '') . '"></div>';
        $html .= '</div>';
        return $html;
    }

    public function enqueueScripts(): void
    {
        if (!$this->isEnabled()) {
            return;
        }

        wp_enqueue_script('griffinforms-turnstile', 'https://challenges.cloudflare.com/turnstile/v0/api.js', [], null, true);
    }

    public function getTokenKey(): string
    {
        return $this->token_key;
    }

    public function getClientContext(): array
    {
        return [
            'enabled'  => $this->isEnabled(),
            'id'       => 'cloudflare_turnstile',
            'token_key'=> $this->token_key,
            'site_key' => $this->options['turnstile_site_key'] ?? '',
        ];
    }

    public function validateSubmission($antispam_data, array $form_data): array
    {
        $token = $antispam_data->{$this->token_key} ?? '';
        if (empty($token)) {
            return ['success' => false, 'message' => __('Unable to submit. Turnstile token missing.', 'griffinforms-form-builder')];
        }

        $secret = $this->options['turnstile_secret_key'] ?? '';
        if (empty($secret)) {
            return ['success' => false, 'message' => __('Turnstile secret key missing.', 'griffinforms-form-builder')];
        }

        $response = wp_remote_post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
            'timeout' => 10,
            'body'    => [
                'secret'   => $secret,
                'response' => $token,
            ],
        ]);

        if (is_wp_error($response)) {
            return ['success' => false, 'message' => sprintf(__('Unable to reach Cloudflare Turnstile: %s', 'griffinforms-form-builder'), $response->get_error_message())];
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (!is_array($body) || !($body['success'] ?? false)) {
            return ['success' => false, 'message' => __('Unable to submit. Turnstile assessment failed.', 'griffinforms-form-builder')];
        }

        return ['success' => true];
    }
}
