<?php

namespace KupShop\AutomationConfiguratorBundle\Configurator\Orders\Conditions\Fields;

use KupShop\AutomationConfiguratorBundle\Configurator\Generic\Conditions\Groups\User;
use KupShop\AutomationConfiguratorBundle\Configurator\Interfaces\Conditions\Fields\Field;
use KupShop\AutomationConfiguratorBundle\Configurator\Orders\OrdersContext;
use KupShop\AutomationConfiguratorBundle\Util\ExpressionContext;
use Query\QueryBuilder;

class UserGroup extends Field implements OrdersContext
{
    public function getConfig(): array
    {
        $fields = [];

        $userGroups = sqlQueryBuilder()->select('id, name')
            ->from('users_groups')
            ->execute()->fetchAll();

        foreach ($userGroups as $group) {
            $fields[] = ['value' => (string) $group['id'], 'title' => $group['name']];
        }

        return [
            'label' => 'Zákazník je ve skupině',
            'type' => 'multiselect',
            'values' => $fields,
            'operators' => ['multiselect_function'],
            'function' => 'true',
        ];
    }

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

    public function getGroupName(): ?string
    {
        return User::NAME;
    }

    public function getCompareValue(ExpressionContext $context, $args = null)
    {
        $context = $context->getContext();

        return !empty(array_intersect(explode(',', $context['user_groups'] ?? ''), $args[0] ?? []));
    }

    /**
     * @param $context QueryBuilder
     */
    public function modifyPrefetchOnUse($context)
    {
        $context->leftJoin('o', 'users', 'u', 'u.id = o.id_user');

        $context->addSubselect(
            sqlQueryBuilder()->select('GROUP_CONCAT(ugr.id_group)')
                ->from('users_groups_relations', 'ugr')
                ->where('u.id = ugr.id_user'),
            'user_groups');
    }
}
