<?php

declare(strict_types=1);

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

use KupShop\AutomationConfiguratorBundle\Configurator\Generic\Conditions\Groups\Time;
use KupShop\AutomationConfiguratorBundle\Configurator\Interfaces\Conditions\Fields\Field;
use KupShop\AutomationConfiguratorBundle\Configurator\Orders\OrdersContext;
use KupShop\AutomationConfiguratorBundle\Util\ExpressionContext;

class DurationBeforeOrderDue extends Field implements OrdersContext
{
    public function getConfig(): array
    {
        return [
            'label' => 'Čas před vypršením splatnosti objednávky',
            'type' => 'duration',
            'function' => true,
        ];
    }

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

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

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

        $now = new \DateTime();
        $orderDateTime = new \DateTime($context['o_date_due']);
        $diff = $this->fieldsUtil->addTimeFromNow((int) $args[0], (int) $args[1], (int) $args[2], $args[3] ?? false);

        return match ($args[4] ?? 'greater') {
            'less' => $orderDateTime >= $now && $orderDateTime < $diff,
            default => $orderDateTime > $diff,
        };
    }

    public function modifyPrefetchFastCondition($context, $jsonValue)
    {
        $params = $this->prefetchUtil->getDateIntervalValues($jsonValue);
        $diff = $this->fieldsUtil->addTimeFromNow((int) $params['days'], (int) $params['hours'], (int) $params['seconds'], (bool) ($params['onlyWorkDays'] ?? false));

        $field = $this->getDateDueField();

        switch ($params['operator']) {
            case 'less':
                $context->andWhere("{$field} >= NOW() AND {$field} < :beforeDue");
                break;
            default: // greater
                $context->andWhere("{$field} > :beforeDue");
        }

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

        return $context;
    }

    public function modifyPrefetchOnUse($context)
    {
        $context->addSelect("{$this->getDateDueField()} as o_date_due");

        return $context;
    }

    private function getDateDueField(): string
    {
        $dbcfg = \Settings::getDefault();

        return 'COALESCE(o.date_due, (COALESCE(o.date_handle, o.date_accept, o.date_created) + INTERVAL '.$dbcfg->shop_due_days.' DAY))';
    }
}
