<?php

namespace KupShop\KupShopBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\AdminBundle\Util\Stats\StoreDataLoader;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class AddPurchasePrice extends Script
{
    use \DatabaseCommunication;

    protected static $name = 'Naplnit nákupní ceny z naskladnění';

    protected static $defaultParameters = [
    ];

    public function run(array $arguments)
    {
        if (!findModule(\Modules::PRODUCTS, \Modules::SUB_PRICE_BUY)) {
            $this->log('Není aktivní modul nákupní ceny!');

            return;
        }
        $this->log('Nastavuji nákupní cenu produktům');
        /** @var $storeDataLoader StoreDataLoader */
        $storeDataLoader = ServiceContainer::getService(StoreDataLoader::class);
        $queryQuantity = $storeDataLoader->getCurrentStoreQb()
            ->select('p.id as id_product, pv.id as id_variation, p.title, r.average_price');

        sqlQuery("
        UPDATE 
            products pUpdate
        INNER JOIN
            ({$queryQuantity->getSQL()}) pFrom
        ON (pUpdate.id = pFrom.id_product AND pFrom.id_variation IS NULL)
        SET pUpdate.price_buy = pFrom.average_price
        WHERE pFrom.id_variation IS NULL AND pUpdate.price_buy IS NULL", $queryQuantity->getParameters()
        );
        $this->log('Hotovo');
        $this->log('Nastavuji nákupní cenu variantám');
        sqlQuery("
        UPDATE 
            products_variations pUpdate
        INNER JOIN
            ({$queryQuantity->getSQL()}) pFrom
        ON (pUpdate.id = pFrom.id_variation)
        SET pUpdate.price_buy = pFrom.average_price
        WHERE pFrom.id_variation IS NOT NULL AND pUpdate.price_buy IS NULL", $queryQuantity->getParameters()
        );
        $this->log('Hotovo');
    }
}

return AddPurchasePrice::class;
