<?php

namespace GriffinForms\Includes\Integrations\CloudflareTurnstile;

/**
 * Cloudflare Turnstile Integration
 *
 * @since 1.0.0
 */
class Main extends \GriffinForms\Includes\Integrations\Format
{
    protected function setMeta()
    {
        $this->meta = 'cloudflare_turnstile';
        $this->id = 'cloudflare_turnstile';
    }

    protected function buildInfo(): array
    {
        return [
            'id'          => 'cloudflare_turnstile',
            'name'        => 'Cloudflare Turnstile',
            'category'    => 'Security',
            'description' => __('Privacy-friendly CAPTCHA alternative from Cloudflare.', 'griffinforms-form-builder'),
            'scope'       => [
                'is_global'      => true,
                'allow_override' => true,
            ],
        ];
    }

    public function getStatus(): array
    {
        $configured = $this->isConfigured();
        return [
            'configured'  => $configured,
            'active'      => $configured,
            'message'     => $configured ? __('Configured', 'griffinforms-form-builder') : __('Not configured', 'griffinforms-form-builder'),
        ];
    }

    public function getConfigFields(): array
    {
        return [
            ['name' => 'turnstile_site_key', 'label' => __('Site Key', 'griffinforms-form-builder'), 'type' => 'text', 'required' => true, 'help' => __('Public site key from Cloudflare Turnstile dashboard', 'griffinforms-form-builder')],
            ['name' => 'turnstile_secret_key', 'label' => __('Secret Key', 'griffinforms-form-builder'), 'type' => 'password', 'required' => true, 'help' => __('Secret key from Cloudflare Turnstile dashboard', 'griffinforms-form-builder')],
            ['name' => 'turnstile_widget_mode', 'label' => __('Widget Mode', 'griffinforms-form-builder'), 'type' => 'select', 'options' => ['managed' => __('Managed (auto)', 'griffinforms-form-builder'), 'invisible' => __('Invisible', 'griffinforms-form-builder')], 'required' => true],
        ];
    }

    protected function saveConfiguration(array $config): bool
    {
        $site_key   = isset($config['turnstile_site_key']) ? sanitize_text_field($config['turnstile_site_key']) : '';
        $secret_key = isset($config['turnstile_secret_key']) ? sanitize_text_field($config['turnstile_secret_key']) : '';
        $mode       = isset($config['turnstile_widget_mode']) ? sanitize_text_field($config['turnstile_widget_mode']) : 'managed';

        if (empty($site_key) || empty($secret_key)) {
            return false;
        }

        if (!in_array($mode, ['managed', 'invisible'], true)) {
            $mode = 'managed';
        }

        $this->settings->updateOption('turnstile_site_key', $site_key, 'antispam');
        $this->settings->updateOption('turnstile_secret_key', $secret_key, 'antispam');
        $this->settings->updateOption('turnstile_widget_mode', $mode, 'antispam');
        $this->settings->updateOption('enable_turnstile', 1, 'antispam');
        \GriffinForms\Includes\Integrations\Categories\Captcha::getInstance()->ensureActiveProvider($this->id);

        return true;
    }

