<?php

declare(strict_types=1);

namespace KupShop\ConvertorsBundle\Admin;

use KupShop\ConvertorsBundle\Utils\ConvertorsUtil;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class ConvertingTable extends \Window
{
    protected $tableName = 'convertors_table';

    public function get_vars()
    {
        $vars = parent::get_vars();
        $vars['body']['priorities'] = [1000 => 'Vysoká', 0 => 'Normální', -1000 => 'Nízká'];

        if ($this->action == 'edit' || $this->isDuplicate()) {
            /** @var ConvertorsUtil $convertorsUtil */
            $convertorsUtil = ServiceContainer::getService(ConvertorsUtil::class);

            $vars['body']['data']['table'] = $convertorsUtil->getTableValues($this->getID());

            $vars['body']['data']['filter'] = json_decode($vars['body']['data']['filter'], true);
        } else {
            if ($this->action == 'add') {
                $vars['body']['data']['priority'] = 0;
            }
        }

        return $vars;
    }

    public function handleUpdate()
    {
        $SQL = parent::handleUpdate();

        if ($SQL) {
            $data = $this->getData();
            $table = [];

            if ($this->isDuplicate()) {
                // Načtu hodnotu z dat původní tabulky
                if (count($data['table'])) {
                    $table = reset($data['table']);
                }
            } else {
                $table = $data['table'][$this->getID()];
            }

            $values = getVal('parameters', $table, []);

            $filter = getVal('filter');
            $this->updateSQL('convertors_table', ['filter' => json_encode($filter)], ['id' => $this->getID()]);

            /** @var ConvertorsUtil $convertorsUtil */
            $convertorsUtil = ServiceContainer::getService(ConvertorsUtil::class);

            $convertorsUtil->saveTableValues($this->getID(), $values);
        }

        return $SQL;
    }
}

return ConvertingTable::class;
