<?php

namespace FiloBlu\Rma\Block\Order\Email\Items;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\View\Element\Template\Context;
use Magento\Sales\Api\Data\OrderItemInterface;
use Magento\Sales\Block\Order\Email\Items\Order\DefaultOrder;

/**
 *
 */
class ChangeSizeOrder extends DefaultOrder
{
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;
    /**
     * @var ObjectManager
     */
    private $objectManager;

    /**
     * @param Context $context
     * @param ProductRepositoryInterface $productRepository
     * @param array $data
     */
    public function __construct(
        Context $context,
        ProductRepositoryInterface $productRepository,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->productRepository = $productRepository;
        $this->objectManager = ObjectManager::getInstance();
    }

    /**
     * @param OrderItemInterface $item
     * @return string
     */
    public function getSmallImageFromSimple(OrderItemInterface $item)
    {
        try {
            $parentSku = $item->getProductType() == 'configurable' ? $item->getSku() : $item->getProduct()->getParentSku();
            $parentProduct = $this->productRepository->get($parentSku, false, $item->getStoreId());
            return $parentProduct->getSmallImage();
        } catch (\Exception $e) {
            return '';
        }
    }

    public function getPreorder()
    {
        if (class_exists(\FiloBlu\Refilo\Block\Order\Email\Items\PreorderItem::class)) {
            return $this->objectManager->get(\FiloBlu\Refilo\Block\Order\Email\Items\PreorderItem::class);
        }

        return null;
    }
}
