<?php

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\I18nBundle\Admin\Util\ListTranslationsFigureBadges;
use KupShop\KupShopBundle\Util\HtmlBuilder\HTML;
use KupShop\LabelsBundle\Translations\LabelTranslation;

class LabelList extends BaseList
{
    use ListTranslationsFigureBadges;
    use \AdminListSortable;

    protected $template = 'listSortable.tpl';
    protected $tableName = 'labels';
    protected ?string $tableAlias = 'l';

    protected $tableDef = [
        'id' => 'l.id',
        'fields' => [
            'position' => ['field' => 'position', 'translate' => true, 'render' => 'renderPosition', 'size' => '70px'],
            'name' => ['field' => 'name_admin', 'translate' => true, 'size' => 1, 'spec' => 'COALESCE(l.name_admin, l.name) as name_admin'],
            'short_name' => ['field' => 'short_name', 'translate' => true, 'size' => 1],
            'active' => ['field' => 'active', 'translate' => true, 'render' => 'renderBoolean', 'size' => 0.8],
            'discount' => ['field' => 'discount', 'translate' => true, 'translate_key' => 'discount_label_discount', 'render' => 'renderDiscount', 'size' => 1, 'spec' => 'JSON_EXTRACT(l.data, "$.id_order_discount") as discount', 'visible' => 'N'],
        ],
    ];

    protected $orderParam = [
        'sort' => 'position',
        'direction' => 'ASC',
    ];

    private ?array $orderDiscounts = null;

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

        if (findModule(\Modules::TRANSLATIONS)) {
            $tableDef['fields']['translationsFigure'] = $this->getTranslationsFigureField(
                LabelTranslation::class,
                figureField: 'active',
                column: ['translation_section' => 'translations', 'visible' => 'Y'],
            );
        }

        return $tableDef;
    }

    public function renderDiscount(array $values, array $column): array
    {
        $discountIds = json_decode($values['discount'] ?: '', true) ?: [];

        $result = [];
        foreach ($discountIds as $discountId) {
            if (!($discountName = $this->getOrderDiscounts()[$discountId] ?? null)) {
                continue;
            }

            $result[] = HTML::create('span')
                ->tag('p')
                    ->tag('a')
                    ->attr('href', 'javascript:nw(\'OrderDiscounts\', \''.$discountId.'\')')
                    ->text($discountName)
                    ->end()
                ->end();
        }

        return $result;
    }

    public function handle()
    {
        parent::handle();

        $item = getVal('moved_item');

        if (!empty($item)) {
            $this->saveList($item, 'labels');
            exit('{}');
        }
    }

    private function getOrderDiscounts(): array
    {
        if ($this->orderDiscounts !== null) {
            return $this->orderDiscounts;
        }

        return $this->orderDiscounts = sqlQueryBuilder()
            ->select('id, name')
            ->from('order_discounts')
            ->execute()->fetchAllKeyValue();
    }
}
