<?php

namespace KupShop\ProductsBatchesBundle\EventListener;

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

class OrderEventListener implements EventSubscriberInterface
{
    /**
     * @var StoreItemWorker
     */
    protected $worker;

    /**
     * @required
     */
    public function setWorker(?StoreItemWorker $worker): void
    {
        $this->worker = $worker;
    }

    public static function getSubscribedEvents()
    {
        return [
            OrderEvent::ORDER_STORNO => [
                ['stornoProductsBatchesNumbers', -1],
            ],
        ];
    }

    public function stornoProductsBatchesNumbers(OrderEvent $event)
    {
        $order = $event->getOrder();

        $warehouse_order = sqlQueryBuilder()
            ->select('*')
            ->from('warehouse_orders')
            ->where(Operator::equals(['id_order' => $order->id]))
            ->andWhere('id_position IS NULL')
            ->andWhere('date_finish IS NOT NULL')
            ->execute()
            ->fetch();

        // Check if order is finished and does not have any box assigned
        if ($warehouse_order) {
            $logProducts = sqlQueryBuilder()->select('*')
                ->from('warehouse_log', 'wl')
                ->where(Operator::equals(['wl.id_order' => $order->id]))
                ->andWhere('wl.new_id_position IS NULL')
                ->andWhere('wl.id_product_batch IS NOT NULL')->execute()->fetchAll();

            $event = new WarehouseOrderEvent();
            $position = $this->worker->getPositionIdByCode($event->getReturnPosition());

            // Select only items that have batch number, subtract them from generated items without batch, and create them again with batch id
            foreach ($logProducts as $item) {
                $itemNoBatch = $item;
                $itemNoBatch['id_product_batch'] = null;
                $this->worker->updateOnPosition(new StoreItem($itemNoBatch), $position, -$itemNoBatch['pieces']);
                $this->worker->createStoreItem(new StoreItem($item), $item['pieces'], $position);
            }
        }
    }
}
