<?php

namespace KupShop\OrderDiscountBundle\Triggers;

use KupShop\AdminBundle\Admin\ProductsFilter;
use KupShop\OrderDiscountBundle\Entity\OrderDiscount;
use KupShop\OrderingBundle\Entity\Purchase\PurchaseState;
use KupShop\OrderingBundle\Util\Purchase\PurchaseUtil;

class ProductFilterTrigger extends AbstractTrigger
{
    protected static $type = 'product_filter';
    protected static $position = 20;
    protected $adminTemplate = 'block.productsFilter.tpl';
    protected $name = 'Filtr produktů';
    protected $description = 'Akce se bude podmíněna koupí vybraných produktů.';
    private $purchaseUtil;

    public function __construct(PurchaseUtil $purchaseUtil)
    {
        $this->purchaseUtil = $purchaseUtil;
    }

    public function isApplicable(PurchaseState $purchaseState, OrderDiscount $orderDiscount, array $data, ?array $persistentData = null): bool
    {
        $products = $this->purchaseUtil->getProductsApplicableByProductsFilter($purchaseState, $data['filter'] ?? []);
        if (!empty($products)) {
            return true;
        }

        return false;
    }

    protected function getVars($vars): array
    {
        $vars['filterName'] = $vars['name'];
        $vars['filterInputName'] = $vars['name'].'[data][filter]';
        $vars['filter_size'] = 2;
        $vars['filter'] = $vars['data']['filter'] ?? [];

        return $vars;
    }

    public function handleData($data)
    {
        $data = parent::handleData($data);
        $data['filter'] = ProductsFilter::cleanFilter($data['filter'] ?? []);

        return $data;
    }
}
