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

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

namespace Aitoc\PreOrders\Plugin\CatalogInventory\Model\Stock;

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

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

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

    /**
     * @param CatalogInventoryStockItem $stockItem
     * @param bool $result
     * @return bool
     */
    public function afterGetIsInStock(
        CatalogInventoryStockItem $stockItem,
        $result
    ) {
        if ($productId = $stockItem->getProductId()) {
            $isPreOrder = $this->preOrderHelper->isProductPreOrder($productId);
            if ($isPreOrder) {
                return true;
            } else {
                if ($this->preOrderHelper->isProductOutOfStockPreOrder($productId)) {
                    return false;
                }
            }
        }

        return $result;
    }
}
