<?php

use KupShop\AdminBundle\AdminList\BaseList;

class PricelevelsList extends BaseList
{
    protected $tableName = 'price_levels';
    protected ?string $tableAlias = 'pl';

    protected $tableDef = [
        'id' => 'pl.id',
        'fields' => [
            'Cenová hladina' => ['field' => 'pl.name'],
            'Sleva' => ['field' => 'pl.discount', 'render' => 'renderDiscount'],
            'Popis' => ['field' => 'pl.descr'],
        ],
    ];

    public function renderDiscount($values, $column)
    {
        global $dbcfg;
        $value = $this->getListRowValue($values, $column['field']);
        if (isset($values['unit'])) {
            switch ($values['unit']) {
                case 'perc':
                    return "{$value}%";
                case 'price':
                    return "{$value} ".$dbcfg->currency;
            }
        }

        return "{$value}";
    }

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

        if ($name = getVal('name')) {
            $qb->andWhere(\KupShop\CatalogBundle\Query\Search::searchFields(
                $name,
                [
                    ['field' => 'name', 'match' => 'both'],
                    ['field' => 'descr', 'match' => 'both'],
                ]
            ));
        }

        return $qb;
    }
}
