<?php

namespace EasyLinkAutomations\Triggers\GravityForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

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

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

    public static function getDescription(): string
    {
        return __('Fires when a user submits a Gravity Forms payment form and payment is completed.', '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' => 'payment_status', 'label' => 'Payment Status', 'type' => 'string'],
            ['key' => 'payment_amount', 'label' => 'Payment Amount', 'type' => 'string'],
            ['key' => 'currency', 'label' => 'Currency', 'type' => 'string'],
            ['key' => 'payment_method', 'label' => 'Payment Method', 'type' => 'string'],
            ['key' => 'transaction_id', 'label' => 'Transaction ID', 'type' => 'string'],
        ];
    }

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

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

        add_action('gform_post_payment_completed', function ($entry, $action): void {
            $data = $this->handle($entry, $action);
            if (empty($data)) {
                return;
            }
            $this->fire($data);
        }, 10, 2);
    }

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

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

        return [
            'entry_id'       => $entry['id'] ?? '',
            'form_id'        => $entry['form_id'] ?? '',
            'payment_status' => $entry['payment_status'] ?? '',
            'payment_amount' => $entry['payment_amount'] ?? '',
            'currency'       => $entry['currency'] ?? '',
            'payment_method' => $entry['payment_method'] ?? '',
            'transaction_id' => $entry['transaction_id'] ?? '',
            'date_created'   => $entry['date_created'] ?? '',
            'source_url'     => $entry['source_url'] ?? '',
            'ip'             => $entry['ip'] ?? '',
        ];
    }
}
