<?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\Observer\BackInStockEmails;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\Catalog\Model\Product;
use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Magento\Framework\Registry;
use Aitoc\PreOrders\Api\Data\Source\RegistryNameInterface;

/**
 * Class Prepare
 */
class Prepare implements ObserverInterface
{
    /**
     * Stock Registry
     *
     * @var StockRegistryInterface
     */
    private $stockRegistry;

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

    /**
     * @var PreOrderHelper
     */
    private $preOrderHelper;

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

    /**
     * @param Observer $observer
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function execute(Observer $observer)
    {
        /** @var Product $product */
        $product = $observer->getEvent()->getProduct();
        $productId = $product->getId();

        if ($this->preOrderHelper->isProductPreOrder($productId)) {
            if ($this->registry->registry(RegistryNameInterface::SAVED_PRE_ORDER_PRODUCT)) {
                $this->registry->unregister(RegistryNameInterface::SAVED_PRE_ORDER_PRODUCT);
            }
            $this->registry->register(RegistryNameInterface::SAVED_PRE_ORDER_PRODUCT, true);
        }
    }
}