<?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\Stock;

use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Magento\CatalogInventory\Model\Stock\Status as CatalogInventoryStockStatus;

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

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

    /**
     * @param CatalogInventoryStockStatus $stockItem
     * @param                             $result
     *
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function afterGetStockStatus(
        CatalogInventoryStockStatus $subject,
        $result
    ) {
        if ($productId = $subject->getProductId()) {
            $isPreOrder = $this->preOrderHelper->isProductPreOrder($productId);
            if ($isPreOrder) {
                return true;
            } else {
                if ($this->preOrderHelper->isProductOutOfStockPreOrder($productId)) {
                    return false;
                }
            }
        }

        return $result;
    }
}
