<?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 Query\QueryBuilder;

class HasInvoice extends Field implements OrdersContext
{
    public function getConfig(): array
    {
        return [
            'label' => 'Má fakturu',
            'type' => 'boolean',
        ];
    }

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

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

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

        return !empty($context['o_invoice_no']);
    }

    public function modifyPrefetchFastCondition($context, $jsonValue)
    {
        $value = $this->prefetchUtil->getBooleanValue($jsonValue);

        if ($value) {
            $context->andWhere('o.invoice_no IS NOT NULL');
        } else {
            $context->andWhere('o.invoice_no IS NULL');
        }

        return $context;
    }

    public function isEnabled(): bool
    {
        return findModule(\Modules::INVOICES);
    }

    /**
     * @param QueryBuilder $context
     */
    public function modifyPrefetchOnUse($context)
    {
        $context->addSelect('o.invoice_no o_invoice_no');

        return $context;
    }
}
