<?php

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\ProductsBatchesBundle\Util\ProductsBatchesUtil;
use KupShop\StoresBundle\Utils\StoresInStore;

$main_class = 'Stores';

class Stores extends Window
{
    protected $template = 'window/stores.tpl';
    protected $tableName = 'stores';
    protected $nameField = 'name';

    public function get_vars()
    {
        $vars = parent::get_vars();

        $pageVars = getVal('body', $vars);

        $deliveries = sqlFetchAll($this->selectSQL('delivery_type_delivery', [], ['id', 'name']), ['id' => 'name']);
        $deliveries = ['' => '---'] + $deliveries;
        $pageVars['delivery'] = $deliveries;

        if (findModule(Modules::WAREHOUSE)) {
            $pageVars['base_positions'] = sqlFetchAll(sqlQueryBuilder()
                ->select('*')
                ->from('warehouse_positions')
                ->where(\Query\Operator::equals(['id_location' => \KupShop\WarehouseBundle\Util\StoreItemWorker::LOCATION_TABLE]))
                ->execute(), ['id' => 'code']);
        }

        $pageVars['types'] = StoresInStore::$store_types;
        if ($this->getAction() == 'add') {
            unset($pageVars['types'][StoresInStore::TYPE_MAIN_STORE]);
        }

        $vars['body'] = $pageVars;

        $vars['type'] = 'stores';

        $this->unserializeCustomData($vars['body']['data']);

        return $vars;
    }

    public function getData()
    {
        $data = parent::getData();

        if (getVal('Submit')) {
            $this->serializeCustomData($data);
        }

        return $data;
    }

    public function handleEditProduct()
    {
        $data = parent::getData();
        $ID = $this->getID();

        if (empty($data['id_product']) || empty($data['quantity'])) {
            $this->returnError('Chybí vybraný produkt nebo kusy!');
        }

        sqlGetConnection()->transactional(function () use ($ID, $data) {
            $where = [
                'id_store' => $ID,
                'id_product' => $data['id_product'],
                'id_variation' => $data['id_variation'] ?: null,
            ];

            $quantity = $data['quantity'] ?? 0;

            $loggingContext = ServiceContainer::getService(\KupShop\KupShopBundle\Util\LoggingContext::class);

            $storesInStore = ServiceContainer::getService(StoresInStore::class);
            $loggingContext->activateEdit(function () use ($storesInStore, $where, $quantity) {
                $storesInStore->updateStoreItem($where + ['quantity' => $quantity]);
            });

            if (findModule(Modules::PRODUCTS_BATCHES) && ($batchId = $data['id_product_batch'] ?? null)) {
                /**
                 * @var $batchesUtil ProductsBatchesUtil
                 */
                $batchesUtil = ServiceContainer::getService(ProductsBatchesUtil::class);
                $batchesUtil->addBatchesToCustomData('stores_items', $where, [$batchId => $quantity]);
            }

            $storesInStore->recalcInStoreFromStores(\Query\Operator::equals(['p.id' => $where['id_product']]), \Query\Operator::equals(['pv.id' => $where['id_variation']]));
        });

        $this->returnOK('Přidáno');
    }

    public function hasRights($name = null)
    {
        switch ($name) {
            case Window::RIGHT_DELETE:
                return isSuperuser();
            case Window::RIGHT_DUPLICATE:
                return $this->getID() == 1 ? false : parent::hasRights($name);
        }

        return parent::hasRights($name);
    }
}
