<?php

namespace EasyLinkAutomations\Triggers\GravityForms;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

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

    public static function getName(): string
    {
        return __('User Registered via Gravity Forms', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Fires when a user registers through 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 [
            ['key' => 'user_id', 'label' => 'User ID', 'type' => 'integer'],
            ['key' => 'user_login', 'label' => 'Username', 'type' => 'string'],
            ['key' => 'user_email', 'label' => 'Email', 'type' => 'string'],
            ['key' => 'display_name', 'label' => 'Display Name', 'type' => 'string'],
            ['key' => 'entry_id', 'label' => 'Entry ID', 'type' => 'integer'],
            ['key' => 'form_id', 'label' => 'Form ID', 'type' => 'integer'],
        ];
    }

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

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

        add_action('gform_user_registered', function ($user_id, $feed, $entry, $password): void {
            $data = $this->handle($user_id, $feed, $entry, $password);
            if (empty($data)) {
                return;
            }
            $this->fire($data);
        }, 10, 4);
    }

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

        $user = get_userdata($user_id);
        if (!$user) {
            return [];
        }

        return [
            'user_id'      => $user->ID,
            'user_login'   => $user->user_login,
            'user_email'   => $user->user_email,
            'display_name' => $user->display_name,
            'first_name'   => $user->first_name,
            'last_name'    => $user->last_name,
            'entry_id'     => isset($entry['id']) ? $entry['id'] : '',
            'form_id'      => isset($entry['form_id']) ? $entry['form_id'] : '',
        ];
    }
}
