<?php

namespace KupShop\OrderDiscountBundle\Triggers;

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

class DeliveryTypeTrigger extends AbstractTrigger
{
    protected static $type = 'delivery_type';
    protected static $position = 100;
    protected $adminTemplate = 'triggers/delivery_type.tpl';

    /** @var Cart */
    private $cart;

    /**
     * @required
     */
    public function setCart(Cart $cart): void
    {
        $this->cart = $cart;
    }

    public function getDiscountFilterSpec(PurchaseState $purchaseState)
    {
        if (!($deliveryTypeId = $this->cart->transport)) {
            return Operator::equals(['odt.type' => static::getType()]);
        }

        return Operator::andX(
            Operator::equals(['odt.type' => static::getType()]),
            Operator::orX(
                Operator::andX(
                    JsonOperator::contains('odt.data', 'delivery_type', (string) $deliveryTypeId),
                    JsonOperator::contains('odt.data', 'delivery_type_invert', 'invert')
                ),
                Operator::andX(
                    Operator::not(JsonOperator::contains('odt.data', 'delivery_type', (string) $deliveryTypeId)),
                    Operator::not(JsonOperator::contains('odt.data', 'delivery_type_invert', 'invert'))
                )
            )
        );
    }

    protected function getVars($vars): array
    {
        $vars = parent::getVars($vars);

        $vars['deliveryTypes'] = \DeliveryType::getAll();

        return $vars;
    }
}
