<?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;

class DurationFromDeliveryDate extends Field implements OrdersContext
{
    public function getConfig(): array
    {
        return [
            'label' => 'Čas od předpokládaného doručení objednávky',
            'type' => 'duration',
            'function' => true,
        ];
    }

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

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

    public function getCompareValue(ExpressionContext $context, $args = null)
    {
        $context = $context->getContext();
        $data = json_decode($context['o_note_admin'], true);
        $deliveryDateTime = new \DateTime($data['deliveryDate']);
        [$diff, $diffAnchor] = $this->fieldsUtil->substractTimeFromNowGetWithAnchor($args[0], $args[1], $args[2], $args[3] ?? false);

        return $this->fieldsUtil->getDurationCompareCondition($deliveryDateTime, $diff, $diffAnchor, $args[4] ?? 'greater');
    }

    public function modifyPrefetchFastCondition($context, $jsonValue)
    {
        $params = $this->prefetchUtil->getDateIntervalValues($jsonValue);
        [$diff, $diffAnchor] = $this->fieldsUtil->substractTimeFromNowGetWithAnchor($params['days'], $params['hours'], $params['seconds'], $params['onlyWorkDays']);

        switch ($params['operator']) {
            case 'less':
                $context->andWhere("json_extract(note_admin, '$.deliveryDate') > :afterDate");
                break;
            default: // greater
                $context->andWhere("json_extract(note_admin, '$.deliveryDate') < :afterDate AND json_extract(note_admin, '$.deliveryDate') > :beforeDate");
        }

        $context->addParameters([
            'afterDate' => $diff->format('Y-m-d H:i:s'),
            'beforeDate' => $diffAnchor->format('Y-m-d H:i:s'),
        ]);

        return $context;
    }
}
