<?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\Catalog\Model\Product\Type;

use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Magento\Framework\Registry;
use Aitoc\PreOrders\Api\Data\Source\RegistryNameInterface;
use Magento\Catalog\Model\Product\Type\AbstractType as ProductTypeAbstract;
use Magento\Catalog\Model\Product;

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

    /**
     * @var Registry
     */
    private $registry;

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

    /**
     * @param ProductTypeAbstract $subject
     * @param Product $product
     */
    public function beforeIsSalable(
        ProductTypeAbstract $subject,
        Product $product
    ) {
        if ($this->registry->registry(RegistryNameInterface::CURRENT_PRODUCT)) {
            $this->registry->unregister(RegistryNameInterface::CURRENT_PRODUCT);
        }
        $this->registry->register(RegistryNameInterface::CURRENT_PRODUCT, $product);
    }

    /**
     * @param ProductTypeAbstract $subject
     * @param bool $result
     * @return bool
     */
    public function afterIsSalable(
        ProductTypeAbstract $subject,
        $result
    ) {
        $product = $this->registry->registry(RegistryNameInterface::CURRENT_PRODUCT);
        $isPreOrder = $this->preOrderHelper->isProductPreOrder($product->getId());
        if ($isPreOrder) {
            return true;
        } else {
            if ($this->preOrderHelper->isProductOutOfStockPreOrder($product->getId())) {
                return false;
            }
        }
        return $result;
    }
}
