<?php

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\AdminBundle\AdminList\FiltersStorage;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Excel\ExcelGenerator;
use KupShop\KupShopBundle\Util\Excel\ExcelHeaderBuilder;
use KupShop\KupShopBundle\Util\System\UrlFinder;
use KupShop\RewriteBundle\Util\Rewrite;

class RewriteList extends BaseList
{
    use FiltersStorage;

    protected $showMassEdit = true;

    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'URL' => ['field' => 'url'],
            'Typ' => ['field' => 'type', 'render' => 'renderType'],
            'Cíl' => ['field' => 'related_id', 'render' => 'renderTarget'],
        ],
    ];

    /** @var Rewrite */
    private $rewriteUtil;

    private $translatedTypes = [];

    public function __construct()
    {
        $this->rewriteUtil = ServiceContainer::getService(Rewrite::class);
        foreach ($this->rewriteUtil->config as $key => $value) {
            $this->translatedTypes[$key] = translate('type_'.$value);
        }
    }

    public function getQuery()
    {
        $qb = sqlQueryBuilder()
            ->select('*')
            ->from('rewrite')
            ->where('1=1');
        $filter = getVal('filter');
        if (!empty($filter['url'])) {
            $qb->andWhere(\Query\Operator::like(['url' => "%{$filter['url']}%"]));
        }
        if (isset($filter['type']) && $filter['type'] !== '') {
            $qb->andWhere(\Query\Operator::equals(['type' => $filter['type']]));
        }

        return $qb;
    }

    public function renderType($values, $column)
    {
        return $this->translatedTypes[$values['type']] ?? $values['type'];
    }

    public function renderTarget($values, $column)
    {
        if ($values['type'] == Rewrite::TYPE_CUSTOM) {
            return $values[$column['field']];
        } elseif (array_key_exists($values['type'], $this->rewriteUtil->config)) {
            switch ($values['type']) {
                case Rewrite::TYPE_PAGE:
                    $windowType = 'menulinks';
                    break;
                case Rewrite::TYPE_CATEGORY:
                    $windowType = 'sections';
                    break;
                default:
                    $windowType = $this->rewriteUtil->config[$values['type']];
            }

            return \KupShop\KupShopBundle\Util\HtmlBuilder\HTML::create('a')
                ->attr('href', "javascript:nw('{$windowType}', '".$values['related_id']."', '');")
                ->text($this->translatedTypes[$values['type']].': '.$values['related_id']);
        }
    }

    public function handleExport()
    {
        $excelGenerator = ServiceContainer::getService(ExcelGenerator::class);
        $excelHeaderBuilder = (new ExcelHeaderBuilder())
            ->string('Zdroj', 'source', 200)
            ->string('Cíl', 'destination', 200);

        $data = function () {
            $urlFinder = ServiceContainer::getService(UrlFinder::class);
            $rows = sqlQueryBuilder()->select('url, type, related_id')->from('rewrite')
                ->orderBy('id')->execute();
            foreach ($rows as $row) {
                yield [
                    'source' => $urlFinder->shopUrlAbsolute($row['url']),
                    'destination' => $urlFinder->shopUrlAbsolute($this->rewriteUtil->getTargetUrlByType($row['type'], $row['related_id'])),
                ];
            }
        };

        $excelGenerator->generateExcel($excelHeaderBuilder->getHeader(), $data(), 'rewrite.xlsx');

        exit;
    }
}
