<?php

namespace RTMCustomMails\ObjectSupport;

use RTMCustomMails\ConditionProcessor\UserHasRoleCondition;
use WP_User;
use WP_User_Query;

class EmailUserSupport extends EmailObjectSupport
{

    public function __construct()
    {
        parent::__construct('user');
    }

    protected function getSelectorConfig(): array
    {
        return [
            'valueField' => 'id',
            'textField' => 'name',
            'searchField' => [
                [
                    'field' => 'name',
                    'weight' => 2
                ],
                [
                    'field' => 'email',
                    'weight' => 1.5
                ],
                [
                    'field' => 'id',
                    'weight' => 0.5
                ]
            ],
            'render' => [
                'option' => '<div>{id}: {name} ({email})</div>',
                'item' => '<div>{id}: {name} ({email})</div>',
            ]
        ];
    }

    public function getAllowedContextVariables($vars = []): array
    {
        return $vars;
    }

    public function findObjects(array $objects, string $search): array
    {
        $query = new WP_User_Query([
            'search' => '*' . esc_attr($search) . '*',
            'search_columns' => [
                'user_login',
                'user_nicename',
                'user_email',
            ],
            'number' => 20,
            'orderby' => 'ID',
            'order' => 'DESC'
        ]);
        $users = $query->get_results();
        return array_merge($objects, array_map([$this, 'simplifyUser'], $users));
    }

    public function simplifyUser(WP_User $user): array
    {
        return [
            'value' => $user->ID,
            'label' => $user->display_name ?: $user->user_email,
        ];
    }

    public function getLatestObjects(int $amount = 20): array
    {
        $users = get_users([
            'role__not_in' => ['administrator'],
            'number' => $amount,
            'orderby' => 'ID',
            'order' => 'DESC'
        ]);
        return array_map([$this, 'simplifyUser'], $users);
    }

    public function addTriggerHookOptions(array $options = []): array
    {
        return $options + [
                'woocommerce_reset_password_notification' => 'User password was reset.'
            ];
    }

    public function addConditionFunctions(array $functionClasses = []): array
    {
        return [
            ...$functionClasses,
            UserHasRoleCondition::class,
        ];
    }
}