<?php

namespace GriffinForms\Includes\Integrations;

use GriffinForms\Config;
use GriffinForms\Traits\Singleton;
use GriffinForms\Includes\Addons\Registry as AddonsRegistry;
use GriffinForms\Includes\Libraries\LibraryRegistry;
use GriffinForms\Includes\Packages\PackageAdmission;

/**
 * Provider Registry for all available integrations
 *
 * Manages integration registration and metadata.
 * Supports:
 * - Built-in integrations (in /includes/integrations/)
 * - Paid addon integrations
 * - Third-party external integrations via filters
 *
 * Usage:
 * $providers = Providers::getInstance();
 * $all = $providers->getAll();                    // All providers
 * $provider = $providers->get('stripe');         // Specific provider metadata
 * $integration = $providers->getIntegration('stripe'); // Integration instance
 *
 * @since 1.0.0
 */
class Providers
{
    use Singleton;

    protected $builtin_providers = [];
    protected $addon_providers = [];
    protected $normalized_providers = [];
    protected $blocked_providers = [];
    protected $addons;
    protected $libraries;
    protected $package_admission;
    protected $extension_namespace = 'GriffinForms\\Extensions\\';

    /**
     * Initialize provider registry
     */
    private function __construct()
    {
        $this->addons = AddonsRegistry::getInstance();
        $this->libraries = LibraryRegistry::getInstance();
        $this->package_admission = PackageAdmission::getInstance();
        $this->refresh();
    }

    /**
     * Rebuild provider state for the current request.
     *
     * This allows QA/runtime callers to inject providers or package-state changes
     * and then re-normalize the registry without needing a fresh request.
     */
    public function refresh(): void
    {
        $this->builtin_providers = [];
        $this->addon_providers = [];
        $this->normalized_providers = [];
        $this->blocked_providers = [];

        $this->registerBuiltInProviders();
        $this->registerAddOnProviders();
        $this->normalized_providers = array_merge($this->builtin_providers, $this->addon_providers);
    }

    /**
     * Register all built-in integrations
     * These are included with the core GriffinForms plugin
     */
    private function registerBuiltInProviders()
    {
        $this->builtin_providers = [
            'stripe'     => $this->getStripeProvider(),
            'paypal'     => $this->getPaypalProvider(),
            'square'     => $this->getSquareProvider(),
            'sendgrid'   => $this->getSendGridProvider(),
            'mailgun'    => $this->getMailgunProvider(),
            'custom_smtp'=> $this->getCustomSmtpProvider(),
            'recaptcha'  => $this->getRecaptchaProvider(),
            'cloudflare_turnstile' => $this->getCloudflareTurnstileProvider(),
            'hcaptcha'   => $this->getHCaptchaProvider(),
            'slack'      => $this->getSlackProvider(),
            'microsoft_teams' => $this->getMicrosoftTeamsProvider(),
            'zapier'     => $this->getZapierProvider(),
            'google_sheets' => $this->getGoogleSheetsProvider(),
            'openai'     => $this->getOpenAIProvider(),
            'anthropic'  => $this->getAnthropicProvider(),
            'gemini'     => $this->getGeminiProvider(),
            'xai'        => $this->getXAiProvider(),
            'mistral'    => $this->getMistralProvider(),
            'mailchimp'  => $this->getMailchimpProvider(),
            'klaviyo'    => $this->getKlaviyoProvider(),
            'hubspot'    => $this->getHubSpotProvider(),
            'woocommerce'=> $this->getWooCommerceProvider(),
        ];
        $this->builtin_providers = $this->normalizeProviderCollection($this->builtin_providers);
    }

    /**
     * Register add-on integrations
     * Add-ons can register themselves via the filter hook
     */
    private function registerAddOnProviders()
    {
        // Allow add-ons and extensions to register integrations
        $providers = apply_filters(
            'griffinforms_register_integration_providers',
            []
        );

        $providers = array_merge($providers, apply_filters(
            'griffinforms_addon_integrations',
            []
        ));

        $this->addon_providers = $this->normalizeProviderCollection($providers);
    }

