<?php
namespace Autogedal\Extend\Model;

use Magento\Framework\View\Element\Template;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Bundle\Model\Product\Type as BundleType;
use Magento\CatalogInventory\Api\StockRegistryInterface;

class IsBundleProductChildrenSalable extends Template
{
    protected $productRepository;
    protected $stockRegistry;

    public function __construct(
        Template\Context $context,
        ProductRepositoryInterface $productRepository,
        StockRegistryInterface $stockRegistry,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        $this->stockRegistry = $stockRegistry;
        parent::__construct($context, $data);
    }

    /**
     * Get child products and their quantities of a bundle product
     *
     * @param int $bundleProductId
     * @return array
     */
    public function execute($bundleProductId)
    {
        $bundleProduct = $this->productRepository->getById($bundleProductId);
        if ($bundleProduct->getTypeId() !== BundleType::TYPE_CODE) {
            return []; // Not a bundle product
        }

        $bundleOptions = $bundleProduct->getTypeInstance()->getSelectionsCollection(
            $bundleProduct->getTypeInstance()->getOptionsIds($bundleProduct),
            $bundleProduct
        );

        $childrenStocks = [];

        foreach ($bundleOptions as $option) {
            $childProduct = $this->productRepository->getById($option->getProductId());
            $stockItem = $this->stockRegistry->getStockItem($childProduct->getId());

            if ($stockItem->getQty() < 1) {
                return false;
            }
            $childrenStocks[] = $stockItem->getQty();
        }

        return min($childrenStocks);
    }
}
