<?php

namespace KupShop\OrderDiscountBundle\Triggers;

use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Query\JsonOperator;
use KupShop\OrderingBundle\Entity\Purchase\PurchaseState;
use Query\Operator;

class UserGroupTrigger extends AbstractTrigger
{
    protected static $type = 'user_group';
    protected static $position = 62;
    protected $adminTemplate = 'triggers/user_group.tpl';

    /** @var UserContext */
    private $userContext;

    /**
     * @return $this
     *
     * @required
     */
    public function setUserContext(UserContext $userContext)
    {
        $this->userContext = $userContext;

        return $this;
    }

    public function getDiscountFilterSpec(PurchaseState $purchaseState)
    {
        $specs = [
            Operator::equals(['odt.type' => static::getType()]),
        ];

        $orSpecs = [];
        foreach ($this->getUserGroups() as $id => $_) {
            $orSpecs[] = JsonOperator::contains('odt.data', 'groups', $id);
        }

        $specs[] = Operator::orX(
            Operator::andX(
                Operator::orX($orSpecs),
                JsonOperator::contains('odt.data', 'groups_invert', 'invert')
            ),
            Operator::andX(
                Operator::not(Operator::orX($orSpecs)),
                Operator::not(JsonOperator::contains('odt.data', 'groups_invert', 'invert'))
            )
        );

        return Operator::andX($specs);
    }

    public function handleData($data)
    {
        $data['groups'] = array_map('intval', $data['groups']);

        return $data;
    }

    protected function getVars($vars): array
    {
        $vars['user_groups'] = sqlQuery('SELECT id, name FROM users_groups')->fetchAll();

        return $vars;
    }

    private function getUserGroups(): array
    {
        return $this->userContext->getActive()?->getGroups() ?: [0 => ''];
    }
}
