<?php

namespace KupShop\PohodaBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\PohodaBundle\Utils\Configuration;
use KupShop\PohodaBundle\Utils\Importers\ProductsImporter;

class PohodaStoresTab extends WindowTab
{
    protected $title = 'flapPohoda';

    protected $template = 'PohodaStoresTab.tpl';

    /**
     * @var ProductsImporter
     */
    protected $productsImporter;

    public static function getTypes()
    {
        return [
            'stores' => 1,
        ];
    }

    public function getVars($smarty_tpl_vars)
    {
        $configuration = ServiceContainer::getService(Configuration::class);

        return [
            'mservers' => $configuration->get('mservers'),
        ];
    }

    public function getLabel()
    {
        return 'Pohoda';
    }

    public static function isAllowed()
    {
        return findModule(\Modules::POHODA, \Modules::SUB_STORES);
    }

    /**
     * @required
     */
    public function setProductsImporter(ProductsImporter $productsImporter): void
    {
        $this->productsImporter = $productsImporter;
    }

    protected function handleSyncStore()
    {
        if (empty($this->getWindow()->getData()['pohoda_id'])) {
            $this->getWindow()->returnError('Sklad nemá vyplněné Pohoda ID.');

            return;
        }

        if (($this->getWindow()->getData()['data']['mserver'] ?? false) || $this->getWindow()->getData()['data']['mserver'] === '0') {
            $this->productsImporter->pohodaConnector->setActiveConfigById($this->getWindow()->getData()['data']['mserver']);
        }

        if ($this->productsImporter->pohodaConnector->checkConnection()) {
            sqlQueryBuilder()->delete('stores_items')
                ->andWhere('id_store=:id_actual_store')
                ->setParameters(['id_actual_store' => $this->getID()])
                ->execute();

            $this->productsImporter->pohodaConnector->skipSaveLastSyncTime(true);
            $this->productsImporter->setFullSync(true);
            $this->productsImporter->processData(null, ['storeId' => $this->getWindow()->getData()['pohoda_id']]);
        } else {
            $this->getWindow()->returnError('Nepovedlo se připojit do Pohody.');
        }
        $this->getWindow()->returnOK('Dokončeno');
    }
}
