<?php

namespace EasyLinkAutomations\Triggers\GravityForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

final class FormEntryUpdatedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'gravityforms/form_entry_updated';
    }

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

    public static function getDescription(): string
    {
        return __('Fires when a Gravity Forms entry is updated.', 'easylink-automations');
    }

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

    public static function getIcon(): string
    {
        return 'gravity-form';
    }

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

    public static function getOutputFields(): array
    {
        return [
            ['key' => 'entry_id', 'label' => 'Entry ID', 'type' => 'integer'],
            ['key' => 'form_id', 'label' => 'Form ID', 'type' => 'integer'],
            ['key' => 'date_created', 'label' => 'Date Created', 'type' => 'string'],
            ['key' => 'source_url', 'label' => 'Source URL', 'type' => 'string'],
            ['key' => 'user_agent', 'label' => 'User Agent', 'type' => 'string'],
            ['key' => 'ip', 'label' => 'IP Address', 'type' => 'string'],
            ['key' => 'status', 'label' => 'Status', 'type' => 'string'],
            ['key' => 'currency', 'label' => 'Currency', 'type' => 'string'],
        ];
    }

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

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

        add_action('gform_after_update_entry', function ($form, $entry_id, $original_entry): void {
            $data = $this->handle($form, $entry_id, $original_entry);
            if (empty($data)) {
                return;
            }
            $this->fire($data);
        }, 10, 3);

        add_action('gform_post_update_entry', function ($entry, $original_entry): void {
            $form_id = isset($entry['form_id']) ? $entry['form_id'] : 0;
            $form    = class_exists('GFAPI') ? \GFAPI::get_form($form_id) : [];
            $data    = $this->handle($form, $entry['id'], $original_entry);
            if (empty($data)) {
                return;
            }
            $this->fire($data);
        }, 10, 2);
    }

    public function handle(mixed ...$args): array
    {
        [$form, $entry_id, $original_entry] = $args;

        if (!class_exists('GFAPI')) {
            return [];
        }

        $entry = \GFAPI::get_entry($entry_id);
        if (is_wp_error($entry) || empty($entry)) {
            return [];
        }

        $context = [
            'entry_id'   => $entry['id'],
            'form_id'    => $entry['form_id'],
            'date_created' => $entry['date_created'] ?? '',
            'source_url' => $entry['source_url'] ?? '',
            'user_agent' => $entry['user_agent'] ?? '',
            'ip'         => $entry['ip'] ?? '',
            'status'     => $entry['status'] ?? '',
            'currency'   => $entry['currency'] ?? '',
        ];

        if (!empty($form['fields'])) {
            foreach ($form['fields'] as $field) {
                $field_id    = $field->id;
                $field_label = $field->label;
                $field_value = isset($entry[$field_id]) ? $entry[$field_id] : '';
                $context['field_' . $field_id]             = $field_value;
                $context['field_label_' . $field_id]       = $field_label;
            }
        }

        return $context;
    }
}