    protected function validateConnection(): array
    {
        $site_key = $this->settings->getOption('turnstile_site_key');
        $secret_key = $this->settings->getOption('turnstile_secret_key');

        if (empty($site_key) || empty($secret_key)) {
            return [
                'success' => false,
                'message' => __('Site key or secret key missing.', 'griffinforms-form-builder'),
            ];
        }

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

        $form_id = $this->resolveFormContextId();

        if (is_wp_error($response)) {
            $this->log->add('error', 'form', $form_id, get_current_user_id(), 'Admin test: Cloudflare Turnstile validation request failed: ' . $response->get_error_message(), 'Integration (cloudflare_turnstile)');
            return [
                'success' => false,
                /* translators: %s: Cloudflare Turnstile error message */
                '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)) {
            $this->log->add('error', 'form', $form_id, get_current_user_id(), 'Admin test: Cloudflare Turnstile validation returned unexpected response.', 'Integration (cloudflare_turnstile)');
            return [
                'success' => false,
                'message' => __('Unexpected response from Cloudflare Turnstile.', 'griffinforms-form-builder'),
            ];
        }

        $errors = $body['error-codes'] ?? [];
        if (in_array('invalid-input-secret', (array) $errors, true)) {
            $this->log->add('error', 'form', $form_id, get_current_user_id(), 'Admin test: Cloudflare Turnstile validation failed because secret appears invalid.', 'Integration (cloudflare_turnstile)');
            return [
                'success' => false,
                'message' => __('Secret key appears to be invalid. Please double-check and try again.', 'griffinforms-form-builder'),
            ];
        }

        $allowed_dummy_errors = ['missing-input-response', 'invalid-input-response'];
        if (!($body['success'] ?? false)) {
            $remaining_errors = array_diff((array) $errors, $allowed_dummy_errors);
            if (!empty($remaining_errors)) {
                $this->log->add('error', 'form', $form_id, get_current_user_id(), 'Admin test: Cloudflare Turnstile validation failed with error codes: ' . implode(', ', $remaining_errors), 'Integration (cloudflare_turnstile)');
                return [
                    'success' => false,
                    'message' => __('Unable to verify Cloudflare Turnstile challenge. Please ensure your site and secret keys are correct.', 'griffinforms-form-builder'),
                ];
            }
        }

        $this->log->add('success', 'form', $form_id, get_current_user_id(), 'Admin test: Cloudflare Turnstile secret validated successfully.', 'Integration (cloudflare_turnstile)');
        return [
            'success' => true,
            'message' => __('Successfully connected to Cloudflare Turnstile. Secret key validated.', 'griffinforms-form-builder'),
        ];
    }

    public function isLibraryInstalled(): bool
    {
        return true;
    }

    public function getLibraryInstructions(): string
    {
        return __('No additional libraries required.', 'griffinforms-form-builder');
    }

    public function isConfigured(): bool
    {
        $site_key = $this->settings->getOption('turnstile_site_key');
        $secret_key = $this->settings->getOption('turnstile_secret_key');

        return !empty($site_key) && !empty($secret_key);
    }

    public function getConfigurationFormHtml(): string
    {
        $fields_html = '';

        foreach ($this->getConfigFields() as $field) {
            $field['value'] = $this->settings->getOption($field['name']) ?? '';
            if ($field['type'] === 'select' && empty($field['value'])) {
                $field['value'] = 'managed';
            }
            $control = \GriffinForms\Includes\Integrations\FormControls\Factory::create(
                $field['type'],
                $field['name'],
                $field['value'],
                $this->meta,
                $field
            );
            $fields_html .= $control->render();
        }

        return $this->renderConfigurationFormTemplate(
            'griffinforms-cloudflare-turnstile-config',
            $this->id,
            $fields_html
        );
    }

    /**
     * Configuration JS to handle AJAX save/cancel
     */
    public function getConfigurationJs(): string
    {
        $id = esc_js($this->id);
        $form_id = 'griffinforms-cloudflare-turnstile-config';

        return "
        (function() {
            const form = document.getElementById('{$form_id}');
            if (!form) return;

            const cancelBtn = form.querySelector('.gf-integration-btn-cancel');
            if (cancelBtn) {
                cancelBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    window.loadIntegrationInfo('{$id}');
                });
            }

            form.addEventListener('submit', function(e) {
                e.preventDefault();

                const formData = new FormData(form);
                const siteKey = (formData.get('turnstile_site_key') || '').trim();
                const secretKey = (formData.get('turnstile_secret_key') || '').trim();
                const mode = formData.get('turnstile_widget_mode') || 'managed';
                const formId = window.griffinformsResolveActiveFormId ? window.griffinformsResolveActiveFormId() : null;

                if (!siteKey || !secretKey) {
                    window.showIntegrationsMessage('danger', 'Please fill in all required fields');
                    return;
                }

                jQuery.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'saveIntegrationConfiguration',
                        integration_id: '{$id}',
                        nonce: window.griffinformsIntegrationsNonce || '',
                        form_id: formId || '',
                        turnstile_site_key: siteKey,
                        turnstile_secret_key: secretKey,
                        turnstile_widget_mode: mode
                    },
                    success: function(response) {
                        if (response.success) {
                            window.showIntegrationsMessage('success', response.data.message || 'Configuration saved');
                            setTimeout(() => window.loadIntegrationInfo('{$id}'), 500);
                        } else {
                            const msg = (response.data && response.data.msg) ? response.data.msg : 'Failed to save configuration';
                            window.showIntegrationsMessage('danger', msg);
                        }
                    },
                    error: function() {
                        window.showIntegrationsMessage('danger', 'Failed to save configuration');
                    }
                });
            });
        })();
        ";
    }

    /**
     * Per-form settings schema
     */
    public function getFormSettingsSchema(): array
    {
        return [
            [
                'name' => 'disable_turnstile',
                'type' => 'checkbox',
                'label' => __('Disable Turnstile on this form', 'griffinforms-form-builder'),
            ],
        ];
    }

    public function getDefaultFormSettings(): array
    {
        return [
            'disable_turnstile' => false,
        ];
    }

    public function validateFormSettings(array $settings)
    {
        return [
            'disable_turnstile' => $this->toBoolean($settings['disable_turnstile'] ?? false),
        ];
    }

    public function isEnabledForForm(int $form_id = 0): bool
    {
        $manager = \GriffinForms\Includes\Integrations\FormSettingsManager::getInstance();
        if ($form_id > 0) {
            $form_settings = $manager->getIntegrationSettings($form_id, $this->id);
            if (empty($form_settings)) {
                return (bool) $this->settings->getOption('enable_turnstile', false);
            }

            if (is_array($form_settings)) {
                $mode = $form_settings['mode'] ?? 'inherit';
                $settings = $form_settings['settings'] ?? [];

                if ($mode === 'disabled') {
                    return false;
                }

                $disable = $this->toBoolean($settings['disable_turnstile'] ?? false);
                if ($disable) {
                    return false;
                }
            }
        }

        return (bool) $this->settings->getOption('enable_turnstile', false);
    }

    /**
     * Resolve current form id for logging context
     */
}
