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

namespace Mageants\SimpleConfigurable\Checkout\CustomerData;

use Magento\Bundle\Model\Product\Type as BundleProductType;
use Magento\Catalog\Model\Product\Configuration\Item\ItemResolverInterface;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Mageants\SimpleConfigurable\Helper\Data as SCPHelper;
use Magento\Store\Model\StoreManagerInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableType;

/**
 * Class DefaultItem
 * @package Mageants\SimpleConfigurable\Checkout\CustomerData
 */
class DefaultItem extends \Magento\Checkout\CustomerData\DefaultItem
{
    /**
     * @var ProductRepository
     */
    protected $productRepository;

    /**
     * @var \Magento\Framework\Escaper
     */
    private $escaper;

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

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

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

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

    /**
     * DefaultItem constructor.
     * @param \Magento\Catalog\Helper\Image $imageHelper
     * @param \Magento\Msrp\Helper\Data $msrpHelper
     * @param \Magento\Framework\UrlInterface $urlBuilder
     * @param \Magento\Catalog\Helper\Product\ConfigurationPool $configurationPool
     * @param \Magento\Checkout\Helper\Data $checkoutHelper
     * @param ProductRepository $productRepository
     * @param ScopeConfigInterface $scopeConfig
     * @param \Magento\Framework\Escaper|null $escaper
     * @param ItemResolverInterface|null $itemResolver
     * @param SCPHelper $scpHelper
     * @param StoreManagerInterface $storeManager
     * @param ConfigurableType $configurableType
     */
    public function __construct(
        \Magento\Catalog\Helper\Image $imageHelper,
        \Magento\Msrp\Helper\Data $msrpHelper,
        \Magento\Framework\UrlInterface $urlBuilder,
        \Magento\Catalog\Helper\Product\ConfigurationPool $configurationPool,
        \Magento\Checkout\Helper\Data $checkoutHelper,
        ProductRepository $productRepository,
        ScopeConfigInterface $scopeConfig,
        SCPHelper $scpHelper,
        StoreManagerInterface $storeManager,
        ConfigurableType $configurableType,
        ?\Magento\Framework\Escaper $escaper = null,
        ?ItemResolverInterface $itemResolver = null
    ) {
        parent::__construct(
            $imageHelper,
            $msrpHelper,
            $urlBuilder,
            $configurationPool,
            $checkoutHelper,
            $escaper,
            $itemResolver
        );
        $this->escaper = $escaper ?: ObjectManager::getInstance()->get(\Magento\Framework\Escaper::class);
        $this->productRepository = $productRepository;
        $this->scopeConfig = $scopeConfig;
        $this->scpHelper = $scpHelper;
        $this->storeManager = $storeManager;
        $this->configurableType = $configurableType;
    }

