<?php

namespace EasyLinkAutomations\Actions\CleverReach;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Triggers a CleverReach automation flow that sends the double opt-in mailing.
 *
 * CleverReach recommends letting the platform own the DOI mailing so the
 * confirmation link, activation and consent audit trail stay consistent.
 * The optional doidata block records the legal proof of consent.
 *
 * CleverReach REST API v3: POST /v3/flow/flow/{flow_id}/send
 */
final class SendDoubleOptInAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'cleverreach/doi_send';
    }

    public static function getName(): string
    {
        return __('Send Double Opt-In Email', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Send the CleverReach double opt-in confirmation email to a subscriber', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'CleverReach';
    }

    public static function getIcon(): string
    {
        return 'cleverreach';
    }

    public static function getRequiresConnection(): ?string
    {
        return 'cleverreach';
    }

    public static function getConfigFields(): array
    {
        return [
            'flow_id' => [
                'label'            => 'Flow ID',
                'type'             => 'text',
                'required'         => true,
                'supports_mapping' => true,
                'placeholder'      => '123456',
                'description'      => 'The ID of the CleverReach form whose double opt-in email you want to send. '
                    . 'Create the form and its DOI template in CleverReach first, then copy the Flow ID from that form.',
            ],
            'receiver_id' => [
                'label'            => 'Subscriber',
                'type'             => 'text',
                'required'         => true,
                'supports_mapping' => true,
                'placeholder'      => '{{email}}',
                'description'      => 'Email address or CleverReach receiver ID of the subscriber to confirm. The subscriber must already exist in CleverReach.',
            ],
            'user_ip' => [
                'label'            => 'Consent IP Address',
                'type'             => 'text',
                'required'         => false,
                'supports_mapping' => true,
                'placeholder'      => '{{ip_address}}',
                'description'      => 'Recorded as proof of consent. Strongly recommended where double opt-in is legally required.',
            ],
            'referer' => [
                'label'            => 'Consent URL',
                'type'             => 'text',
                'required'         => false,
                'supports_mapping' => true,
                'placeholder'      => 'https://example.com/newsletter',
                'description'      => 'The page the subscriber signed up from.',
            ],
            'user_agent' => [
                'label'            => 'Consent User Agent',
                'type'             => 'text',
                'required'         => false,
                'supports_mapping' => true,
                'description'      => 'The browser user agent captured at signup.',
            ],
        ];
    }

    public function execute(array $triggerData, array $config): array
    {
        $mapped  = $this->mapConfig($config, $triggerData);
        $missing = $this->validateRequired($mapped);
        if ($missing) {
            return [
                'success' => false,
                'message' => 'Missing required fields after mapping: ' . implode(', ', $missing),
                'data'    => [],
            ];
        }

        $connectionId = (int) ($config['connection_id'] ?? 0);

        $body = ['receiver_id' => trim((string) $mapped['receiver_id'])];

        $doiData = array_filter([
            'user_ip'    => trim((string) ($mapped['user_ip'] ?? '')),
            'referer'    => trim((string) ($mapped['referer'] ?? '')),
            'user_agent' => trim((string) ($mapped['user_agent'] ?? '')),
        ], static fn (string $value): bool => $value !== '');

        if ($doiData) {
            $body['doidata'] = $doiData;
        }

        return CleverReachRequestHelper::request(
            $connectionId,
            'POST',
            '/flow/flow/' . CleverReachRequestHelper::id($mapped['flow_id']) . '/send',
            $body
        );
    }
}
