<?php

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

use KupShop\AutomationConfiguratorBundle\Configurator\Interfaces\Conditions\Fields\Field;
use KupShop\AutomationConfiguratorBundle\Configurator\Orders\Conditions\Groups\PaymentDeliveryPrice;
use KupShop\AutomationConfiguratorBundle\Configurator\Orders\OrdersContext;
use KupShop\AutomationConfiguratorBundle\Util\ConfiguratorQuery;
use KupShop\AutomationConfiguratorBundle\Util\ExpressionContext;
use Query\Operator;

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

        foreach (\DeliveryType::getPayments(true) as $key => $status) {
            $statuses[] = ['value' => (string) $key, 'title' => $status['name']];
        }

        return [
            'label' => 'Způsob platby',
            'type' => 'multiselect',
            'values' => $statuses,
        ];
    }

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

    public function getGroupName(): ?string
    {
        return PaymentDeliveryPrice::NAME;
    }

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

        return (string) $context['dt_id_payment'];
    }

    public function modifyPrefetchFastCondition($context, $jsonValue)
    {
        $statuses = $jsonValue['all'][1]['in'][1] ?? false;
        if ($statuses) {
            $context->andWhere(Operator::inStringArray($statuses, 'dt.id_payment'));
        }

        return $context;
    }

    public function modifyPrefetchOnUse($context)
    {
        return $context->andWhere(ConfiguratorQuery::joinDeliveryType());
    }
}
