<?php

namespace EasyLinkAutomations\Triggers\GravityForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

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

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

    public static function getDescription(): string
    {
        return __('Fires when a user submits a Gravity Forms form.', '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 [
            'entry_id'     => ['label' => 'Entry ID', 'type' => 'number'],
            'form_id'      => ['label' => 'Form ID', 'type' => 'number'],
            'form_title'   => ['label' => 'Form Title', 'type' => 'string'],
            'date_created' => ['label' => 'Date Created', 'type' => 'string'],
            'source_url'   => ['label' => 'Source URL', 'type' => 'string'],
            'ip'           => ['label' => 'IP Address', 'type' => 'string'],
            'status'       => ['label' => 'Status', 'type' => 'string'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [
            'form_id' => [
                'label'    => 'Select Form',
                'type'     => 'select',
                'options'  => static::getAvailableForms(),
                'required' => true,
            ],
        ];
    }

    private static function getAvailableForms(): array
    {
        $options = [];

        if (class_exists('GFAPI')) {
            $forms = \GFAPI::get_forms();
            if (is_array($forms)) {
                foreach ($forms as $form) {
                    $options[] = [
                        'value' => (string) $form['id'],
                        'label' => $form['title'] ?? ('Form #' . $form['id']),
                    ];
                }
            }
        }

        return $options;
    }

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

        add_action('gform_after_submission', function ($entry, $form): void {
            try {
                $data = $this->handle($entry, $form);
                if (empty($data)) {
                    return;
                }
                $this->fire($data);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] GravityForms trigger error: ' . $e->getMessage());
            }
        }, 10, 2);
    }

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

        if (isset($entry['status']) && 'spam' === $entry['status']) {
            return [];
        }

        $context = [
            'entry_id'     => (int) ($entry['id'] ?? 0),
            'form_id'      => (int) ($entry['form_id'] ?? 0),
            'form_title'   => $form['title'] ?? '',
            '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;
    }
}
