<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Plugin\CatalogInventory\Model;

use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Magento\CatalogInventory\Model\StockStateProvider as CatalogInventoryStockStateProvider;
use Magento\CatalogInventory\Model\Stock\Item as CatalogInventoryStockItem;

/**
 * Class StockStateProvider
 */
class StockStateProvider
{
    /**
     * @var PreOrderHelper
     */
    private $preOrderHelper;

    /**
     * @param PreOrderHelper $preOrderHelper
     */
    public function __construct(
        PreOrderHelper $preOrderHelper
    ) {
        $this->preOrderHelper = $preOrderHelper;
    }

    /**
     * @param CatalogInventoryStockStateProvider $subject
     * @param bool $result
     * @return bool
     */
    public function afterCheckQty(
        CatalogInventoryStockStateProvider $subject,
        $result,
        CatalogInventoryStockItem $stockItem,
        $qty
    ) {
        if ($productId = $stockItem->getProductId()) {
            return $this->preOrderHelper->isQtyAvailable($productId, $qty);
        }

        return $result;
    }
}
