<?php

namespace EasyLinkAutomations\Triggers\WordPress;

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

use EasyLinkAutomations\Triggers\BaseTrigger;

/**
 * Trigger that fires when a specific user profile field changes value.
 */
final class UserProfileFieldUpdatedTrigger extends BaseTrigger
{
    public static function getSlug(): string
    {
        return 'wordpress/user_profile_field_updated';
    }

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

    public static function getDescription(): string
    {
        return __('Triggers when a specific user profile field changes value', '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' => 'User 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'],
            'profile_field' => ['label' => 'Profile Field', 'type' => 'string'],
            'old_value'     => ['label' => 'Old Value', 'type' => 'string'],
            'new_value'     => ['label' => 'New Value', 'type' => 'string'],
        ];
    }

    public static function getConfigFields(): array
    {
        return [
            'profile_field' => [
                'label'    => 'Profile Field',
                'type'     => 'select',
                'required' => true,
                'options'  => [
                    ['value' => 'user_login',    'label' => 'Username'],
                    ['value' => 'user_email',    'label' => 'Email'],
                    ['value' => 'display_name',  'label' => 'Display Name'],
                    ['value' => 'first_name',    'label' => 'First Name'],
                    ['value' => 'last_name',     'label' => 'Last Name'],
                    ['value' => 'user_url',      'label' => 'Website'],
                    ['value' => 'description',   'label' => 'Biographical Info'],
                    ['value' => 'user_nicename', 'label' => 'Nickname'],
                ],
            ],
        ];
    }

    private const WATCHED_FIELDS = [
        'user_login',
        'user_email',
        'display_name',
        'first_name',
        'last_name',
        'user_url',
        'description',
        'user_nicename',
    ];

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

        add_action('profile_update', function (int $userId, \WP_User $oldUserData): void {
            $newUser = get_userdata($userId);
            if (!$newUser) {
                return;
            }

            foreach (self::WATCHED_FIELDS as $field) {
                $oldValue = (string) ($oldUserData->$field ?? '');
                $newValue = (string) ($newUser->$field ?? '');

                if ($oldValue === $newValue) {
                    continue;
                }

                $data = $this->handle($userId, $oldUserData, $field, $oldValue, $newValue, $newUser);
                $this->fire($data);
                break;
            }
        }, 10, 2);
    }

    public function handle(mixed ...$args): array
    {
        $userId      = (int) $args[0];
        $field       = (string) $args[2];
        $oldValue    = (string) $args[3];
        $newValue    = (string) $args[4];
        $newUser     = $args[5];
        $roles       = $newUser->roles ?? [];

        return [
            'user_id'       => $userId,
            'user_login'    => $newUser->user_login ?? '',
            'user_email'    => $newUser->user_email ?? '',
            'display_name'  => $newUser->display_name ?? '',
            'first_name'    => $newUser->first_name ?? '',
            'last_name'     => $newUser->last_name ?? '',
            'role'          => $roles[0] ?? '',
            'profile_field' => $field,
            'old_value'     => $oldValue,
            'new_value'     => $newValue,
        ];
    }
}
