<?php


namespace Magetop\Advancepreview\Block\Order;


use Magento\Framework\View\Element\Template;

class CustomInvoiceEmail extends \Magetop\Advancepreview\Block\AdvancePreviewAbstract
{
    protected $colPreviewOrderItemsFactory;
    public function __construct(
        Template\Context $context,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magetop\Advancepreview\Helper\Data $advancePreviewHelper,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory,
        array $data = []
    )
    {
        parent::__construct($context, $priceHelper, $advancePreviewHelper, $data);
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
    }


    /**
     * @param \Magento\Sales\Model\Order $order
     * @param $invoiceId
     * @return |null
     */
    public function getItemByItemId($order, $invoiceId) {
        $item = null;
        $itemId = $this->getItemIdByInvoiceId($invoiceId);
        if($itemId > 0 && $order && $order->getAllItems()) {
            foreach ($order->getAllItems() as $orderItem) {
                if($orderItem->getId() == $itemId) {
                    $item = $orderItem;
                    break;
                }
            }
        }
        return $item;
    }

    /**
     * @param int $invoiceId
     * @return array|int|mixed|null
     */
    public function getItemIdByInvoiceId($invoiceId = 0) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToSelect(array('item_id'))
            ->addFieldToFilter('invoice_id',$invoiceId);
        $itemId = $collection && $collection->getSize() > 0 ? $collection->getFirstItem()->getData('item_id') : 0;
        return $itemId;
    }

}