    /**
     * @inheritDoc
     */
    protected function doGetItemData()
    {
        $isEnable = ($this->scpHelper->isEnable() && $this->scpHelper->updateChieldInCart());
        if ($isEnable) {
            $imageHelper = $this->imageHelper->init($this->getProductForThumbnail(), 'mini_cart_product_thumbnail');
            $productName = $this->escaper->escapeHtml($this->item->getProduct()->getName());
            $product = $this->item->getProduct();
            $changeName = $this->scopeConfig->getValue('simpleconfigurable_config/simpleconfigurable_settings/updatechieldincart') &&
                $product->getTypeId() !== BundleProductType::TYPE_CODE;
            if (!empty($this->item->getProduct()->getCustomOption('fb_child_product'))) {
                $icpChildProduct = $this->item->getProduct()->getCustomOption('fb_child_product')->getProduct();
                $icpChildProductSku = $icpChildProduct->getData('sku');
                $productSku = $this->getIcpOptionSku($product, $icpChildProduct, $icpChildProductSku);
                if ($changeName) {
                    $productName = $icpChildProduct->getName();
                }
                $filteredOptions = $this->filterConfigurableAttributes($product, $this->getOptionList());
            } else {
                $productSku = $this->item->getProduct()->getSku();
                $filteredOptions = $this->filterConfigurableAttributes($product, $this->getOptionList());
                if ($changeName) {
                    $simpleProductOption = $this->item->getProduct()->getCustomOption('simple_product');
                    if (!empty($simpleProductOption)) {
                        $icpChildProduct = $simpleProductOption->getProduct();
                        $productName = $icpChildProduct->getName();
                    }
                }
            }
            if (isset($icpChildProduct)) {
                $imageHelper = $this->imageHelper->init($icpChildProduct, 'mini_cart_product_thumbnail');

                $baseUrl = $this->storeManager->getStore()->getBaseUrl();
                $suffixValue = $this->scopeConfig->getValue(
                    \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX,
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                );

                if (!empty($suffixValue)) {
                    $childProductUrl = $baseUrl;
                    $childProductUrl .= $icpChildProduct->getUrlKey();
                    $childProductUrl .= $suffixValue;
                } else {
                    $childProductUrl = $baseUrl;
                    $childProductUrl .= $icpChildProduct->getUrlKey();
                }
            }

            return [
                'options' => $filteredOptions,
                'qty' => $this->item->getQty() * 1,
                'item_id' => $this->item->getId(),
                'configure_url' => $this->getConfigureUrl(),
                'is_visible_in_site_visibility' => $this->item->getProduct()->isVisibleInSiteVisibility(),
                'product_id' => $this->item->getProduct()->getId(),
                'product_name' => $productName,
                'product_sku' => $productSku,
                'product_url' => isset($childProductUrl) ? $childProductUrl : $this->getProductUrl(),
                'product_has_url' => $this->hasProductUrl(),
                'product_price' => $this->checkoutHelper->formatPrice($this->item->getCalculationPrice()),
                'product_price_value' => $this->item->getCalculationPrice(),
                'product_image' => [
                    'src' => $imageHelper->getUrl(),
                    'alt' => $imageHelper->getLabel(),
                    'width' => $imageHelper->getWidth(),
                    'height' => $imageHelper->getHeight(),
                ],
                'canApplyMsrp' => $this->msrpHelper->isShowBeforeOrderConfirm($this->item->getProduct())
                    && $this->msrpHelper->isMinimalPriceLessMsrp($this->item->getProduct()),
                'message' => $this->item->getMessage(),
            ];
        } else {
            return parent::doGetItemData();
        }
    }

    /**
     * @param $product
     * @param $childProduct
     * @param string $sku
     * @return mixed|string
     */
    public function getIcpOptionSku($product, $childProduct, $sku = '')
    {
        if (!empty($childProduct)) {
            $skuDelimiter = '-';
            if (empty($sku)) {
                $sku = $childProduct->getData('sku');
            }
            $fbOptionIds = $product->getCustomOption('fb_option_ids');
            if (!empty($fbOptionIds)) {
                $optionIds = explode(',', $fbOptionIds->getValue());
                foreach ($optionIds as $optionId) {
                    $option = $childProduct->getOptionById($optionId);
                    if (!empty($option)) {
                        $confItemOption = $product->getCustomOption('fb_option_' . $optionId);
                        $group = $option->groupFactory($option->getType())
                            ->setOption($option)
                            ->setListener(new \Magento\Framework\DataObject());

                        $optionSku = $group->getOptionSku($confItemOption->getValue(), $skuDelimiter);
                        if ($optionSku) {
                            $sku .= $skuDelimiter . $optionSku;
                        }
                        if ($group->getListener()->getHasError()) {
                            $product->setHasError(true)->setMessage($group->getListener()->getMessage());
                        }
                    }
                }
            }
        }
        return $sku;
    }

    /**
     * Filters out configurable attributes from options.
     *
     * @param \Magento\Catalog\Model\Product $product
     * @param array $options
     * @return array
     */
    protected function filterConfigurableAttributes($product, $options)
    {
        if ($product->getTypeId() !== 'configurable') {
            return $options;
        }
    
        try {
            $configurableAttributes = $this->configurableType->getConfigurableAttributesAsArray($product);
            $configurableAttributeLabels = array_column($configurableAttributes, 'label');

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

            return $filteredOptions;
        } catch (\Exception $e) {
            return $options;
        }
    }
}
