<?php

namespace FiloBlu\Storelocator\Model\Rma;

use Magento\Catalog\Model\ProductRepository;
use Magento\Catalog\Model\ResourceModel\Product;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Model\AbstractModel;
use Magento\Sales\Api\OrderRepositoryInterface;

/**
 *
 */
class Returntostore extends AbstractModel
{

	/**
	 * @var OrderRepositoryInterface
	 */
	protected $orderRepository;

	/**
	 * @var ProductRepository
	 */
	protected $productRepository;

	/**
	 * @param OrderRepositoryInterface $orderRepository
	 * @param ProductRepository $productRepository
	 */
	public function __construct(OrderRepositoryInterface $orderRepository,
	                            ProductRepository $productRepository)
	{
		$this->orderRepository = $orderRepository;
		$this->productRepository = $productRepository;
	}

	/**
	 * @param $orderId
	 * @return array|null
	 * @throws NoSuchEntityException
	 */
	public function getItemsCategoriesByOrderId($orderId = null)
	{
		$prodCats = [];

		if (!is_null($orderId)) {
			$orderItems = $this->orderRepository->get($orderId)->getAllItems();
			foreach ($orderItems as $item) {
				$productId = $item->getData('product_id');
				$product = $this->productRepository->getById($productId);
				$prodCats[$productId] = $product->getCategoryIds();
			}
			return $prodCats;
		}

		return null;
	}
}
