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

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order\Item as OrderItemModel;
use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Aitoc\PreOrders\Model\OrderItemPreOrderSettingsRepository;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Class SaveOrderItemStatus
 */
class SaveOrderItemStatus implements ObserverInterface
{
    /**
     * @var PreOrderHelper
     */
    private $preOrderHelper;

    /**
     * @var OrderItemPreOrderSettingsRepository
     */
    private $orderItemPreOrderSettingsRepository;

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

    /**
     * Save Pre-Order flag for order items
     *
     * @param Observer $observer
     * @throws LocalizedException
     */
    public function execute(Observer $observer)
    {
        $orderItems = $observer->getOrder()->getItems();
        foreach ($orderItems as $orderItem) {
            $this->saveOrderItemSettings($orderItem);
        }
    }

    /**
     * @param OrderItemModel $orderItem
     * @throws CouldNotSaveException
     * @throws LocalizedException
     * @throws NoSuchEntityException
     */
    private function saveOrderItemSettings(OrderItemModel $orderItem)
    {
        $orderItemId = $orderItem->getId();
        if ($orderItem->getProduct()->getTypeId() == 'configurable') {
            $childrenItems = $orderItem->getChildrenItems();
            $product = reset($childrenItems);
            $productId = $product->getId();
        } else {
            $productId = $orderItem->getProductId();
        }
        $isPreOrder = $this->preOrderHelper->isProductPreOrder($productId);
        $settingsModel = $this->orderItemPreOrderSettingsRepository->getByOrderItemId($orderItemId);
        $settingsModel->setOrderItemId($orderItemId)
            ->setIsPreOrder($isPreOrder);
        $this->orderItemPreOrderSettingsRepository->save($settingsModel);
    }
}
