<?php

namespace KupShop\WarehouseBundle\EventListener;

use KupShop\OrderingBundle\Event\OrderItemEvent;
use KupShop\WarehouseBundle\Entity\StoreItem;
use KupShop\WarehouseBundle\Util\Logger;
use KupShop\WarehouseBundle\Util\StoreItemWorker;
use Query\Operator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ReturnListener implements EventSubscriberInterface
{
    /**
     * @var Logger
     */
    private $logger;

    /* @var StoreItemWorker */
    private $storeItemWorker;

    public static function getSubscribedEvents()
    {
        return [
            OrderItemEvent::RETURN_ITEM => [
                ['returnToTable', 100],
            ],
        ];
    }

    public function returnToTable(OrderItemEvent $event)
    {
        $order = $event->getOrder();

        $this->logger->activateOrder($order->id, function () use ($event) {
            $order = $event->getOrder();
            $id_store = $order->getData('id_store');

            if ($id_store) {
                $id_return_table = sqlQueryBuilder()->select('s.id_return_table')
                    ->from('stores', 's')
                    ->where(Operator::equals(['s.id' => $id_store]))
                    ->execute()
                    ->fetchColumn();
            }

            if (empty($id_return_table)) {
                $id_return_table = $this->storeItemWorker->getPositionIdByCode('VRATKY');
            }

            $piecesWithoutBatch = $event->getPieces();

            if (findModule(\Modules::PRODUCTS_BATCHES)) {
                $itemData = $event->getData()['order_item_data'] ?? null;

                if ($itemData) {
                    $batches = json_decode($itemData, true)['batch_numbers'] ?? [];
                }
                foreach ($batches ?? [] as $batchId => $batchAmount) {
                    $storeItem = new StoreItem([
                        'id_product' => $event->getProduct()->id,
                        'id_variation' => $event->getVariationId(),
                        'id_product_batch' => $batchId,
                    ]);

                    $this->storeItemWorker->createStoreItem($storeItem, $batchAmount, $id_return_table, null, true);
                    $piecesWithoutBatch -= $batchAmount;
                }
                $piecesWithoutBatch = $piecesWithoutBatch > 0 ? $piecesWithoutBatch : false;
            }

            if ($piecesWithoutBatch !== false) {
                $storeItem = new StoreItem([
                    'id_product' => $event->getProduct()->id,
                    'id_variation' => $event->getVariationId(),
                ]);
                $this->storeItemWorker->createStoreItem($storeItem, $piecesWithoutBatch, $id_return_table, null, true);
            }
        });

        $updatedRows = sqlQueryBuilder()
            ->update('order_items')
            ->set('descr', "CONCAT('VRATKA - ', descr)")
            ->where(\Query\Operator::equals(['id' => $event->getData()['order_item_id']]))
            ->execute();

        assert($updatedRows == 1, 'Replacement::returnItem - making nonProduct does not modified any row');
    }

    /**
     * @required
     */
    public function setLogger(Logger $logger): void
    {
        $this->logger = $logger;
    }

    /**
     * @required
     */
    public function setStoreItemWorker(StoreItemWorker $storeItemWorker): void
    {
        $this->storeItemWorker = $storeItemWorker;
    }
}
