<?php

namespace KupShop\SellerBundle\View;

use KupShop\KupShopBundle\Views\View;
use KupShop\SellerBundle\Translations\SellersTranslation;
use KupShop\SellerBundle\Utils\SellerUtil;
use Query\Operator;
use Query\QueryBuilder;
use Query\Translation;

class ListView extends View
{
    protected $template = 'seller/seller.list.tpl';
    protected string $smartyFallback = 'blank';

    /** @var SellerUtil */
    protected $sellerUtil;

    /** @required */
    public function setSellerUtil(SellerUtil $sellerUtil): void
    {
        $this->sellerUtil = $sellerUtil;
    }

    public function getBodyVariables()
    {
        $body = [];

        $qb = $this->applySellersFilter(
            sqlQueryBuilder()
                ->select('se.*, X(se.position) as x, Y(se.position) as y')
                ->from('sellers', 'se')
                ->andWhere(Operator::equals(['se.figure' => 'Y']))
                ->andWhere(Translation::coalesceTranslatedFields(SellersTranslation::class))
        );

        $sellers = [];
        foreach ($qb->execute() as $item) {
            $sellers[] = $this->sellerUtil->prepareSeller($item);
        }

        $body['dealers'] = $sellers;

        return $body;
    }

    protected function applySellersFilter(QueryBuilder $qb): QueryBuilder
    {
        $types = getVal('type');

        if ($types) {
            $qb->andWhere(Operator::inStringArray((array) $types, 'type'));
        }

        return $qb;
    }
}
