<?php

namespace KupShop\I18nBundle\Admin\lists;

use Doctrine\DBAL\Query\QueryBuilder;
use KupShop\AdminBundle\Util\AdminSectionTree;
use KupShop\I18nBundle\Translations\SectionsTranslation;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class TranslateSectionsList extends TranslateList
{
    private AdminSectionTree $adminSectionTree;
    protected $template = 'list/translateSections.tpl';
    protected $listType = 'translateSections';

    public function __construct()
    {
        parent::__construct();
        $this->translation = ServiceContainer::getService(SectionsTranslation::class);
        $this->adminSectionTree = ServiceContainer::getService(AdminSectionTree::class);
    }

    public function applyFilters(QueryBuilder $qb)
    {
        $qb = parent::applyFilters($qb);

        // product filter
        $productID = getVal('productID', $_GET, false);
        $this->filters['productID']['selected'] = $productID;
        if ($productID) {
            $qb->join('s', 'products_in_sections', 'ps', 'ps.id_section = s.id AND ps.id_product = :id_product')
                ->setParameter('id_product', $productID);
            $qb->groupBy('s.id');
        }

        return $qb;
    }

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

        $newSQL = [];
        foreach ($vars['SQL'] as $object) {
            $parents = [];
            if ($object['id']) {
                $parents = $this->getSectionParents($object['id']);
            }
            // unset self from parents
            unset($parents[$object['id']]);
            $object['parents'] = $parents;

            $newSQL[] = $object;
        }

        $vars['SQL'] = $newSQL;

        return $vars;
    }

    private function getSectionParents($sectionId)
    {
        $section = $this->adminSectionTree->getCategoryById($sectionId);

        return $section->getParents();
    }
}

$main_class = TranslateSectionsList::class;
