<?php

namespace KupShop\I18nBundle\Admin\lists;

use Doctrine\DBAL\Query\QueryBuilder;
use KupShop\I18nBundle\Translations\TemplatesTranslation;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class TranslateTemplatesList extends TranslateList
{
    protected $template = 'list/translateTemplates.tpl';

    protected $listType = 'translateTemplates';

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

    public function createQueryBuilder(): QueryBuilder
    {
        $qb = parent::createQueryBuilder();
        $qb->leftJoin($this->translation->getTableAlias(), 'templates_categories', 'tc', 'tc.id = t.id_category')
            ->addSelect('tc.name AS category_name');

        return $qb;
    }

    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(
                $this->translation->getTableAlias(),
                'templates_products',
                'tp',
                'tp.id_template = '.$this->translation->getTableAlias().'.id'
                .' AND tp.id_product = :id_product'
            )
                ->setParameter('id_product', $productID);
            $qb->groupBy($this->translation->getTableAlias().'.id');
        }

        return $qb;
    }
}

$main_class = TranslateTemplatesList::class;
