<?php

namespace EasyLinkAutomations\Triggers\FormidableForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a Formidable Forms entry is updated by a user.
 */
final class EntryUpdatedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'formidable-forms/entry_updated';
    }

    public static function getName(): string
    {
        return __('Form Entry Updated', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Fires when a user updates an existing Formidable Forms entry.', 'easylink-automations');
    }

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

    public static function getIcon(): string
    {
        return 'formidable-forms';
    }

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

    public static function getOutputFields(): array
    {
        return [
            'formidable_form' => ['label' => 'Form ID', 'type' => 'number'],
            'entry_id'        => ['label' => 'Entry ID', 'type' => 'number'],
        ];
    }

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

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

        add_action('frm_after_update_entry', function (int $entryId, int $formId): void {
            $data = $this->handle($entryId, $formId);
            if (empty($data)) {
                return;
            }
            $this->fire($data);
        }, 10, 2);
    }

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

        if (empty($entryId)) {
            return [];
        }

        $fields = [];

        if (class_exists('FrmEntryMeta')) {
            global $wpdb;
            $metas = \FrmEntryMeta::get_entry_meta_info($entryId);
            foreach ($metas as $meta) {
                $fieldId   = $meta->field_id;
                $fieldName = $wpdb->get_var(
                    $wpdb->prepare(
                        'SELECT name FROM ' . $wpdb->prefix . 'frm_fields WHERE id=%d',
                        $fieldId
                    )
                );
                $unserialized = @unserialize($meta->meta_value);
                $dataVal      = (false !== $unserialized) ? $unserialized : $meta->meta_value;
                if (is_array($dataVal)) {
                    foreach ($dataVal as $key => $val) {
                        $fields[$key] = $val;
                    }
                } else {
                    $fields[$fieldName] = $dataVal;
                }
            }
        }

        $context = [
            'formidable_form' => (int) $formId,
            'entry_id'        => (int) $entryId,
        ];

        foreach ($fields as $key => $value) {
            if (!isset($context[$key])) {
                $context[$key] = $value;
            }
        }

        return $context;
    }
}
