<?php

namespace KupShop\CatalogBundle\Admin;

use KupShop\KupShopBundle\Util\StringUtil;
use Query\Operator;

class ParameterValues extends \Window
{
    protected $tableName = 'parameters_list';
    protected $nameField = 'value';

    public function get_vars()
    {
        $vars = parent::get_vars();

        $parameterId = $this->getAction() === 'add' ? getVal('parameterId') : getVal('id_parameter', $vars['body']['data']);
        $vars['body']['data']['id_parameter'] = $parameterId;

        $vars['body']['data']['value_meaning'] = sqlQueryBuilder()
            ->select('value_meaning')
            ->from('parameters')
            ->where(Operator::equals(['id' => $parameterId]))
            ->execute()->fetchOne();

        $this->unserializeCustomData($vars['body']['data']);

        return $vars;
    }

    public function getData()
    {
        $data = parent::getData();

        $colors = [];
        // kvuli ukladani dat z adminu - index 0 se v administraci nezobrazuje, proto umele navysim index, aby se barva zobrazila
        $index = 1;
        foreach ($data['data']['colors'] as $i => $item) {
            if ($i === 0 || $item['delete']) {
                continue;
            }

            $colors[$index++] = $item['value'];
        }

        $data['data']['colors'] = $colors;

        if (($data['position'] ?? null) === '') {
            unset($data['position']);
        }

        $this->serializeCustomData($data);

        return $data;
    }

    public function processFormData()
    {
        $data = parent::processFormData();

        if (($data['filter_url'] ?? false) === '') {
            $data['filter_url'] = StringUtil::slugify($data['value'] ?? '');
        }

        return $data;
    }
}

return ParameterValues::class;
