<?php

namespace External\VarioBundle\Resources\script;

use External\VarioBundle\Synchronizers\ProductSynchronizer;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class VarioStoreItemsSync extends Script
{
    protected static $name = '[Vario] Store Items Sync';
    protected static $defaultParameters = [
        'productId' => '',
        'startFrom' => 218,
    ];

    protected function run(array $arguments)
    {
        $productSynchronizer = ServiceContainer::getService(ProductSynchronizer::class);
        // aktivní produkty tedy skrytý nebo viditelný
        $productIds = sqlQueryBuilder()
    ->select('vp.id_product, vp.id_vario')
    ->from('vario_products', 'vp')
    ->innerJoin('vp', 'products', 'p', 'vp.id_product = p.id')
    ->where(Operator::not(Operator::equals(['p.figure' => 'O'])));
        // pokud je předán productId, tak se přidá podmínka
        if (!empty($arguments['productId'])) {
            $productIds->andWhere(Operator::equals(['id_product' => $arguments['productId']]));
        }
        if (!empty($arguments['startFrom'])) {
            $productIds->andWhere('vp.id_product >= :startFrom')
                ->setParameter('startFrom', $arguments['startFrom']);
        }
        $productIds->orderBy('vp.id_product', 'ASC');
        $productIds = $productIds->execute()->fetchAllKeyValue();
        foreach ($productIds as $productId => $varioId) {
            sqlGetConnection()->transactional(function () use ($productId, $varioId, $productSynchronizer) {
                // Smazání položek skladu pro produkt - provest update quantity na 0
                sqlQueryBuilder()
                    ->update('stores_items')
                    ->directValues(['quantity' => 0])
                    ->where(Operator::equals(['id_product' => $productId]))
                    ->execute();
                // Zavolání forceSync z productSynchronizer
                $productSynchronizer->forceSyncSupply($varioId);
            });
            $this->log('Synchronizace položek skladu pro produkt: '.$productId.' dokončena');
        }
    }
}

return VarioStoreItemsSync::class;
