<?php

namespace RTMCustomMails\ConditionProcessor;

use RTMCustomMails\SupportedObjectTypes;
use RTMMailComposer\ConditionProcessor\ConditionFunctionInterface;

class UserHasRoleCondition implements ConditionFunctionInterface
{

    public function __construct()
    {
    }

    public function getObjectType(): string
    {
        return SupportedObjectTypes::USER->value;
    }

    public function getName(): string
    {
        return 'user_has_role';
    }

    public function getParameters(): array
    {
        $names = wp_roles()->get_names();
        $oneOf = array_map(fn($key, $value) => [
            'const' => $key,
            'title' => $value
        ], array_keys($names), array_values($names));

        return [
            'role' => [
                'title' => 'Role',
                'type' => 'string',
                'required' => true,
                'oneOf' => $oneOf
            ]
        ];
    }


    public function evaluate(array $context, ...$args): bool
    {
        $user = $context['user'] ?? null;
        $role = $args['role'] ?? '';

        return in_array($role, $user?->roles ?? []);
    }
}
