<?php

namespace FiloBlu\Rma\Helper;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\App\Helper\AbstractHelper;

class ReturnableProductHelper extends AbstractHelper
{
    public function isProductReturnable(ProductInterface $product, $orderedSku = '') :bool
    {
        if (!$product->getIsReturnable()) {
            return false;
        }

        $notReturnableItems = [];

        if ($product->getTypeId() == 'configurable') {
            $configurable = $product->getTypeInstance();
            foreach ($configurable->getUsedProducts($product) as $child) {

                //reload product in order to force data refresh
                $child->load($child->getEntityId());

                if (!(bool)$child->getIsReturnable()) {
                    $notReturnableItems[] = $child->getSku();
                }

            }
        }

        if (in_array($orderedSku, $notReturnableItems)) {
            return false;
        }

        return true;
    }
}