<?php

namespace EasyLinkAutomations\Triggers\ElementorPro;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires once per field when an Elementor Pro form is submitted,
 * allowing automations to filter by a specific field ID and value.
 */
final class FormSubmittedWithSpecificValueTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'elementor-pro/form_submitted_with_specific_value';
    }

    public static function getName(): string
    {
        return __('Form Submitted with Specific Field Value', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Fires when an Elementor Pro form is submitted with a specific field value.', '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'],
            'field_id'    => ['label' => 'Field ID', 'type' => 'string'],
            'field_value' => ['label' => 'Field Value', '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;
                }
                foreach ($record->get('fields') as $field) {
                    $data = $this->handle($record, $field);
                    if (empty($data)) {
                        continue;
                    }
                    $this->fire($data);
                }
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] ElementorPro FormSubmittedWithSpecificValue trigger error: ' . $e->getMessage());
            }
        }, 10, 2);
    }

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

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

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

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

        return array_merge([
            'form_id'     => $formSettings['form_post_id'] . '_' . $formSettings['id'],
            'form_name'   => $formSettings['form_name'] ?? '',
            'field_id'    => $field['id'] ?? '',
            'field_value' => $field['value'] ?? '',
        ], $allFields);
    }
}
