<?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\Framework\Registry;
use Aitoc\PreOrders\Api\Data\Source\RegistryNameInterface;
use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Aitoc\PreOrders\Helper\Settings as SettingsHelper;
use Magento\Framework\Exception\LocalizedException;
use Aitoc\PreOrders\Api\NotificationManagementInterface;
use Magento\Sales\Api\Data\OrderItemInterface;

/**
 * Class Send
 */
class Send implements ObserverInterface
{
    /**
     * @var Registry
     */
    private $registry;

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

    /**
     * @var SettingsHelper
     */
    private $settingsHelper;

    /**
     * @var NotificationManagementInterface
     */
    private $notificationManagement;

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

    /**
     * @param Observer $observer
     * @throws LocalizedException
     */
    public function execute(Observer $observer)
    {
        if ($this->settingsHelper->getBackInStockNotificationSetting()) {
            $isOrigPreOrder = (bool)$this->registry->registry(RegistryNameInterface::SAVED_PRE_ORDER_PRODUCT);
            if ($isOrigPreOrder) {
                /** @var OrderItemInterface $orderItem */
                $orderItem = $observer->getItem();
                $productId = $orderItem->getProductId();
                $isPreOrder = $this->preOrderHelper->isProductPreOrder($productId);
                if ($isPreOrder === false) {
                    $this->processNotificationSending($productId);
                }
            }
        }
    }

    /**
     * @param int $productId
     */
    private function processNotificationSending($productId)
    {
        $this->notificationManagement->sendBackInStockNotificationsByProductId($productId);
        $this->notificationManagement->sendFollowUpNotificationsByProductId($productId);
    }
}