<?php

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\AdminBundle\Query\Invert;
use Query\Operator;

class DeliveryPaymentList extends BaseList
{
    use AdminListSortable;

    protected $template = 'listSortable.tpl';
    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'Pořadí' => ['field' => 'position', 'render' => 'renderPosition', 'size' => 0.13],
            'Název' => ['field' => 'name_admin'],
            'Název v košíku' => ['field' => 'name', 'visible' => 'N'],
            'Cena s DPH' => ['field' => 'price', 'render' => 'renderPriceVat'],
            'Typ platby' => ['field' => 'class', 'render' => 'renderPaymentClass'],
        ],
    ];

    public function renderPaymentClass($values, $column)
    {
        $value = $this->getListRowValue($values, $column['field']);

        if (!$value) {
            return $value;
        }

        $class = Payment::getClass($value);

        if (!$class) {
            return '';
        }

        return $class->getName();
    }

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

        $item = getVal('moved_item');

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

    public function getQuery()
    {
        $qb = sqlQueryBuilder()->select('*, COALESCE(name_admin, name) AS name_admin', 'id')
            ->from('delivery_type_payment')
            ->orderBy('position');

        $name = getVal('paymentName');
        if ($name) {
            $qb->andWhere(Invert::checkInvert(Operator::inStringArray($name, 'id'), getVal('paymentName_invert')));
        }

        $type = getVal('paymentType');
        if ($type) {
            $qb->andWhere(Invert::checkInvert(Operator::inStringArray($type, 'class'), getVal('paymentType_invert')));
        }

        return $qb;
    }
}
