<?php

namespace EasyLinkAutomations\Triggers\ElementorPro;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

final class NewUserSubmitsFormTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'elementor-pro/new_user_submits_form';
    }

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

    public static function getDescription(): string
    {
        return __('Fires when a new (first-time) user submits an Elementor Pro form.', 'easylink-automations');
    }

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

    public static function getIcon(): string
    {
        return 'elementor-pro';
    }

    public static function isAvailable(): bool
    {
        return class_exists('ElementorPro\Plugin');
    }

    public static function getOutputFields(): array
    {
        return [
            'form_id'   => ['label' => 'Form ID', 'type' => 'string'],
            'form_name' => ['label' => 'Form Name', 'type' => 'string'],
        ];
    }

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

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

        add_action('elementor_pro/forms/new_record', function ($record, $handler): void {
            try {
                if (!is_object($record) || !method_exists($record, 'get')) {
                    return;
                }
                $data = $this->handle($record, $handler);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] ElementorPro NewUserSubmitsForm trigger error: ' . $e->getMessage());
            }
        }, 10, 2);
    }

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

        if (!is_object($record) || !method_exists($record, 'get')) {
            return [];
        }

        $formSettings = $record->get('form_settings');
        $fields       = [];

        foreach ($record->get('fields') as $field) {
            $key          = str_replace(' ', '_', strtolower($field['title'] ?? $field['id'] ?? ''));
            $fields[$key] = $field['value'] ?? '';
        }

        return array_merge([
            'form_id'   => $formSettings['form_post_id'] . '_' . $formSettings['id'],
            'form_name' => $formSettings['form_name'] ?? '',
        ], $fields);
    }
}
