<?php

declare(strict_types=1);

namespace KupShop\PohodaBundle\Utils\Tools;

use KupShop\KupShopBundle\Context\VatContext;
use KupShop\OrderingBundle\Util\Order\OrderItemInfo;
use KupShop\OSSVatsBundle\Util\VatsUtil;
use Symfony\Contracts\Service\Attribute\Required;

class VatHelper
{
    #[Required]
    public VatContext $vatContext;

    public $vatsUtil;

    protected ?array $vats;

    public function loadRateVatFromCache($itemVat, $delivery_country = 'CZ', $oss = false)
    {
        $itemVat = (string) $itemVat;

        if (empty($this->vats[$delivery_country])) {
            $vatsSQL = sqlQueryBuilder()
                ->select('*')
                ->from('vats');
            if (findModule(\Modules::OSS_VATS)) {
                if ($oss || $delivery_country != 'CZ') {
                    $vatsSQL->where(\Query\Operator::equals(['id_country' => $delivery_country]));
                } else {
                    $vatsSQL->andWhere('automanaged=0');
                }
            }
            foreach ($vatsSQL->execute() as $vat) {
                $data = json_decode($vat['data'] ?? '', true);
                $this->vats[$delivery_country][(string) $vat['vat']] = $data['level'] ?? 'high';
            }
        }

        if (!$oss) {
            switch ($this->vats[$delivery_country][$itemVat] ?? $itemVat) {
                case 21:
                case OrderItemInfo::VAT_HIGH:
                    return 'high';
                case 15:
                case 12:
                case OrderItemInfo::VAT_LOW:
                    return 'low';
                case 10:
                case OrderItemInfo::VAT_LOW2:
                    return 'third';
            }

            return OrderItemInfo::VAT_NONE;
        }

        switch ($this->vats[$delivery_country][$itemVat] ?? 'high') {
            case OrderItemInfo::VAT_HIGH:
                return 'historyHigh';
            case OrderItemInfo::VAT_LOW:
                return 'historyLow';
            case OrderItemInfo::VAT_LOW2:
                return 'historyThird';
            case OrderItemInfo::VAT_NONE:
                return 'none';
        }

        return 'historyHigh';
    }

    /**
     * @required
     */
    public function setVatsUtil(?VatsUtil $vatsUtil): void
    {
        $this->vatsUtil = $vatsUtil;
    }
}
