<?php
/**
 * @category Mageants SimpleConfigurable
 * @package Mageants_SimpleConfigurable
 * @copyright Copyright (c) 2017 Mageants
 * @author Mageants Team <info@mageants.com>
 */
namespace Mageants\SimpleConfigurable\Observer\Sales;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Model\ProductFactory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableProductType;
use Mageants\SimpleConfigurable\Helper\Data as SCPHelper;

class OrderSaveAfter implements ObserverInterface
{
    /**
     * @var ProductFactory
     */
    protected $productFactory;

    /**
     * @var ConfigurableProductType
     */
    protected $configurableProductType;

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

    /**
     * @param ProductFactory $productFactory
     * @param ConfigurableProductType $configurableProductType
     * @param SCPHelper $scpHelper
     */
    public function __construct(
        ProductFactory $productFactory,
        ConfigurableProductType $configurableProductType,
        SCPHelper $scpHelper
    ) {
        $this->productFactory = $productFactory;
        $this->configurableProductType = $configurableProductType;
        $this->scpHelper = $scpHelper;
    }

    /**
     * Modify configurable product name for ordered items
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        if (!$this->scpHelper->isEnable() || !$this->scpHelper->updateChieldInOrder()) {
            return;
        }

        $order = $observer->getEvent()->getOrder();
        $items = $order->getAllItems();

        foreach ($items as $item) {
                $parentItem = $item->getParentItem();

            // Check if the item has a parent item and if the parent item is a configurable product
            if ($parentItem && $parentItem->getProductType() === ConfigurableProductType::TYPE_CODE) {
                // Load the child product (current item)
                $childProductId = $item->getProductId();
                $childProduct = $this->loadChildProduct($childProductId);

                // Set the parent item's name to the child product's name
                if ($childProduct) {
                    $parentItem->setName($childProduct->getName());
                }
            }
        }
    }

    /**
     * Load the child product by ID
     *
     * @param int $childProductId
     * @return \Magento\Catalog\Model\Product|null
     */
    protected function loadChildProduct($childProductId)
    {
        return $this->productFactory->create()->load($childProductId);
    }
}
