<?php

declare(strict_types=1);

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\AdminBundle\Query\Invert;
use KupShop\CatalogBundle\Query\Search;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\OSSVatsBundle\Util\VatsUtil;
use Query\Operator;
use Query\QueryBuilder;

class CNsVatsList extends BaseList
{
    protected $showMassEdit = true;
    protected bool $hasStringId = true;
    protected $tableName = 'vats_cns';
    protected ?string $tableAlias = 'vc';
    protected $tableDef = [
        'id' => "CONCAT(vc.id_cn, '_', vc.id_vat)",
        'fields' => [
            'CN' => ['field' => 'id_text', 'type' => '', 'translate' => true],
            'Country' => ['field' => 'country', 'translate' => true, 'type' => 'countries', 'type_id' => 'id_country'],
            'VAT' => [
                'field' => 'id_vat',
                'fieldType' => BaseList::TYPE_LIST_AUTOCOMPLETE,
                'fieldOptions' => ['autocomplete' => 'vats'],
                'render' => 'renderVat',
                'translate' => true,
                'type' => 'vats',
                'type_id' => 'id_vat',
            ],
            'automanaged' => ['field' => 'vc.automanaged', 'render' => 'renderBoolean', 'translate' => true, 'editable' => 'N', 'fieldType' => BaseList::TYPE_BOOL],
        ],
    ];

    public function customizeTableDef($tableDef)
    {
        $tableDef = parent::customizeTableDef($tableDef);

        $tableDef['fields']['CN']['spec'] = function (QueryBuilder $qb) {
            $qb->addSelect('IF(vc.id_cn < 0, voe.description, vc.id_cn) id_text')
                ->leftJoin('vc', 'vats_oss_exceptions', 'voe', 'voe.id=-vc.id_cn');
        };

        return $tableDef;
    }

    public function renderVat($values, $column)
    {
        return $this->renderPercents($values, ['field' => 'vat']);
    }

    public function getFilterQuery(): QueryBuilder
    {
        $qb = parent::getFilterQuery();

        if ($countries = getVal('country')) {
            $qb->andWhere(Invert::checkInvert(Operator::inStringArray($countries, 'id_country'), getVal('country_invert')));
        }

        if ($cn = getVal('cn')) {
            $qb->andWhere(Invert::checkInvert(Search::searchFields($cn, [['field' => 'CONCAT(vc.id_cn, "_", vc.id_vat)', 'match' => 'both', 'order' => '1']]), getVal('cn_invert')));
        }

        if ($automanaged = getVal('automanaged')) {
            $qb->andWhere(Operator::inIntArray($automanaged, 'vc.automanaged'));
        }

        return $qb;
    }

    public function getQuery()
    {
        $qb = parent::getQuery();

        $qb->addSelect('v.vat, CONCAT(vc.id_cn, "_", vc.id_vat) id, id_country')
            ->leftJoin('vc', 'vats', 'v', 'v.id=vc.id_vat');

        $qb->addSelect('c.name country')
            ->leftJoin('v', 'countries', 'c', 'c.id=v.id_country');

        return $qb;
    }

    public function applyOrder(QueryBuilder $qb, &$vars)
    {
        $returnQb = parent::applyOrder($qb, $vars);

        $returnQb->addSelect('v.vat, CONCAT(vc.id_cn, "_", vc.id_vat) id, id_country')
            ->leftJoin('vc', 'vats', 'v', 'v.id=vc.id_vat');

        $returnQb->addSelect('c.name country')
            ->leftJoin('v', 'countries', 'c', 'c.id=v.id_country');

        if (($vars['orderField'] ?? '') == 'id_vat') {
            $returnQb->orderBy('v.vat', $vars['orderDir']);
        }

        return $returnQb;
    }

    public function handleLoadVatRates()
    {
        $vatsUtil = ServiceContainer::getService(VatsUtil::class);
        $vatsUtil->updateVatRates();
        $vatsUtil->refreshVatsCnsRelations();
        $vatsUtil->generateForNonEUCountries();
        $this->returnOK(translate('updateVATRatesSuccessful'));
    }

    public function handleRefreshVatsCns()
    {
        $vatsUtil = ServiceContainer::getService(VatsUtil::class);
        $vatsUtil->refreshVatsCnsRelations();
        $this->returnOK(translate('refreshVATsCNsSuccessful'));
    }

    public function handleGenerateNonEU(): void
    {
        $util = ServiceContainer::getService(VatsUtil::class);
        $util->generateForNonEUCountries();
    }
}
