<?php

namespace FiloBlu\Flow\Model\Actions\From;

use Exception;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\Store\Model\StoreManagerInterface;

/**
 * Class Addincrementstock
 *
 * @package FiloBlu\Flow\Model\Actions\From
 */
class Addincrementstock
{
    /**
     * @var StockRegistryInterface
     */
    protected $stockRegistry;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * Addincrementstock constructor.
     * @param StockRegistryInterface $stockRegistry
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        StockRegistryInterface $stockRegistry,
        StoreManagerInterface $storeManager
    )
    {
        $this->stockRegistry = $stockRegistry;
        $this->storeManager = $storeManager;
    }

    /**
     * @param $product
     * @param $value
     * @param $storeId
     * @throws Exception
     */
    public function process($product, $value, $storeId)
    {
        if ((int)$storeId !== 0) {
            throw new Exception('The function is avalaible only for the ADMIN store.');
        }

        $this->storeManager->setCurrentStore($storeId);

        $productId = $product->getId();

        if (empty($productId)) {
            throw new Exception(sprintf('Product not found! product_code: \'%s\'', $product->getSku()));
        }

        if ($value !== null && $value !== '') {
            throw new Exception("Invalid value supplied '{$value}'");
        }
        $stock = $this->stockRegistry->getStockItem($productId);

        if (!is_numeric($value)) {
            throw new Exception("Product increment value wrong: '{$value}'");
        }

        /* $value > 0 */
        if ($value > 0) {
            $stock->setUseConfigEnableQtyInc(false);
            $stock->setUseConfigQtyIncrements(false);
            $stock->setEnableQtyIncrements(true);
            $stock->setQtyIncrements($value);
            $stock->save();
            return;
        }

        /* $value < 0 */
        $stock->setEnableQtyIncrements(false);
        $stock->setUseConfigEnableQtyInc(true);
        $stock->setUseConfigQtyIncrements(true);
        $stock->save();

    }

}
