<?php

declare(strict_types=1);

namespace KupShop\AdminBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\AdminBundle\Util\AdminClassLocator;
use KupShop\AdminBundle\Util\ListColumns;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class ListColumnsTab extends WindowTab
{
    protected $title = 'flapColumns';

    protected $template = 'window/tabs/listColumnsTab.tpl';

    /** @var ListColumns */
    private $listColumns;

    /** @required */
    public function setListColumns(ListColumns $listColumns)
    {
        $this->listColumns = $listColumns;
    }

    public static function getTypes()
    {
        return [
            'filters' => 0,
        ];
    }

    public function isVisible()
    {
        $referer = getVal('HTTP_REFERER', $_SERVER);
        if ($referer && strpos($referer, 'productsMassModification')) {
            return false;
        }

        return true;
    }

    public function getLabel()
    {
        return translate('flapColumns', 'filters');
    }

    public function getVars($smarty_tpl_vars)
    {
        $vars = $smarty_tpl_vars;

        $filter_data = $vars['body']->value['data'] ?? [];
        if ($listType = $filter_data['type'] ?? null) {
            $listInstance = $this->getListInstance($listType);
            // TODO: HACK: nastavim get parametr type, by se naloadovalo spravny nastaveni sloupcu
            $_REQUEST['type'] = $listType;
            $_REQUEST['adminFilter'] = $this->getID();
            $fields = $listInstance->getTableDef()['fields'];
            unset($_REQUEST['type']);
            $sort = json_decode($filter_data['sort'] ?? '', true);
            if ($sort && array_key_exists($sort['sort'], $fields)) {
                $fields[$sort['sort']]['order_by'] = $sort['direction'] ?? 'ASC';
            }
            $vars['body']->value['data']['fields'] = $fields;
        }

        return $vars;
    }

    public function handleUpdate()
    {
        $data = getVal('data');
        $columns = $data['columns'] ?? null;
        $type = $data['type'] ?? null;

        if ($type && $columns) {
            if ('Y' == $data['columns_set'] ?? 'N') {
                $visible = array_filter($columns, function ($c) { return $c['visible'] == 'Y'; });
                if (empty($visible)) {
                    $this->getWindow()->returnError('Musí být zobrazen alespoň jeden sloupec.');
                }
                $this->listColumns->setListOptions($columns, $type, $this->getID());
            } else {
                // Použít výchozí rozložení sloupců
                sqlQueryBuilder()->update('admin_filters')
                    ->set('columns', 'null')
                    ->where(Operator::equals(['id' => $this->getID()]))
                    ->execute();
            }
        }
    }

    /**
     * @return \KupShop\AdminBundle\AdminList\BaseList
     */
    private function getListInstance($listType)
    {
        $className = ucfirst($listType).'List';

        /** @var AdminClassLocator $adminClassLocator */
        $adminClassLocator = ServiceContainer::getService(AdminClassLocator::class);
        $classPath = $adminClassLocator->getClassPath('lists/'.$className.'.php');

        if (file_exists($classPath)) {
            return $adminClassLocator->createClass($classPath, $className);
        }

        throw new RuntimeException(sprintf('List %s does not exists!', $className));
    }
}
