<?php

namespace KupShop\OrderDiscountBundle\Triggers;

use KupShop\OrderDiscountBundle\Entity\OrderDiscount;
use KupShop\OrderingBundle\Entity\Purchase\PurchaseState;
use Query\Operator;

class ForbidCombineTrigger extends AbstractTrigger
{
    protected static $type = 'forbid_combine';
    protected static $position = 70;
    protected $adminTemplate = 'triggers/forbid_combine.tpl';

    public function isApplicable(PurchaseState $purchaseState, OrderDiscount $orderDiscount, array $data, ?array $persistentData = null): bool
    {
        $forbiddenDiscounts = $data['discounts'] ?? [];

        if (!empty($purchaseState->getUsedDiscounts())) {
            if (in_array(0, $forbiddenDiscounts)) {
                // Nekombinovat s Jakakoli
                $usedDiscounts = $purchaseState->getUsedDiscounts();
                // krome slev s triggerem 'ignore_forbid_combine'
                $ignore_forbid_combine = sqlQueryBuilder()->select('DISTINCT id_order_discount')
                    ->from('order_discounts_triggers')
                    ->where(Operator::inIntArray($purchaseState->getUsedDiscounts(), 'id_order_discount'))
                    ->andWhere(Operator::equals(['type' => 'ignore_forbid_combine']))
                    ->execute()->fetchFirstColumn();

                $usedDiscounts = array_diff($usedDiscounts, $ignore_forbid_combine);
                if (empty($usedDiscounts)) {
                    return true;
                }

                // krome slev typu Příplatek k objednávce a Uplatnění bodů a Zisk bodů
                $ignore_types = ['orders_charge', 'bonus_program', 'bonus_points_earning'];
                $usedDiscounts = sqlQueryBuilder()->select('DISTINCT id_order_discount')->from('order_discounts_actions')
                    ->where(Operator::inIntArray($usedDiscounts, 'id_order_discount'))
                    ->andWhere(Operator::not(Operator::inStringArray($ignore_types, 'type')))
                    ->execute()->fetchFirstColumn();

                return empty($usedDiscounts);
            }

            foreach ($forbiddenDiscounts as $forbiddenDiscount) {
                if (in_array($forbiddenDiscount, $purchaseState->getUsedDiscounts())) {
                    return false;
                }
            }
        }

        return true;
    }

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

        $vars['discounts'] = sqlQuery('SELECT id, name FROM order_discounts ');

        return $vars;
    }
}
