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

namespace Mageants\SimpleConfigurable\Plugin\Block\Checkout\Cart\Item;

use Magento\Catalog\Model\ProductRepository;
use Magento\Checkout\Block\Cart\Item\Renderer as CartItemRenderer;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\TestFramework\Inspection\Exception;
use Magento\Bundle\Model\Product\Type as BundleProductType;
use Mageants\SimpleConfigurable\Helper\Data as SCPHelper;
use Magento\Store\Model\StoreManagerInterface;

class Renderer
{
    /**
     * @var ProductRepository
     */
    protected $productRepository;

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

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

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

    /**
     * Renderer constructor.
     * @param ScopeConfigInterface $scopeConfig
     * @param ProductRepository $productRepository
     * @param SCPHelper $scpHelper
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        ProductRepository $productRepository,
        SCPHelper $scpHelper,
        StoreManagerInterface $storeManager
    ) {
        $this->productRepository = $productRepository;
        $this->scopeConfig = $scopeConfig;
        $this->scpHelper = $scpHelper;
        $this->storeManager = $storeManager;
    }

    /**
     * @param CartItemRenderer $subject
     * @param $result
     * @return string
     */
    public function afterGetProductName(
        CartItemRenderer $subject,
        $result
    ) {
        $isEnable = ($this->scpHelper->isEnable() && $this->scpHelper->updateChieldInCart());
        $currentProduct = $subject->getProduct();
        if ($isEnable && !empty($currentProduct)) {
            $changeName = $this->scopeConfig->getValue('simpleconfigurable_config/simpleconfigurable_settings/enable');
            if ($changeName && $currentProduct->getTypeId() !== BundleProductType::TYPE_CODE) {
                $simpleOption = $currentProduct->getCustomOption('simple_product');
                if (!empty($simpleOption)) {
                    $optionProduct = $simpleOption->getProduct();
                    if (!empty($optionProduct)) {
                        return $optionProduct->getName();
                    }
                }
            }
        }
        return $result;
    }

    /**
     * Plugin method to customize the product URL.
     *
     * @param CartItemRenderer $subject
     * @param string $result
     * @return string
     */
    public function afterGetProductUrl(CartItemRenderer $subject, string $result): string
    {
        $isEnable = ($this->scpHelper->isEnable() && $this->scpHelper->updateChieldInCart());
        if ($isEnable) {
            $item = $subject->getItem();
            $product = $item->getProduct();

            if (!empty($product->getCustomOption('fb_child_product'))) {
                $icpChildProduct = $product->getCustomOption('fb_child_product')->getProduct();
                return $this->generateChildProductUrl($icpChildProduct);
            } elseif ($product->getTypeId() !== BundleProductType::TYPE_CODE) {
                $simpleProductOption = $product->getCustomOption('simple_product');
                if (!empty($simpleProductOption)) {
                    $icpChildProduct = $simpleProductOption->getProduct();
                    return $this->generateChildProductUrl($icpChildProduct);
                }
            }
        }
        return $result;
    }

    /**
     * Generate Product Url
     *
     * @param object $childProduct
     * @return string
     */
    protected function generateChildProductUrl($childProduct)
    {
        $baseUrl = $this->storeManager->getStore()->getBaseUrl();
        $suffixValue = $this->scopeConfig->getValue(
            \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );

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

        return $childProductUrl;
    }

    /**
     * Before plugin for getImage method
     *
     * @param \Magento\Checkout\Block\Cart\Item\Renderer $subject
     * @param Product $product
     * @param string $imageId
     * @param array $attributes
     * @return array
     */
    public function beforeGetImage(
        \Magento\Checkout\Block\Cart\Item\Renderer $subject,
        $product,
        $imageId,
        $attributes = []
    ) {
        $isEnable = ($this->scpHelper->isEnable() && $this->scpHelper->updateChieldInCart());
        if ($isEnable) {
            if (!empty($product->getCustomOption('fb_child_product'))) {
                $icpChildProduct = $product->getCustomOption('fb_child_product')->getProduct();
            } elseif ($product->getTypeId() !== \Magento\Bundle\Model\Product\Type::TYPE_CODE) {
                $simpleProductOption = $product->getCustomOption('simple_product');
                if (!empty($simpleProductOption)) {
                    $icpChildProduct = $simpleProductOption->getProduct();
                }
            }
            $product = isset($icpChildProduct) ? $icpChildProduct : $product;
        }
        return [$product, $imageId, $attributes];
    }
}
