<?php

namespace KupShop\ReturnsBundle\Admin\lists;

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\AdminBundle\AdminList\FiltersStorage;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\ReturnsBundle\Deliveries\Utils\ReturnDeliveries;

class ReturnDeliveryList extends BaseList
{
    use FiltersStorage;
    use \AdminListSortable;

    protected $showMassEdit = true;
    protected $tableName = 'return_delivery';
    protected ?string $tableAlias = 'rd';

    protected $template = 'listSortable.tpl';

    protected $deliveryService;

    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'Pořadí' => ['field' => 'position', 'render' => 'renderPosition', 'size' => 0.3],
            'Název' => ['field' => 'name'],
            'Cena s DPH' => ['field' => 'price', 'render' => 'renderPriceVAT', 'spec' => 'price, currency', 'price_params' => ['ceil' => false]],
            'Typ' => ['field' => 'type', 'render' => 'renderReturnDeliveryType'],
        ],
    ];

    public function renderReturnDeliveryType($values, $column)
    {
        $value = $this->renderCell($values, $column);

        if (!$this->deliveryService) {
            $this->deliveryService = ServiceContainer::getService(ReturnDeliveries::class);
        }

        return $this->deliveryService->getAllDeliveryTypes()[$value]->getName();
    }

    public function getQuery()
    {
        $qb = sqlQueryBuilder()
            ->select('id, COALESCE(name_admin, name) as name, price, type')
            ->from('return_delivery')
            ->orderBy('position');

        return $qb;
    }

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

        $item = getVal('moved_item');

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

return ReturnDeliveryList::class;