    /**
     * Get all available providers
     *
     * @return array All providers (built-in + addons), keyed by provider ID
     */
    public function getAll(): array
    {
        return $this->normalized_providers;
    }

    /**
     * Get all admitted providers plus any paid providers that are blocked (Pro absent/unlicensed).
     * Used by the integration modal grid so paid integrations remain visible and can show a Pro badge.
     */
    public function getAllIncludingPaidBlocked(): array
    {
        $paid_blocked = array_filter(
            $this->blocked_providers,
            static fn(array $p): bool => !empty($p['is_paid'])
        );
        return array_merge($this->normalized_providers, $paid_blocked);
    }

    /**
     * Get provider metadata by ID
     *
     * @param string $id Provider ID (e.g., 'stripe', 'sendgrid')
     * @param bool $dynamic_status Whether to include dynamic configured/active status from integration class
     * @return array|null Provider metadata or null if not found
     */
    public function get(string $id, bool $dynamic_status = true): ?array
    {
        $provider = $this->normalized_providers[$id] ?? null;

        if ($provider && $dynamic_status) {
            $integration = $this->getIntegration($id);
            if ($integration && method_exists($integration, 'isConfigured')) {
                $provider['configured'] = $integration->isConfigured();
            }
        }

        return $provider;
    }

    public function getRegistered(string $id): ?array
    {
        return $this->normalized_providers[$id] ?? $this->blocked_providers[$id] ?? null;
    }

    public function getBlocked(): array
    {
        return $this->blocked_providers;
    }

