<?php

namespace KupShop\OrderDiscountBundle\Triggers;

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

class DiscountAppliedTrigger extends AbstractTrigger
{
    protected static $type = 'discount_applied';
    protected static $position = 75;
    protected $adminTemplate = 'triggers/discount_applied.tpl';

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

        if (!empty($purchaseState->getUsedDiscounts())) {
            if (in_array(0, $discounts)) {
                return true;
            }

            foreach ($discounts as $discount) {
                if (!in_array($discount, $purchaseState->getUsedDiscounts())) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }

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

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

        return $vars;
    }
}
