<?php

namespace KupShop\AutomationConfiguratorBundle\Configurator\Orders\Actions;

use KupShop\AutomationConfiguratorBundle\Configurator\Interfaces\Config\ActionConfig;
use KupShop\AutomationConfiguratorBundle\Configurator\Orders\OrdersContext;
use KupShop\AutomationConfiguratorBundle\Event\TriggerEvent;
use KupShop\AutomationConfiguratorBundle\Util\ActionUtil;
use KupShop\KupShopBundle\Config;
use Symfony\Contracts\Service\Attribute\Required;

class AddOrderFlag extends Action implements OrdersContext
{
    public const NAME = 'add_order_flag';

    #[Required]
    public ActionUtil $actionUtil;

    public function getConfig()
    {
        $statuses = [];

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

        $statuses[] = ['key' => '-', 'title' => 'Zvolte příznak'];
        foreach ($flags as $key => $flag) {
            $statuses[] = ['key' => (string) $key, 'title' => $flag['name']];
        }

        return [
            'label' => 'Přidat příznak k objednávce',
            'fields' => [
                [
                    'name' => 'flag',
                    'title' => 'Příznak',
                    'type' => 'select',
                    'values' => $statuses,
                ],
            ],
            'enableMultiple' => true,
        ];
    }

    public function getName()
    {
        return self::NAME;
    }

    public function run(ActionConfig $actionConfig, $context, TriggerEvent $triggerEvent): bool
    {
        $flag = $actionConfig->getField('flag')->getValue();

        if (!$flag || $flag == '-') {
            return false;
        }

        $order = $this->actionUtil->getOrder($context['id'], $triggerEvent);
        if (!isset($order->getFlags()[$flag])) {
            $order->addFlag($flag);
        }

        return true;
    }

    public function getLog(ActionConfig $actionConfig, $context)
    {
        $flag = $actionConfig->getField('flag')->getValue();

        $order = new \Order();
        $order->createFromDB($context['id']);

        if (!isset($order->getFlags()[$flag])) {
            return 'K objednávce č. '.$context['o_order_no'].' byl přidám příznak '.$flag;
        }

        return '';
    }
}