    /**
     * Get integration class instance
     *
     * @param string $id Provider ID
     * @return \GriffinForms\Includes\Integrations\Format|null Integration instance or null if not found/not loadable
     */
    public function getIntegration(string $id): ?\GriffinForms\Includes\Integrations\Format
    {
        $provider = $this->get($id, false);  // Pass false to avoid recursive dynamic status check
        if (!$provider) {
            return null;
        }

        $class = apply_filters('griffinforms_integration_class', $provider['class'], $id);

        // If the class is already loaded (by Core or an addon autoloader), use it directly.
        if (!class_exists($class, true)) {
            // For Core-native classes only: resolve file path and attempt a manual require.
            if (strpos($class, 'GriffinForms\\') === 0) {
                $internal_class = str_replace('GriffinForms\\', '', $class);
                $config = Config::getInstance();
                $file = $config->getRootPath() . strtolower(str_replace('\\', '/', $internal_class)) . '.php';

                if (!file_exists($file)) {
                    return null;
                }

                require_once $file;
            }

            if (!class_exists($class, false)) {
                return null;
            }
        }

        try {
            return new $class();
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Merge addon metadata into provider definition.
     *
     * @param array $provider
     * @return array
     */
    private function applyAddonMetadata(array $provider): array
    {
        $provider_id = sanitize_key($provider['id'] ?? '');
        if (empty($provider_id)) {
            return $provider;
        }

        $addon_slug = $provider['addon_slug'] ?? '';
        $addon = null;

        if (!empty($addon_slug)) {
            $addon = $this->addons->get($addon_slug);
        }

        if (!$addon) {
            $addon = $this->addons->getByProvider($provider_id);
        }

        if ($addon) {
            $provider['addon'] = $addon;
            if (!array_key_exists('is_paid', $provider)) {
                $provider['is_paid'] = (bool) ($addon['is_paid'] ?? false);
            }

            $provider['addon_version'] = $addon['version'] ?? null;
            if (!array_key_exists('package_id', $provider)) {
                $provider['package_id'] = !empty($addon['is_paid']) ? 'pro' : 'core';
            }

            if (!array_key_exists('requires_lib', $provider)) {
                $provider['requires_lib'] = true;
            }
        }

        $library = $this->libraries->getByProvider($provider_id);
        if ($library) {
            $provider['library_id'] = $library['id'];
            $provider['library'] = $library;
            $provider['lib_installed'] = !empty($library['state']['active']);
            if (!array_key_exists('requires_lib', $provider)) {
                $provider['requires_lib'] = true;
            }

            if (empty($provider['requires']) || !is_array($provider['requires'])) {
                $provider['requires'] = [];
            }

            $provider['requires']['libraries'] = array_values(array_unique(array_merge(
                (array) ($provider['requires']['libraries'] ?? []),
                [$library['id']]
            )));
        } elseif (!array_key_exists('lib_installed', $provider)) {
            $provider['lib_installed'] = true;
        }

        return $provider;
    }

    private function normalizeProviderCollection(array $providers): array
    {
        $normalized = [];
        $blocked = $this->blocked_providers;

        foreach ($providers as $key => $provider) {
            if (!is_array($provider)) {
                continue;
            }

            $provider = $this->applyAddonMetadata($provider);
            if (empty($provider['id'])) {
                $provider['id'] = sanitize_key((string) $key);
            }

            $provider = $this->package_admission->normalizeProvider($provider, 'integration');
            $normalized_key = sanitize_key((string) ($provider['id'] ?? $key));

            if (empty($provider['package_admitted'])) {
                $blocked[$normalized_key] = $provider;
                continue;
            }

            $normalized[$normalized_key] = $provider;
        }

        $this->blocked_providers = $blocked;

        return $normalized;
    }

    /**
     * Get integrations filtered by category
     *
     * @param string $category Category name (e.g., 'Payments', 'Email')
     * @return array Providers in the specified category
     */
    public function getByCategory(string $category): array
    {
        return array_filter($this->getAll(), function($provider) use ($category) {
            return ($provider['category'] ?? '') === $category;
        });
    }

    /**
     * Get all unique categories
     *
     * @return array Array of category names
     */
    public function getCategories(): array
    {
        $categories = array_unique(array_map(function($provider) {
            return $provider['category'] ?? 'Other';
        }, $this->getAll()));

        return array_values($categories);
    }

    /**
     * Check if integration is available and enabled
     *
     * @param string $id Provider ID
     * @return bool True if available and enabled
     */
    public function isAvailable(string $id): bool
    {
        $provider = $this->get($id);
        return $provider && ($provider['enabled'] ?? false);
    }

    // ========== Built-In Provider Definitions ==========

    /**
     * Stripe payment integration provider metadata
     */
    private function getStripeProvider(): array
    {
        $config = Config::getInstance();

        return [
            // Basic Info
            'id'              => 'stripe',
            'name'            => 'Stripe',
            'category'        => 'Payments',
            'category_type'   => 'payment',
            'description'     => __('Accept credit and debit card payments securely through Stripe. Supports on-site one-time payments with Elements; subscriptions and webhooks will be added in a future release.', 'griffinforms-form-builder'),
            'version'         => '1.0.0',

            // Classification
            'enabled'         => true,
            'is_paid'         => false,
            'is_beta'         => false,
            'priority'        => 5,
            'tags'            => ['payment', 'stripe', 'credit-card', 'subscription'],

            // Status & Configuration
            'configured'      => false,
            'active'          => false,
            'requires_lib'    => false,
            'lib_installed'   => true,

            // Class References
            'class'           => '\\GriffinForms\\Includes\\Integrations\\Stripe\\Main',

            // UI Assets
            'icon'            => $config->getRootUrl() . '/admin/images/integrations/stripe.svg',
            'icon_dark'       => $config->getRootUrl() . '/admin/images/integrations/stripe-dark.svg',

            // External References
            'documentation'   => 'https://stripe.com/docs/payments/accept-a-payment',
            'setup_guide'     => '',
            'support_url'     => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',

            // System Requirements
            'requires'        => [
                'php'         => '7.4',
                'modules'     => ['curl', 'json'],
                'libs'        => ['stripe/stripe-php:^10.0'],
            ],

            // Scope & Availability
            'scope'           => [
                'is_global'       => true,
                'allow_override'  => true,
            ],

            // Configuration
            'config_fields'   => ['publishable_key', 'secret_key', 'webhook_secret'],
            'info_notes'      => [
                __('Depending on regional KYC and tax regulations, Stripe may require additional customer data (name, billing address, phone, tax ID). Use the Form Settings button to map these fields for each form.', 'griffinforms-form-builder'),
            ],
        ];
    }

    /**
     * PayPal payment integration provider metadata.
     */
    private function getPaypalProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'              => 'paypal',
            'name'            => 'PayPal',
            'category'        => 'Payments',
            'category_type'   => 'payment',
            'description'     => __('Accept PayPal payments through the official JavaScript SDK and Orders API flow. Supports server-side order creation and capture for one-time payments.', 'griffinforms-form-builder'),
            'version'         => '1.0.0',
            'enabled'         => true,
            'is_paid'         => false,
            'is_beta'         => false,
            'priority'        => 6,
            'tags'            => ['payment', 'paypal', 'wallet', 'checkout'],
            'configured'      => false,
            'active'          => false,
            'requires_lib'    => false,
            'lib_installed'   => true,
            'class'           => '\\GriffinForms\\Includes\\Integrations\\Paypal\\Main',
            'icon'            => $config->getRootUrl() . '/admin/images/integrations/paypal.svg',
            'icon_dark'       => $config->getRootUrl() . '/admin/images/integrations/paypal.svg',
            'documentation'   => 'https://developer.paypal.com/sdk/js/',
            'setup_guide'     => '',
            'support_url'     => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'requires'        => [
                'php'         => '7.4',
                'modules'     => ['curl', 'json'],
                'libs'        => [],
            ],
            'scope'           => [
                'is_global'       => true,
                'allow_override'  => false,
            ],
            'config_fields'   => ['mode', 'client_id', 'client_secret'],
            'info_notes'      => [
                __('PayPal credentials and buyer-facing label/description settings are managed in this integration modal, not in Settings -> Payments.', 'griffinforms-form-builder'),
                __('The buyer approval step runs in the official PayPal popup flow; GriffinForms handles server-side order creation and capture.', 'griffinforms-form-builder'),
            ],
        ];
    }

