<?php

use KupShop\AdminBundle\AdminList\BaseList;

class GlobalDiscountsList extends BaseList
{
    use AdminListSortable;

    protected $template = 'list/GlobalDiscounts.tpl';
    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'Pořadí' => ['field' => 'position', 'render' => 'renderPosition', 'size' => '70px'],
            'Název' => ['field' => 'name'],
            'Sleva' => ['field' => 'discount', 'render' => 'renderDiscount'],
            'Datum od' => ['field' => 'date_from', 'render' => 'renderDateTime'],
            'Datum do' => ['field' => 'date_to', 'render' => 'renderDateTime'],
            'Aktivní' => ['field' => 'active', 'render' => 'renderBoolean'],
        ],
    ];
    protected $pageDivide = 999999;

    public function renderDiscount($values, $column)
    {
        $discount = toDecimal($values['discount']);

        return $discount->printFloatValue(-2).' %';
    }

    public function handleRecalculate()
    {
        $globalDiscounts = \KupShop\KupShopBundle\Util\Compat\ServiceContainer::getService(\KupShop\GlobalDiscountsBundle\Util\GlobalDiscounts::class);

        $globalDiscounts->activateDiscounts();
        $globalDiscounts->deactivateDiscounts();
        $globalDiscounts->recalculateDiscounts();

        clearCache('insert_products', true);

        $this->returnOK('Přepočet proveden');
    }

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

        $item = getVal('moved_item');

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

    public function getQuery()
    {
        $qb = sqlQueryBuilder()->select('*')
            ->from('global_discounts');

        return $qb;
    }
}

return GlobalDiscountsList::class;
