<?php

namespace EasyLinkAutomations\Triggers\NinjaForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user submits a Ninja Forms form.
 */
final class UserSubmitFormTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'ninja-forms/user_submits_ninjaforms';
    }

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

    public static function getDescription(): string
    {
        return __('Fires when a user submits a Ninja Forms form.', 'easylink-automations');
    }

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

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

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

    public static function getOutputFields(): array
    {
        return [
            'form_id'    => ['label' => 'Form ID', 'type' => 'number'],
            'form_title' => ['label' => 'Form Title', 'type' => 'string'],
            'fields'     => ['label' => 'Form Fields', 'type' => 'json'],
        ];
    }

    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 (!function_exists('Ninja_Forms')) {
            return $options;
        }

        $forms = Ninja_Forms()->form()->get_forms();
        if (is_array($forms)) {
            foreach ($forms as $form) {
                $options[] = [
                    'value' => (string) $form->get_id(),
                    'label' => $form->get_setting('title') ?: ('Form #' . $form->get_id()),
                ];
            }
        }

        return $options;
    }

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

        add_action('ninja_forms_after_submission', function (array $data): void {
            try {
                if (empty($data) || !isset($data['form_id']) || !isset($data['fields_by_key'])) {
                    return;
                }
                $result = $this->handle($data);
                if (empty($result)) {
                    return;
                }
                $this->fire($result);
            } catch (\Throwable $e) {
                error_log('[EasyLink Automations] NinjaForms trigger error: ' . $e->getMessage());
            }
        }, 10, 1);
    }

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

        if (empty($data) || !isset($data['form_id']) || !isset($data['fields_by_key'])) {
            return [];
        }

        $context            = [];
        $context['form_id'] = (int) $data['form_id'];

        foreach ($data['fields_by_key'] as $key => $field) {
            $context[$key] = $field['value'] ?? '';
        }

        return $context;
    }
}