    private function getSquareProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'square',
            'name'          => 'Square',
            'category'      => 'Payments',
            'category_type' => 'payment',
            'description'   => __('Accept card payments through Square with the Web Payments SDK. Requires GriffinForms Pro.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => true,
            'upsell_key'    => 'square_payments',
            'package_id'    => 'pro',
            'is_beta'       => false,
            'priority'      => 7,
            'tags'          => ['payment', 'square', 'credit-card', 'pos'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\Square\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/square.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/square.svg',
            'documentation' => 'https://developer.squareup.com/docs/web-payments/overview',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => true,
            ],
            'config_fields' => [
                'mode',
                'sandbox_application_id',
                'sandbox_access_token',
                'sandbox_location_id',
                'production_application_id',
                'production_access_token',
                'production_location_id',
            ],
            'info_notes'    => [
                __('Square requires an Application ID, Access Token, and Location ID separately for sandbox and production. All six values can be pre-configured before switching modes.', 'griffinforms-form-builder'),
                __('Credentials and buyer-facing label/description are managed here. The buyer completes payment via the Square Web Payments card form rendered inline on the review screen.', 'griffinforms-form-builder'),
            ],
        ];
    }

    /**
     * SendGrid email integration provider metadata
     */
    private function getSendGridProvider(): array
    {
        $config = Config::getInstance();

        return [
            // Basic Info
            'id'              => 'sendgrid',
            'name'            => 'SendGrid',
            'category'        => 'Email',
            'category_type'   => 'mailer',
            'description'     => __('Deliver transactional and marketing emails reliably through SendGrid\'s trusted email delivery platform. Features include form notifications, autoresponders, email templates, and detailed delivery analytics.', 'griffinforms-form-builder'),
            'version'         => '1.0.0',

            // Classification
            'enabled'         => true,
            'is_paid'         => false,
            'is_beta'         => false,
            'priority'        => 10,
            'tags'            => ['email', 'smtp', 'sendgrid', 'transactional', 'newsletter'],

            // Status & Configuration
            'configured'      => false,
            'active'          => false,
            'requires_lib'    => false,
            'lib_installed'   => true,

            // Class References
            'class'           => '\\GriffinForms\\Includes\\Integrations\\SendGrid\\Main',

            // UI Assets
            'icon'            => $config->getRootUrl() . '/admin/images/integrations/sendgrid.jpg',
            'icon_dark'       => $config->getRootUrl() . '/admin/images/integrations/sendgrid.jpg',

            // External References
            'documentation'   => 'https://docs.sendgrid.com/',
            'setup_guide'     => '',
            'support_url'     => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',

            // System Requirements
            'requires'        => [
                'php'         => '7.2',
                'modules'     => ['curl', 'json'],
                'libs'        => ['sendgrid/sendgrid:^7.14'],
            ],

            // Scope & Availability
            'scope'           => [
                'is_global'       => true,
                'allow_override'  => false,
            ],

            // Configuration
            'config_fields'   => ['api_key'],
            'info_notes'      => [
                __('Prefer SMTP credentials from SendGrid? Use the Custom SMTP integration for the same account if API access is restricted.', 'griffinforms-form-builder'),
            ],
        ];
    }

    private function getMailgunProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'              => 'mailgun',
            'name'            => 'Mailgun',
            'category'        => 'Email',
            'category_type'   => 'mailer',
            'description'     => __('Send transactional and marketing campaigns through Mailgun with regional endpoints, domain-level credentials, and delivery analytics.', 'griffinforms-form-builder'),
            'version'         => '1.0.0',
            'enabled'         => true,
            'is_paid'         => false,
            'is_beta'         => false,
            'priority'        => 15,
            'tags'            => ['email', 'api', 'mailgun', 'transactional'],
            'configured'      => false,
            'active'          => false,
            'requires_lib'    => false,
            'lib_installed'   => true,
            'class'           => '\\GriffinForms\\Includes\\Integrations\\Mailgun\\Main',
            'icon'            => $config->getRootUrl() . '/admin/images/integrations/mailgun.svg',
            'icon_dark'       => $config->getRootUrl() . '/admin/images/integrations/mailgun.svg',
            'documentation'   => 'https://documentation.mailgun.com/',
            'setup_guide'     => '',
            'support_url'     => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'scope'           => [
                'is_global'       => true,
                'allow_override'  => false,
            ],
            'config_fields'   => ['domain', 'api_key', 'region'],
            'info_notes'      => [
                __('Verify your Mailgun domain and DNS records before sending live traffic. Sandbox domains only deliver to authorized recipients until validation is complete.', 'griffinforms-form-builder'),
                __('If your Mailgun plan only exposes SMTP credentials, configure it via the Custom SMTP integration instead of API mode.', 'griffinforms-form-builder'),
            ],
        ];
    }

    /**
     * Custom SMTP integration metadata
     */
    private function getCustomSmtpProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'              => 'custom_smtp',
            'name'            => 'Custom SMTP',
            'category'        => 'Email',
            'category_type'   => 'mailer',
            'description'     => __('Custom SMTP lets you connect any mail server (hosting provider, cPanel mailbox, transactional relay, etc.) using host, port, encryption, and login credentials so GriffinForms can send notifications through your trusted infrastructure.', 'griffinforms-form-builder'),
            'version'         => '1.0.0',
            'enabled'         => true,
            'is_paid'         => false,
            'is_beta'         => false,
            'priority'        => 25,
            'tags'            => ['email', 'smtp', 'mail', 'notifications'],
            'configured'      => false,
            'active'          => false,
            'requires_lib'    => false,
            'lib_installed'   => true,
            'class'           => '\\GriffinForms\\Includes\\Integrations\\CustomSmtp\\Main',
            'icon'            => $config->getRootUrl() . '/admin/images/integrations/custom-smtp.svg',
            'icon_dark'       => $config->getRootUrl() . '/admin/images/integrations/custom-smtp.svg',
            'documentation'   => '',
            'setup_guide'     => '',
            'support_url'     => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'     => false,
            'scope'           => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'config_fields'   => ['smtp_host', 'smtp_port', 'smtp_encryption', 'smtp_username', 'smtp_password'],
        ];
    }

    /**
     * Google reCAPTCHA security integration provider metadata
     */
    private function getRecaptchaProvider(): array
    {
        $config = Config::getInstance();

        return [
            // Basic Info
            'id'              => 'recaptcha',
            'name'            => 'Google reCAPTCHA',
            'category'        => 'Security',
            'category_type'   => 'captcha',
            'description'     => __('Protect forms from spam and abuse using Google\'s intelligent reCAPTCHA v3 technology. Analyzes user behavior to detect suspicious activity without disrupting legitimate users with CAPTCHAs.', 'griffinforms-form-builder'),
            'version'         => '1.0.0',

            // Classification
            'enabled'         => true,
            'is_paid'         => false,
            'is_beta'         => false,
            'priority'        => 15,
            'tags'            => ['security', 'captcha', 'spam-protection', 'google'],

            // Status & Configuration
            'configured'      => false,
            'active'          => false,
            'requires_lib'    => false,
            'lib_installed'   => true,

            // Class References
            'class'           => '\\GriffinForms\\Includes\\Integrations\\Googlerecaptcha\\Main',

            // UI Assets
            'icon'            => $config->getRootUrl() . '/admin/images/integrations/recaptcha.svg',
            'icon_dark'       => $config->getRootUrl() . '/admin/images/integrations/recaptcha-dark.svg',

            // External References
            'documentation'   => 'https://developers.google.com/recaptcha',
            'setup_guide'     => '',
            'support_url'     => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',

            // System Requirements
            'requires'        => [
                'php'         => '7.2',
                'modules'     => ['curl', 'json'],
            ],

            // Scope & Availability
            'scope'           => [
                'is_global'       => true,
                'allow_override'  => true,
            ],

            // Configuration
            'config_fields'   => ['site_key', 'secret_key'],
        ];
    }

    /**
     * Cloudflare Turnstile security integration provider metadata
     */
    private function getCloudflareTurnstileProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'cloudflare_turnstile',
            'name'          => 'Cloudflare Turnstile',
            'category'      => 'Security',
            'category_type' => 'captcha',
            'description'   => __('Privacy-friendly CAPTCHA alternative powered by Cloudflare with managed and invisible modes.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => false,
            'is_beta'       => false,
            'priority'      => 20,
            'tags'          => ['security', 'captcha', 'cloudflare'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\CloudflareTurnstile\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/turnstile.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/turnstile.svg',
            'documentation' => 'https://developers.cloudflare.com/turnstile/',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => true,
            ],
            'requirements'  => [
                'php' => '7.4',
            ],
            'config_fields' => ['site_key', 'secret_key', 'widget_mode'],
        ];
    }

    /**
     * hCaptcha integration provider metadata
     */
    private function getHCaptchaProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'hcaptcha',
            'name'          => 'hCaptcha',
            'category'      => 'Security',
            'category_type' => 'captcha',
            'description'   => __('Privacy-first CAPTCHA alternative compatible with reCAPTCHA workflows, offering drop-in checkbox and invisible modes with improved compliance.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => false,
            'is_beta'       => false,
            'priority'      => 22,
            'tags'          => ['security', 'captcha', 'hcaptcha'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\Hcaptcha\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/hcaptcha.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/hcaptcha.svg',
            'documentation' => 'https://docs.hcaptcha.com/',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'scope'         => [
                'is_global'      => true,
                'allow_override' => true,
            ],
            'requirements'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * Slack notifications integration provider metadata
     */
    private function getSlackProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'slack',
            'name'          => 'Slack',
            'category'      => 'Notifications',
            'description'   => __('Send form submission alerts directly into Slack channels. Launching soon.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => false,
            'is_paid'       => false,
            'is_beta'       => true,
            'priority'      => 25,
            'tags'          => ['notifications', 'chat', 'slack'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\Slack\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/slack.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/slack.svg',
            'documentation' => 'https://api.slack.com/messaging/webhooks',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => true,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => true,
            ],
            'requirements'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * Microsoft Teams notifications integration provider metadata
     */
    private function getMicrosoftTeamsProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'microsoft_teams',
            'name'          => 'Microsoft Teams',
            'category'      => 'Notifications',
            'description'   => __('Post submissions to Microsoft Teams channels via incoming webhooks. Launching soon.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => false,
            'is_paid'       => false,
            'is_beta'       => true,
            'priority'      => 26,
            'tags'          => ['notifications', 'chat', 'teams'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\MicrosoftTeams\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/msteams.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/msteams.svg',
            'documentation' => 'https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => true,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => true,
            ],
            'requirements'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * Zapier automation integration provider metadata
     */
    private function getZapierProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'zapier',
            'name'          => 'Zapier',
            'category'      => 'Automation',
            'description'   => __('Trigger over 5,000+ apps using Zapier webhooks. Launching soon.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => false,
            'is_paid'       => false,
            'is_beta'       => true,
            'priority'      => 30,
            'tags'          => ['automation', 'webhooks', 'zapier'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\Zapier\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/zapier.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/zapier.svg',
            'documentation' => 'https://platform.zapier.com/docs',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => true,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'requirements'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * Google Sheets integration provider metadata
     */
    private function getGoogleSheetsProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'google_sheets',
            'name'          => 'Google Sheets',
            'category'      => 'Productivity',
            'description'   => __('Sync submissions into Google Sheets workbooks automatically. Requires GriffinForms Pro.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => false,
            'is_paid'       => true,
            'package_id'    => 'pro',
            'upsell_key'    => 'google_sheets_sync',
            'is_beta'       => false,
            'priority'      => 32,
            'tags'          => ['sheets', 'google', 'sync'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\GoogleSheets\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/sheets.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/sheets.svg',
            'documentation' => 'https://developers.google.com/sheets/api/guides/concepts',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => true,
            ],
            'requirements'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * OpenAI AI integration provider metadata
     */
    private function getOpenAIProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'openai',
            'name'          => 'OpenAI',
            'category'      => 'AI',
            'description'   => __('Connect your OpenAI API key to power Griffin Assist features. Enter your BYO key to get started.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => false,
            'is_beta'       => false,
            'priority'      => 50,
            'tags'          => ['ai', 'automation', 'chatgpt', 'griffin-assist'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\OpenAI\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/openai.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/openai-dark.svg',
            'documentation' => 'https://platform.openai.com/docs/overview',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'requires'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * Anthropic AI integration provider metadata
     */
    private function getAnthropicProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'anthropic',
            'name'          => 'Anthropic',
            'category'      => 'AI',
            'description'   => __('Connect your Anthropic API key to power Griffin Assist features with Claude. Enter your BYO key to get started.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => false,
            'is_beta'       => false,
            'priority'      => 55,
            'tags'          => ['ai', 'automation', 'claude', 'griffin-assist'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\Anthropic\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/anthropic.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/anthropic-dark.svg',
            'documentation' => 'https://docs.anthropic.com/',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'requires'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * xAI integration provider metadata
     */
    private function getXAiProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'xai',
            'name'          => 'xAI',
            'category'      => 'AI',
            'description'   => __('Connect your xAI API key to power Griffin Assist features with Grok models. Enter your BYO key to get started.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => false,
            'is_beta'       => false,
            'priority'      => 65,
            'tags'          => ['ai', 'grok', 'xai', 'griffin-assist'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\XAi\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/xai.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/xai-dark.svg',
            'documentation' => 'https://docs.x.ai/',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'requires'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * Mistral AI integration provider metadata
     */
    private function getMistralProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'mistral',
            'name'          => 'Mistral AI',
            'category'      => 'AI',
            'description'   => __('Connect your Mistral API key to power Griffin Assist features with Mistral models. Enter your BYO key to get started.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => false,
            'is_beta'       => false,
            'priority'      => 70,
            'tags'          => ['ai', 'mistral', 'griffin-assist'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\Mistral\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/mistral.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/mistral-dark.svg',
            'documentation' => 'https://docs.mistral.ai/',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'requires'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * Google Gemini AI integration provider metadata
     */
    private function getGeminiProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'gemini',
            'name'          => 'Google Gemini',
            'category'      => 'AI',
            'description'   => __('Connect your Google AI API key to power Griffin Assist features with Gemini models. Enter your BYO key to get started.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => false,
            'is_beta'       => false,
            'priority'      => 60,
            'tags'          => ['ai', 'google', 'gemini', 'griffin-assist'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\Gemini\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/gemini.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/gemini-dark.svg',
            'documentation' => 'https://ai.google.dev/docs',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'requires'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * Mailchimp marketing integration provider metadata
     */
    private function getMailchimpProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'mailchimp',
            'name'          => 'Mailchimp',
            'category'      => 'Marketing',
            'description'   => __('Connect Mailchimp globally, discover audiences, and prepare reusable defaults for form-level subscriber sync.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => false,
            'is_beta'       => true,
            'priority'      => 60,
            'tags'          => ['marketing', 'email', 'crm', 'newsletter', 'audience'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'config_fields' => ['api_key', 'default_audience_id', 'default_status'],
            'class'         => '\\GriffinForms\\Includes\\Integrations\\Mailchimp\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/mailchimp.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/mailchimp-dark.svg',
            'documentation' => 'https://mailchimp.com/developer/',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => true,
            ],
            'requirements'  => [
                'php' => '7.4',
            ],
        ];
    }

    private function getKlaviyoProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'klaviyo',
            'name'          => 'Klaviyo',
            'category'      => 'Marketing',
            'category_type' => '',
            'description'   => __('Push contacts into Klaviyo lists and profiles after successful form submissions. Supports custom profile properties and optional consent gating.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => true,
            'is_paid'       => true,
            'package_id'    => 'pro',
            'is_beta'       => true,
            'priority'      => 63,
            'tags'          => ['marketing', 'email', 'crm', 'klaviyo'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'config_fields' => ['api_key', 'default_list_id'],
            'class'         => '\\GriffinForms\\Includes\\Integrations\\Klaviyo\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/klaviyo.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/klaviyo-dark.svg',
            'documentation' => 'https://developers.klaviyo.com/en/reference/api-overview',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => false,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => true,
            ],
            'requirements'  => [
                'php' => '8.2',
            ],
        ];
    }

    /**
     * HubSpot marketing integration provider metadata
     */
    private function getHubSpotProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'hubspot',
            'name'          => 'HubSpot',
            'category'      => 'Marketing',
            'description'   => __('Push leads into HubSpot CRM pipelines and automation workflows directly from form submissions. Launching soon.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => false,
            'is_paid'       => false,
            'is_beta'       => true,
            'priority'      => 65,
            'tags'          => ['crm', 'automation', 'marketing'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => true,
            'class'         => '\\GriffinForms\\Includes\\Integrations\\HubSpot\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/hubspot.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/hubspot.svg',
            'documentation' => 'https://developers.hubspot.com/docs/api/overview',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => true,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => true,
            ],
            'requirements'  => [
                'php' => '7.4',
            ],
        ];
    }

    /**
     * WooCommerce e-commerce integration provider metadata
     */
    private function getWooCommerceProvider(): array
    {
        $config = Config::getInstance();

        return [
            'id'            => 'woocommerce',
            'name'          => 'WooCommerce',
            'category'      => 'E-commerce',
            'description'   => __('Create store customers, draft orders, or trigger follow-up emails in WooCommerce. Launching soon.', 'griffinforms-form-builder'),
            'version'       => '1.0.0',
            'enabled'       => false,
            'is_paid'       => false,
            'is_beta'       => true,
            'priority'      => 55,
            'tags'          => ['ecommerce', 'orders', 'store'],
            'configured'    => false,
            'active'        => false,
            'requires_lib'  => false,
            'lib_installed' => class_exists('\\WooCommerce'),
            'class'         => '\\GriffinForms\\Includes\\Integrations\\WooCommerce\\Main',
            'icon'          => $config->getRootUrl() . '/admin/images/integrations/woo.svg',
            'icon_dark'     => $config->getRootUrl() . '/admin/images/integrations/woo-dark.svg',
            'documentation' => 'https://woocommerce.com/document/',
            'setup_guide'   => '',
            'support_url'   => 'https://wordpress.org/support/plugin/griffinforms-form-builder/',
            'coming_soon'   => true,
            'scope'         => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'requirements'  => [
                'php'     => '7.4',
                'plugins' => ['woocommerce'],
            ],
        ];
    }
}
