<?php

namespace Formatrica\Integrations;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Integration Manager
 *
 * Provides metadata and helpers for third-party integrations like Zapier and Make.com.
 * Self-contained, no hooks, just data and utility methods.
 */
final class Integration_Manager
{
    /**
     * Get all available integrations with their metadata
     *
     * @return array<string, array<string, mixed>>
     */
    public static function get_integrations(): array
    {
        return [
            'wordpress_post' => [
                'id' => 'wordpress_post',
                'name' => 'WordPress Post',
                'description' => __('Create WordPress posts (or custom post types) directly from form submissions with taxonomy and meta field mapping.', 'formatrica'),
                'icon' => 'brand-wordpress.svg',
                'docs_url' => '',
                'setup_steps' => [
                    __('Enable the WordPress Post integration in form settings', 'formatrica'),
                    __('Select the post type (post, page, or custom post type)', 'formatrica'),
                    __('Map form fields to post title, content, and excerpt', 'formatrica'),
                    __('Configure taxonomy assignments (categories, tags, custom taxonomies)', 'formatrica'),
                    __('Set custom meta field mappings if needed', 'formatrica'),
                    __('Choose author handling: current user, fixed user, or anonymous', 'formatrica'),
                ],
                'help_text' => __('Posts are created with "pending" status by default for review before publishing.', 'formatrica'),
            ],
            'woocommerce' => [
                'id' => 'woocommerce',
                'name' => 'WooCommerce',
                'description' => __('Generate WooCommerce orders directly from form submissions with product mapping and customer creation.', 'formatrica'),
                'icon' => 'shopping-cart-code.svg',
                'docs_url' => '',
                'setup_steps' => [
                    __('Ensure WooCommerce is installed and active', 'formatrica'),
                    __('Enable the WooCommerce integration in form settings', 'formatrica'),
                    __('Configure product mode: static products or field-based selection', 'formatrica'),
                    __('Map customer details: email, name, phone, billing, and shipping addresses', 'formatrica'),
                    __('Set order status (pending, processing, completed, etc.)', 'formatrica'),
                    __('Optionally enable automatic customer account creation', 'formatrica'),
                ],
                'help_text' => __('Orders are created with mapped products, customer details, and metadata from form submissions.', 'formatrica'),
            ],
            'zapier' => [
                'id' => 'zapier',
                'name' => 'Zapier',
                'description' => __('Connect your forms to 5,000+ apps using Zapier\'s Webhooks by Zapier trigger.', 'formatrica'),
                'icon' => 'bolt.svg',
                'docs_url' => 'https://zapier.com/apps/webhooks/integrations',
                'setup_steps' => [
                    __('Create a new Zap in Zapier', 'formatrica'),
                    __('Choose "Webhooks by Zapier" as the trigger', 'formatrica'),
                    __('Select "Catch Hook" as the event', 'formatrica'),
                    __('Copy the webhook URL provided by Zapier', 'formatrica'),
                    __('Paste it below and save your form', 'formatrica'),
                    __('Submit a test form to send data to Zapier', 'formatrica'),
                ],
                'help_text' => __('Every form submission will be sent to Zapier in real-time.', 'formatrica'),
            ],
            'make' => [
                'id' => 'make',
                'name' => 'Make',
                'description' => __('Automate workflows with Make.com (formerly Integromat) using webhooks.', 'formatrica'),
                'icon' => 'cloud-data-connection.svg',
                'docs_url' => 'https://www.make.com/en/help/tools/webhooks',
                'setup_steps' => [
                    __('Create a new Scenario in Make.com', 'formatrica'),
                    __('Add a "Webhooks" module as the trigger', 'formatrica'),
                    __('Choose "Custom webhook"', 'formatrica'),
                    __('Copy the webhook URL provided by Make', 'formatrica'),
                    __('Paste it below and save your form', 'formatrica'),
                    __('Submit a test form to determine the data structure in Make', 'formatrica'),
                ],
                'help_text' => __('Make will receive JSON data with form fields, metadata, and context.', 'formatrica'),
            ],
            'slack' => [
                'id' => 'slack',
                'name' => 'Slack',
                'description' => __('Send real-time notifications to Slack channels using Incoming Webhooks.', 'formatrica'),
                'icon' => 'brand-slack.svg',
                'docs_url' => 'https://api.slack.com/messaging/webhooks',
                'setup_steps' => [
                    __('In Slack, create an incoming webhook and choose a channel', 'formatrica'),
                    __('Copy the webhook URL generated by Slack', 'formatrica'),
                    __('Enable Slack in the form settings and paste the webhook URL', 'formatrica'),
                    __('Optionally customize the message template', 'formatrica'),
                    __('Submit a test form to verify delivery in Slack', 'formatrica'),
                ],
                'help_text' => __('Messages include the form title and submitted field values by default.', 'formatrica'),
            ],
            'mailchimp' => [
                'id' => 'mailchimp',
                'name' => 'Mailchimp',
                'description' => __('Add contacts to a Mailchimp audience automatically, with optional double opt-in.', 'formatrica'),
                'icon' => 'mail-heart.svg',
                'docs_url' => 'https://mailchimp.com/help/about-api-keys/',
                'setup_steps' => [
                    __('Create or locate your Mailchimp API key', 'formatrica'),
                    __('Paste the API key and fetch available audiences', 'formatrica'),
                    __('Choose the list to subscribe users to', 'formatrica'),
                    __('Map the email and name fields from your form', 'formatrica'),
                    __('Decide whether to use double opt-in and save', 'formatrica'),
                ],
                'help_text' => __('Subscribers are created or updated in Mailchimp using the selected field mappings.', 'formatrica'),
            ],
            'brevo' => [
                'id' => 'brevo',
                'name' => 'Brevo',
                'description' => __('Add contacts to a Brevo list automatically, with optional name and tag mapping.', 'formatrica'),
                'icon' => 'send-2.svg',
                'docs_url' => 'https://help.brevo.com/hc/en-us/articles/209467485',
                'setup_steps' => [
                    __('Create an API key in Brevo (SMTP & API → API Keys)', 'formatrica'),
                    __('Paste the API key and fetch your contact lists', 'formatrica'),
                    __('Choose the list to add contacts to', 'formatrica'),
                    __('Map the email and name fields from your form', 'formatrica'),
                    __('Optionally add tags (define a TAGS contact attribute in Brevo) and save', 'formatrica'),
                ],
                'help_text' => __('Contacts are created or updated in Brevo using the selected field mappings. This is separate from the Brevo email-delivery transport.', 'formatrica'),
            ],
            'salesforce' => [
                'id' => 'salesforce',
                'name' => 'Salesforce (Essentials)',
                'description' => __('Create Salesforce leads with the classic Web-to-Lead endpoint—no OAuth required.', 'formatrica'),
                'icon' => 'rosette-discount.svg',
                'docs_url' => 'https://help.salesforce.com/s/articleView?id=sf.leads_web_to_lead_create.htm',
                'setup_steps' => [
                    __('Find your Salesforce organisation ID (Setup → Company Settings)', 'formatrica'),
                    __('Enable Web-to-Lead and copy any assignment rule IDs you plan to use', 'formatrica'),
                    __('Enable the Salesforce integration and enter the organisation ID', 'formatrica'),
                    __('Map form fields (email, name, company, etc.) to Salesforce lead fields', 'formatrica'),
                    __('Submit a test form and confirm the lead appears in Salesforce', 'formatrica'),
                ],
                'help_text' => __('We post the payload securely to Salesforce using their Web-to-Lead endpoint.', 'formatrica'),
            ],
            'hubspot' => [
                'id' => 'hubspot',
                'name' => 'HubSpot',
                'description' => __('Submit contacts to a HubSpot form using a Private App access token.', 'formatrica'),
                'icon' => 'cube-plus.svg',
                'docs_url' => 'https://developers.hubspot.com/docs/api/marketing/forms',
                'setup_steps' => [
                    __('Create a Private App in HubSpot and copy the access token', 'formatrica'),
                    __('Locate the target form and note the portal ID and form GUID', 'formatrica'),
                    __('Enable the HubSpot integration and provide the token, portal ID, and form GUID', 'formatrica'),
                    __('Map form fields to HubSpot properties such as email, firstname, lastname', 'formatrica'),
                    __('Enable GDPR consent messaging if required and save the form', 'formatrica'),
                ],
                'help_text' => __('Each submission is sent to HubSpot using their Forms API with your selected mappings.', 'formatrica'),
            ],
            'twilio' => [
                'id' => 'twilio',
                'name' => 'Twilio SMS',
                'description' => __('Send an SMS notification to a fixed admin number for every submission (Pro).', 'formatrica'),
                'icon' => 'brand-twilio.svg',
                'docs_url' => 'https://www.twilio.com/docs/usage/api',
                'setup_steps' => [
                    __('Create an API key (SID + secret) in the Twilio console', 'formatrica'),
                    __('Enter your Account SID, API key SID, and API key secret', 'formatrica'),
                    __('Choose the sender: a Twilio phone number or a Messaging Service SID', 'formatrica'),
                    __('Enter the recipient number in E.164 format (e.g. +15551234567)', 'formatrica'),
                    __('Optionally customise the message template and save', 'formatrica'),
                ],
                'help_text' => __('One SMS is sent per submission, asynchronously. Messages are capped at 1000 characters.', 'formatrica'),
            ],
            'webhook' => [
                'id' => 'webhook',
                'name' => 'Custom Webhooks',
                'description' => __('Send form submissions to any custom webhook endpoint with optional HMAC signature verification.', 'formatrica'),
                'icon' => 'world-share.svg',
                'docs_url' => '',
                'setup_steps' => [
                    __('Enable custom webhooks in form settings', 'formatrica'),
                    __('Enter your webhook endpoint URL', 'formatrica'),
                    __('Optionally provide a secret key for HMAC-SHA256 signature verification', 'formatrica'),
                    __('Configure any custom payload transformations using filters', 'formatrica'),
                    __('Submit a test form to verify delivery', 'formatrica'),
                ],
                'help_text' => __('Webhook requests include form data, metadata, and context. The X-Formatrica-Signature header is included when a secret key is set.', 'formatrica'),
            ],
        ];
    }

