<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Plugins\Model\Product\Type;

use Magento\Catalog\Model\Product;

/**
 * Class Grouped
 * @package FiloBlu\Refilo\Plugins\Model\Product\Type
 */
class Grouped {

    /**
     * @see \Magento\GroupedProduct\Model\Product\Type\Grouped::getAssociatedProducts()
     *
     * @param \Magento\GroupedProduct\Model\Product\Type\Grouped $subject
     * @param Product $product
     * @return Product[]
     */
    public function beforeGetAssociatedProducts(\Magento\GroupedProduct\Model\Product\Type\Grouped $subject, Product $product)
    {
        if (!$product->hasData('_cache_instance_associated_products')) {
            $associatedProducts = [];

            $subject->setSaleableStatus($product);

            $collection = $subject->getAssociatedProductCollection(
                $product
            )->addAttributeToSelect(
                ['name', 'price', 'special_price', 'special_from_date', 'special_to_date', 'tax_class_id', 'image']
            )->setPositionOrder()->addStoreFilter(
                $subject->getStoreFilter($product)
            )->addAttributeToFilter(
                'status',
                ['in' => $subject->getStatusFilters($product)]
            );

            foreach ($collection as $item) {
                $associatedProducts[] = $item;
            }

            $product->setData('_cache_instance_associated_products', $associatedProducts);
        }

        return [$product];
    }
}
