<?php
namespace Mageants\SimpleConfigurable\Plugin\Sales\Order;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableType;
use Magento\Sales\Model\Order\Item;
use Mageants\SimpleConfigurable\Helper\Data as SCPHelper;

class ItemPlugin
{
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    /**
     * @var ConfigurableType
     */
    private $configurableType;

    /**
     * @var SCPHelper
     */
    protected $scpHelper;

    /**
     * @param ProductRepositoryInterface $productRepository
     * @param ConfigurableType $configurableType
     * @param SCPHelper $scpHelper
     */
    public function __construct(
        ProductRepositoryInterface $productRepository,
        ConfigurableType $configurableType,
        SCPHelper $scpHelper
    ) {
        $this->productRepository = $productRepository;
        $this->configurableType = $configurableType;
        $this->scpHelper = $scpHelper;
    }

    /**
     * Modify product options to hide configurable options for ordered items
     *
     * @param Item $subject
     * @param array|null $result
     * @return array|null
     */
    public function afterGetProductOptions(Item $subject, $result)
    {
        if (!$this->scpHelper->isEnable() || !$this->scpHelper->updateChieldInOrder()) {
            return $result;
        }

        // Check if the product is configurable
        if ($subject->getProductType() === 'configurable' && isset($result['attributes_info'])) {
            $productId = $subject->getProductId();

            $temp_result = $result;
            try {
                // Load the configurable product
                $product = $this->productRepository->getById($productId);

                // Get configurable attributes
                $configurableAttributes = $this->configurableType->getConfigurableAttributesAsArray($product);

                // Extract attribute labels from the configurable product
                $configurableAttributeLabels = array_column($configurableAttributes, 'label');

                // Filter out configurable attributes from the result
                $filteredAttributes = array_filter($result['attributes_info'], function ($attribute) use ($configurableAttributeLabels) {
                    return isset($attribute['label']) && !in_array($attribute['label'], $configurableAttributeLabels);
                });

                $result['attributes_info'] = $filteredAttributes;
            } catch (\Exception $e) {
                $result = $temp_result;
            }
        }
        return $result;
    }
}