    /**
     * Get a single integration by ID
     *
     * @param string $integration_id
     * @return array<string, mixed>|null
     */
    public static function get_integration(string $integration_id): ?array
    {
        $integrations = self::get_integrations();
        return $integrations[$integration_id] ?? null;
    }

    /**
     * Validate integration settings
     *
     * @param string $integration_id
     * @param array<string, mixed> $settings
     * @return array{valid: bool, errors: array<string>}
     */
    public static function validate_settings(string $integration_id, array $settings): array
    {
        $errors = [];

        if (!self::get_integration($integration_id)) {
            $errors[] = __('Unknown integration.', 'formatrica');
            return ['valid' => false, 'errors' => $errors];
        }

        $enabled = $settings['enabled'] ?? false;
        $webhook_url = $settings['webhook_url'] ?? '';

        if ($enabled && empty(trim($webhook_url))) {
            $errors[] = __('Webhook URL is required when integration is enabled.', 'formatrica');
        }

        if ($enabled && !empty($webhook_url) && !filter_var($webhook_url, FILTER_VALIDATE_URL)) {
            $errors[] = __('Invalid webhook URL format.', 'formatrica');
        }

        return [
            'valid' => empty($errors),
            'errors' => $errors,
        ];
    }

    /**
     * Get example payload structure for an integration
     *
     * @param string $integration_id
     * @return array<string, mixed>
     */
    public static function get_example_payload(string $integration_id): array
    {
        return [
            'form' => [
                'id' => 42,
                'title' => 'Contact Form',
            ],
            'submission' => [
                'first_name' => 'Ada',
                'last_name' => 'Lovelace',
                'user_email' => 'ada@example.com',
                'message' => 'Hello from Formatrica!',
            ],
            'meta' => [
                'fields' => [
                    [
                        'id' => 'text-1a2b3c',
                        'type' => 'text',
                        'name' => 'first_name',
                        'label' => 'First name',
                    ],
                    [
                        'id' => 'email-4d5e6f',
                        'type' => 'email',
                        'name' => 'user_email',
                        'label' => 'Email',
                    ],
                ],
            ],
            'context' => [
                'ip_address' => '203.0.113.4',
                'user_agent' => 'Mozilla/5.0 ...',
                'integration' => $integration_id,
            ],
            'integration' => $integration_id,
        ];
    }
}
