<?php

namespace EasyLinkAutomations\Triggers\WordPress;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a user logs in.
 */
final class UserLoginTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'wordpress/user_login';
    }

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

    public static function getDescription(): string
    {
        return __('Triggers when a user logs in to the site', 'easylink-automations');
    }

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

    public static function getIcon(): string
    {
        return 'user-add';
    }

    public static function getOutputFields(): array
    {
        return [
            'user_id'      => ['label' => 'User ID', 'type' => 'number'],
            'user_login'   => ['label' => 'Username', 'type' => 'string'],
            'user_email'   => ['label' => 'Email', 'type' => 'email'],
            'display_name' => ['label' => 'Display Name', 'type' => 'string'],
            'first_name'   => ['label' => 'First Name', 'type' => 'string'],
            'last_name'    => ['label' => 'Last Name', 'type' => 'string'],
            'role'         => ['label' => 'Role', 'type' => 'string'],
            'login_time'   => ['label' => 'Login Time', 'type' => 'datetime'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [
            'roles' => [
                'label'   => 'Only these roles (optional)',
                'type'    => 'multi_select',
                'options' => 'dynamic:roles',
            ],
        ];
    }

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

        add_action('wp_login', function ($userLogin, $user): void {
            $data = $this->handle($user);
            $this->fire($data);
        }, 10, 2);
    }

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

        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,
            'role'         => $user->roles[0] ?? '',
            'login_time'   => current_time('mysql'),
        ];
    }
}
