<?php

namespace GriffinForms\Includes\Integrations\Hcaptcha;

class Main extends \GriffinForms\Includes\Integrations\Format
{
    protected function setMeta()
    {
        $this->meta = 'hcaptcha';
        $this->id = 'hcaptcha';
    }

    protected function buildInfo(): array
    {
        return [
            'id'          => 'hcaptcha',
            'name'        => 'hCaptcha',
            'category'    => 'Security',
            'description' => __('Privacy-first CAPTCHA alternative compatible with Google reCAPTCHA.', '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' => 'hcaptcha_site_key', 'label' => __('Site Key', 'griffinforms-form-builder'), 'type' => 'text', 'required' => true, 'help' => __('Public site key from hCaptcha dashboard', 'griffinforms-form-builder')],
            ['name' => 'hcaptcha_secret_key', 'label' => __('Secret Key', 'griffinforms-form-builder'), 'type' => 'password', 'required' => true, 'help' => __('Secret key from hCaptcha dashboard', 'griffinforms-form-builder')],
            ['name' => 'hcaptcha_widget_mode', 'label' => __('Widget Mode', 'griffinforms-form-builder'), 'type' => 'select', 'options' => ['checkbox' => __('Checkbox', 'griffinforms-form-builder'), 'invisible' => __('Invisible', 'griffinforms-form-builder')], 'required' => true],
        ];
    }

    protected function saveConfiguration(array $config): bool
    {
        $site_key   = isset($config['hcaptcha_site_key']) ? sanitize_text_field($config['hcaptcha_site_key']) : '';
        $secret_key = isset($config['hcaptcha_secret_key']) ? sanitize_text_field($config['hcaptcha_secret_key']) : '';
        $mode       = isset($config['hcaptcha_widget_mode']) ? sanitize_text_field($config['hcaptcha_widget_mode']) : 'checkbox';

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

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

        $this->settings->updateOption('hcaptcha_site_key', $site_key, 'antispam');
        $this->settings->updateOption('hcaptcha_secret_key', $secret_key, 'antispam');
        $this->settings->updateOption('hcaptcha_widget_mode', $mode, 'antispam');
        $this->settings->updateOption('enable_hcaptcha', 1, 'antispam');
        \GriffinForms\Includes\Integrations\Categories\Captcha::getInstance()->ensureActiveProvider($this->id);

        return true;
    }

    protected function validateConnection(): array
    {
        $site_key = $this->settings->getOption('hcaptcha_site_key');
        $secret_key = $this->settings->getOption('hcaptcha_secret_key');
        $form_id = $this->resolveFormContextId();

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

        // Use empty response so hCaptcha returns invalid-input-response and validates secret only if configured properly
        $response = wp_remote_post('https://hcaptcha.com/siteverify', [
            'timeout' => 10,
            'body'    => [
                'secret'   => $secret_key,
                'response' => '',
            ],
        ]);

        if (is_wp_error($response)) {
            $message = 'Admin test: hCaptcha validation request failed: ' . $response->get_error_message();
            $this->log->add('error', 'form', $form_id, get_current_user_id(), $message, 'Integration (hcaptcha)');
            return [
                'success' => false,
                /* translators: %s: hCaptcha error message */
                'message' => sprintf(__('Unable to reach hCaptcha: %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: hCaptcha validation returned unexpected response.', 'Integration (hcaptcha)');
            return [
                'success' => false,
                'message' => __('Unexpected response from hCaptcha.', '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: hCaptcha validation failed because secret appears invalid.', 'Integration (hcaptcha)');
            return [
                'success' => false,
                'message' => __('Secret key appears to be invalid. Please double-check and try again.', 'griffinforms-form-builder'),
            ];
        }

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

        $this->log->add('success', 'form', $form_id, get_current_user_id(), 'Admin test: hCaptcha secret validated successfully.', 'Integration (hcaptcha)');
        return [
            'success' => true,
            'message' => __('Successfully connected to hCaptcha. 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('hcaptcha_site_key');
        $secret_key = $this->settings->getOption('hcaptcha_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'] = 'checkbox';
            }
            $control = \GriffinForms\Includes\Integrations\FormControls\Factory::create(
                $field['type'],
                $field['name'],
                $field['value'],
                $this->meta,
                $field
            );
            $fields_html .= $control->render();
        }

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

    public function getConfigurationJs(): string
    {
        $form_id = 'griffinforms-hcaptcha-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('hcaptcha');
                });
            }

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

                const formId = window.griffinformsResolveActiveFormId ? window.griffinformsResolveActiveFormId() : null;
                const formData = new FormData(form);
                const siteKey = (formData.get('hcaptcha_site_key') || '').trim();
                const secretKey = (formData.get('hcaptcha_secret_key') || '').trim();
                const mode = formData.get('hcaptcha_widget_mode') || 'checkbox';

                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: 'hcaptcha',
                        nonce: window.griffinformsIntegrationsNonce || '',
                        form_id: formId || '',
                        hcaptcha_site_key: siteKey,
                        hcaptcha_secret_key: secretKey,
                        hcaptcha_widget_mode: mode
                    },
                    success: function(response) {
                        if (response.success) {
                            window.showIntegrationsMessage('success', response.data.message || 'Configuration saved');
                            setTimeout(() => window.loadIntegrationInfo('hcaptcha'), 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');
                    }
                });
            });
        })();
        ";
    }

    public function getFormSettingsSchema(): array
    {
        return [
            [
                'name' => 'disable_hcaptcha',
                'type' => 'checkbox',
                'label' => __('Disable hCaptcha on this form', 'griffinforms-form-builder'),
            ],
        ];
    }

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

    public function validateFormSettings(array $settings)
    {
        return [
            'disable_hcaptcha' => $this->toBoolean($settings['disable_hcaptcha'] ?? 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_hcaptcha', 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_hcaptcha'] ?? false);
                if ($disable) {
                    return false;
                }
            }
        }

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

}
