<?php

namespace KupShop\AutomationConfiguratorBundle\Configurator\Orders\Conditions\Fields;

use KupShop\AutomationConfiguratorBundle\Configurator\Interfaces\Conditions\Fields\Field;
use KupShop\AutomationConfiguratorBundle\Configurator\Orders\OrdersContext;
use KupShop\AutomationConfiguratorBundle\Util\ExpressionContext;
use KupShop\KupShopBundle\Config;

class HasFlag extends Field implements OrdersContext
{
    public function getConfig(): array
    {
        $options = [];

        $cfg = Config::get();
        $flags = $cfg['Order']['Flags'];

        foreach ($flags as $key => $flag) {
            $options[] = ['value' => (string) $key, 'title' => $flag['name']];
        }

        return [
            'label' => 'Má příznak',
            'type' => 'multiselect',
            'values' => $options,
            'operators' => ['multiselect_function'],
            'function' => 'true',
            'tooltip' => 'Objednávka má alespoň jeden z vybraných příznaků.',
        ];
    }

    public function getName(): string
    {
        return 'has_flag';
    }

    public function getGroupName(): ?string
    {
        return 'order_flags';
    }

    public function getCompareValue(ExpressionContext $context, $args = null)
    {
        $context = $context->getContext();

        return !empty(array_intersect(explode(',', $context['o_flags']), $args[0] ?? []));
    }
}
