<?php

namespace EasyLinkAutomations\Triggers\BeaverBuilder;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits a Beaver Builder contact/subscribe form.
 */
final class UserSubmitsContactFormTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'beaver-builder/user_submits_contact_form';
    }

    public static function getName(): string
    {
        return __('User Submits Contact/Subscribe Form', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Fires when a user submits a Beaver Builder contact or subscribe form.', 'easylink-automations');
    }

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

    public static function getIcon(): string
    {
        return 'beaver-builder';
    }

    public static function isAvailable(): bool
    {
        return class_exists('FLBuilder');
    }

    public static function getOutputFields(): array
    {
        return [
            'name'    => ['label' => 'Name', 'type' => 'string'],
            'email'   => ['label' => 'Email', 'type' => 'email'],
            'message' => ['label' => 'Message', 'type' => 'string'],
            'subject' => ['label' => 'Subject', 'type' => 'string'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [];
    }

    public function register(callable $callback): void
    {
        $this->callback = $callback;

        add_action('suretriggers_bb_after_form_submit', function (array $context): void {
            try {
                if (empty($context)) {
                    return;
                }
                $data = $this->handle($context);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] BeaverBuilder trigger error: ' . $e->getMessage());
            }
        }, 10, 1);
    }

    public function handle(mixed ...$args): array
    {
        [$context] = $args;

        if (!is_array($context)) {
            return [];
        }

        return [
            'name'    => (string) ($context['name'] ?? $context['Name'] ?? ''),
            'email'   => (string) ($context['email'] ?? $context['Email'] ?? ''),
            'message' => (string) ($context['message'] ?? $context['Message'] ?? ''),
            'subject' => (string) ($context['subject'] ?? $context['Subject'] ?? ''),
        ];
    }
}
