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

use Magento\Quote\Model\Cart\CartTotalRepository;
use Magento\Quote\Api\Data\TotalsInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\QuoteFactory;
use Magento\Quote\Model\QuoteRepository;
use Magento\Checkout\Model\Session;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableType;;
use Mageants\SimpleConfigurable\Helper\Data as SCPHelper;

class ModifyCheckoutItemData
{
    /**
     * @var QuoteRepository
     */
    protected $quoteRepository;

    /**
     * @var Session
     */
    protected $checkoutSession;

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

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

    /**
     * Constructor
     *
     * @param QuoteRepository $quoteRepository
     * @param Session $checkoutSession
     * @param ConfigurableType $configurableType
     * @param SCPHelper $scpHelper
     */
    public function __construct(
        QuoteRepository $quoteRepository,
        Session $checkoutSession,
        ConfigurableType $configurableType,
        SCPHelper $scpHelper
    ) {
        $this->quoteRepository = $quoteRepository;
        $this->checkoutSession = $checkoutSession;
        $this->configurableType = $configurableType;
        $this->scpHelper = $scpHelper;
    }

    /**
     * Modify the checkout order summary item data.
     *
     * @param CartTotalRepository $subject
     * @param TotalsInterface $result
     * @return TotalsInterface
     */
    public function afterGet(CartTotalRepository $subject, TotalsInterface $result)
    {
        if (!$this->scpHelper->isEnable() || !$this->scpHelper->updateChieldInCart()) {
            return $result;
        }

        $quote = $this->checkoutSession->getQuote();
        foreach ($result->getItems() as $item) {
            $itemId = $item->getItemId();
            $quoteItem = $quote->getItemById($itemId);

            if ($quoteItem && $quoteItem->getProductType() === ConfigurableType::TYPE_CODE && $quoteItem->getHasChildren()) {
                $childItem = $quoteItem->getChildren();
                foreach ($childItem as $child) {
                    $item->setName($child->getName());
                    $options = $item->getOptions();
                    $newOptions = $this->filterConfigurableAttributes($quoteItem->getProduct(), $options);
                    $item->setOptions($newOptions);
                    break;
                }
            } elseif ($quoteItem && $quoteItem->getProductType() == 'simple') {
                $option = $quoteItem->getOptionByCode('additional_options');
                if ($option) {
                    $optionData = $option->getData();
                    $options = $optionData['value'];
                    if ($options) {
                        $optionData['value'] = $options;
                        $option->setData($optionData);
                        $option->setValue($options);
                    }
                }
            }
        }
        return $result;
    }

    /**
     * Filter options to remove configurable attributes.
     *
     * @param \Magento\Catalog\Model\Product $product
     * @param string $optionsJson
     * @return string
     */
    private function filterConfigurableAttributes($product, $optionsJson)
    {
        $options = json_decode($optionsJson, true);
        $configurableAttributes = $this->configurableType->getConfigurableAttributesAsArray($product);

        $configurableLabels = [];
        foreach ($configurableAttributes as $attribute) {
            $configurableLabels[] = $attribute['label'];
        }

        $filteredOptions = array_filter($options, function ($option) use ($configurableLabels) {
            return !in_array($option['label'], $configurableLabels);
        });

        return json_encode(array_values($filteredOptions));
    }
}
