<?php

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

use KupShop\AutomationConfiguratorBundle\Configurator\Interfaces\Conditions\Fields\Field;
use KupShop\AutomationConfiguratorBundle\Configurator\Users\Conditions\Groups\UserFlags;
use KupShop\AutomationConfiguratorBundle\Configurator\Users\UsersContext;
use KupShop\AutomationConfiguratorBundle\Util\ExpressionContext;
use Query\Operator;
use Query\QueryBuilder;

class UserHasGroup extends Field implements UsersContext
{
    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' => 'Skupina uživatele',
            'type' => 'multiselect',
            'values' => $fields,
            'operators' => ['multiselect_function', 'multiselect_function_not'],
            'function' => 'true',
        ];
    }

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

    public function getGroupName(): ?string
    {
        return UserFlags::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 modifyPrefetchFastCondition($context, $jsonValue)
    {
        [$values, $negation] = $this->prefetchUtil->getMultiSelectValues($jsonValue, true);
        $exists = Operator::exists($this->getUserGroupsQuery()->select('1')->andWhere(Operator::inIntArray($values, 'ugr.id_group')));
        if ($negation) {
            $exists = Operator::not($exists);
        }
        $context->andWhere($exists);

        return $context;
    }

    /**
     * @param $context QueryBuilder
     */
    public function modifyPrefetchOnUse($context)
    {
        $context->addSubselect($this->getUserGroupsQuery()->select('GROUP_CONCAT(ugr.id_group)'), 'user_groups');
    }

    protected function getUserGroupsQuery()
    {
        return sqlQueryBuilder()->from('users_groups_relations', 'ugr')
            ->where('u.id = ugr.id_user');
    }
}
