<?php

namespace GriffinForms\Includes\Integrations\Mailgun;

use GriffinForms\Includes\Integrations\FormControls\Factory;

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

    protected function buildInfo(): array
    {
        return [
            'id'       => 'mailgun',
            'name'     => 'Mailgun',
            'category' => 'Email',
        ];
    }

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

    public function getLibraryInstructions(): string
    {
        return __('Uses WordPress HTTP API; no additional library required.', 'griffinforms-form-builder');
    }

    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' => 'mailgun_domain', 'label' => __('Domain', 'griffinforms-form-builder'), 'type' => 'text', 'required' => true],
            ['name' => 'mailgun_api_key', 'label' => __('API Key', 'griffinforms-form-builder'), 'type' => 'password', 'required' => true],
            ['name' => 'mailgun_region', 'label' => __('Region', 'griffinforms-form-builder'), 'type' => 'select', 'required' => true],
        ];
    }

    public function isConfigured(): bool
    {
        $domain = $this->settings->getOption('mailgun_domain');
        $api_key = $this->settings->getOption('mailgun_api_key');
        return !empty($domain) && !empty($api_key);
    }

    protected function saveConfiguration(array $config): bool
    {
        try {
            $domain = isset($config['mailgun_domain']) ? sanitize_text_field($config['mailgun_domain']) : '';
            $api_key = isset($config['mailgun_api_key']) ? sanitize_text_field($config['mailgun_api_key']) : '';
            $region = isset($config['mailgun_region']) ? sanitize_text_field($config['mailgun_region']) : 'us';

            if (empty($domain) || empty($api_key)) {
                return false;
            }

            if (!in_array($region, ['us', 'eu'], true)) {
                $region = 'us';
            }

            $this->settings->updateOption('mailgun_domain', $domain, 'mail');
            $this->settings->updateOption('mailgun_api_key', $api_key, 'mail');
            $this->settings->updateOption('mailgun_region', $region, 'mail');

            return true;
        } catch (\Exception $e) {
            $this->log->add('error', 'integration', 0, get_current_user_id(), 'Mailgun save failed: ' . $e->getMessage(), 'mailgun_config');
            return false;
        }
    }

    protected function validateConnection(): array
    {
        $domain = $this->settings->getOption('mailgun_domain');
        $api_key = $this->settings->getOption('mailgun_api_key');
        $region = $this->settings->getOption('mailgun_region', 'us');
        $form_id = $this->resolveFormContextId();

        if (empty($domain) || empty($api_key)) {
            return [
                'success' => false,
                'message' => __('Mailgun domain and API key are required before testing.', 'griffinforms-form-builder'),
            ];
        }

        $base = ($region === 'eu') ? 'https://api.eu.mailgun.net' : 'https://api.mailgun.net';
        $endpoint = sprintf('%s/v3/domains/%s', $base, rawurlencode($domain));

        $response = wp_remote_get($endpoint, [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode('api:' . $api_key),
            ],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            $this->log->add('error', 'form', $form_id, get_current_user_id(), 'Mailgun validation error: ' . $response->get_error_message(), 'Mail Integration (mailgun)');
            return [
                'success' => false,
                /* translators: %s: Mailgun error message */
                'message' => sprintf(__('Mailgun request failed: %s', 'griffinforms-form-builder'), $response->get_error_message()),
            ];
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code === 200) {
            $this->log->add('success', 'form', $form_id, get_current_user_id(), __('Mailgun credentials verified.', 'griffinforms-form-builder'), 'Mail Integration (mailgun)');
            return [
                'success' => true,
                'message' => __('Mailgun credentials verified successfully.', 'griffinforms-form-builder'),
            ];
        }

        $body = wp_remote_retrieve_body($response);
        $this->log->add('error', 'form', $form_id, get_current_user_id(), 'Mailgun validation failed: ' . $body, 'Mail Integration (mailgun)');
        return [
            'success' => false,
            /* translators: %d: HTTP status code */
            'message' => sprintf(__('Mailgun API returned status %d. Check your domain/API key.', 'griffinforms-form-builder'), $code),
        ];
    }

    public function getConfigurationFormHtml(): string
    {
        $domain = $this->settings->getOption('mailgun_domain', '');
        $api_key = $this->settings->getOption('mailgun_api_key', '');
        $region = $this->settings->getOption('mailgun_region', 'us');

        $fields_html = '';
        $factory = Factory::class;

        $fields_html .= $factory::create('text', 'mailgun_domain', $domain, 'mailgun', [
            'label' => __('Mailgun Domain', 'griffinforms-form-builder'),
            'required' => true,
            'description' => __('Example: mg.example.com', 'griffinforms-form-builder'),
        ])->render();

        $fields_html .= $factory::create('password', 'mailgun_api_key', $api_key, 'mailgun', [
            'label' => __('Private API Key', 'griffinforms-form-builder'),
            'required' => true,
        ])->render();

        $fields_html .= $factory::create('select', 'mailgun_region', $region, 'mailgun', [
            'label' => __('Region', 'griffinforms-form-builder'),
            'options' => [
                'us' => __('US Region', 'griffinforms-form-builder'),
                'eu' => __('EU Region', 'griffinforms-form-builder'),
            ],
        ])->render();

        return $this->renderConfigurationFormTemplate('gf-mailgun-config', 'mailgun', $fields_html);
    }

    public function getConfigurationJs(): string
    {
        return "(function(){\n            const form = document.getElementById('gf-mailgun-config');\n            if(!form){return;}\n            const cancelBtn = form.querySelector('.gf-integration-btn-cancel');\n            if(cancelBtn){\n                cancelBtn.addEventListener('click', function(e){\n                    e.preventDefault();\n                    window.loadIntegrationInfo('mailgun');\n                });\n            }\n            form.addEventListener('submit', function(e){\n                e.preventDefault();\n                const formId = window.griffinformsResolveActiveFormId ? window.griffinformsResolveActiveFormId() : null;\n                const formData = new FormData(form);\n                jQuery.ajax({\n                    url: ajaxurl,\n                    type: 'POST',\n                    dataType: 'json',\n                    data: {\n                        action: 'saveIntegrationConfiguration',\n                        integration_id: 'mailgun',\n                        nonce: window.griffinformsIntegrationsNonce || '',\n                        form_id: formId || '',\n                        mailgun_domain: formData.get('mailgun_domain') || '',\n                        mailgun_api_key: formData.get('mailgun_api_key') || '',\n                        mailgun_region: formData.get('mailgun_region') || 'us'\n                    },\n                    success: function(response){\n                        if(response.success){\n                            window.showIntegrationsMessage('success', response.data.message || '" . esc_js(__('Mailgun configuration saved.', 'griffinforms-form-builder')) . "');\n                            setTimeout(function(){ window.loadIntegrationInfo('mailgun'); }, 500);\n                        } else {\n                            const msg = (response.data && response.data.msg) ? response.data.msg : '" . esc_js(__('Failed to save configuration', 'griffinforms-form-builder')) . "';\n                            window.showIntegrationsMessage('danger', msg);\n                        }\n                    },\n                    error: function(){\n                        window.showIntegrationsMessage('danger', '" . esc_js(__('Failed to save configuration', 'griffinforms-form-builder')) . "');\n                    }\n                });\n            });\n        })();";
    }
}
