<?php

namespace KupShop\XMLFeedBundle\View;

use Doctrine\ORM\EntityManagerInterface;
use KupShop\KupShopBundle\Views\View;
use KupShop\XMLFeedBundle\Util\XMLFeedUtil;
use Query\Operator;
use Symfony\Contracts\Service\Attribute\Required;

class B2BInfoView extends View
{
    use \DatabaseCommunication;

    /** @var EntityManagerInterface */
    protected $em;

    private XMLFeedUtil $xmlFeedUtil;

    protected $template = 'XMLFeed/B2BInfo.tpl';

    /**
     * B2BInfoView constructor.
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    #[Required]
    final public function setXMLFeedUtil(XMLFeedUtil $xmlFeedUtil): void
    {
        $this->xmlFeedUtil = $xmlFeedUtil;
    }

    public function getTitle()
    {
        return translate('title', 'xmlfeed');
    }

    public function getEnabledFeeds()
    {
        $user = \User::getCurrentUser();
        $enabledFeeds = [];
        if ($user && findModule(\Modules::XML_FEEDS_B2B, \Modules::SUB_FEED_IDS)) {
            $data = $user->getCustomData();
            $defaultB2BFeeds = $this->xmlFeedUtil->getDefaultFeedIds();
            $enabledFeedsIDs = array_unique(array_merge($defaultB2BFeeds, $data['b2b_feeds'] ?? []));
            $qb = sqlQueryBuilder()->select('id, name, data')->from('feeds')
                ->where(Operator::inIntArray($enabledFeedsIDs, 'id'))
                ->orderBy('name')->execute();
            foreach ($qb as $feed) {
                $feedData = json_decode($feed['data'], true);
                $enabledFeeds[$feed['id']] = [
                    'id' => $feed['id'],
                    'name' => $feed['name'],
                    'format' => $feedData['format'] ?? 'xml',
                    'data' => $feedData,
                ];
            }
        }

        return $enabledFeeds;
    }

    public function fetchFeedToken()
    {
        $user = \User::getCurrentUser();

        if ($user) {
            return $user->feed_token;
        }

        return null;
    }
}
