<?php
/**
 * @category Mageants HyvaSimpleConfigurable
 * @package Mageants_HyvaSimpleConfigurable
 * @copyright Copyright (c) 2017 Mageants
 * @author Mageants Team <info@mageants.com>
 */
namespace Mageants\HyvaSimpleConfigurable\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\View\LayoutFactory;
use Magento\Catalog\Helper\Output as OutputHelper;
use Magento\Catalog\Model\Product as ProductModel;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Registry;
use Mageants\SimpleConfigurable\Helper\Data as SimpleConfigurableHelper;
use Magento\Store\Model\StoreManagerInterface;

class GetChildProductData extends Action
{

    /**
     * @var JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @var ProductRepository
     */
    protected $productRepository;

    /**
     * @var LayoutFactory
     */
    protected $layoutFactory;

    /**
     * @var OutputHelper
     */
    protected $output;

    /**
     * @var ProductModel
     */
    protected $productObj;

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

    /**
     * @var Registry
     */
    protected $coreRegistry;

    /**
     * @var SimpleConfigurableHelper
     */
    protected $simpleConfigurableHelper;

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

    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param ProductRepository $productRepository
     * @param LayoutFactory $layoutFactory
     * @param OutputHelper $output
     * @param ProductModel $productObj
     * @param ScopeConfigInterface $scopeConfig
     * @param Registry $coreRegistry
     * @param SimpleConfigurableHelper $simpleConfigurableHelper
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        ProductRepository $productRepository,
        LayoutFactory $layoutFactory,
        OutputHelper $output,
        ProductModel $productObj,
        ScopeConfigInterface $scopeConfig,
        Registry $coreRegistry,
        SimpleConfigurableHelper $simpleConfigurableHelper,
        StoreManagerInterface $storeManager
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->productRepository = $productRepository;
        $this->layoutFactory = $layoutFactory;
        $this->output = $output;
        $this->productObj = $productObj;
        $this->scopeConfig = $scopeConfig;
        $this->coreRegistry = $coreRegistry;
        $this->simpleConfigurableHelper = $simpleConfigurableHelper;
        $this->storeManager = $storeManager;
    }

    /**
     * Execute
     *
     * @return void
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        $productId = (int)$this->getRequest()->getParam('product_id');

        if (!$productId) {
            return $result->setData([
                'success' => false,
                'message' => 'Missing product_id.'
            ]);
        }

        try {
            $product = $this->productRepository->getById($productId);
            $reloadAttributes = $this->simpleConfigurableHelper->getReloadContent();
            $reloadValues = explode(',', $reloadAttributes);

            $productInfo = $this->_getProductInfo($product, $reloadValues);

            return $result->setData([
                'success' => true,
                'product_id' => $productId,
                'product_url' => $this->getProductFullUrlByProduct($product),
                'data' => $productInfo
            ]);
        } catch (\Exception $e) {
            return $result->setData([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * Get Product Information
     *
     * @param [type] $product
     * @param [type] $reloadValues
     * @return void
     */
    private function _getProductInfo($product, $reloadValues)
    {
        $reloadMeta = $this->simpleConfigurableHelper->updateMetaDta();
        if ($reloadMeta) {
            array_push($reloadValues, "meta_title", "meta_keyword", "meta_description", "canonical");
            $metaSelector = [
                'meta_title' => "meta[name='title']",
                'meta_keyword' => "meta[name='keywords']",
                'meta_description' => "meta[name='description']",
                'canonical' => "link[rel='canonical']"
            ];
        }

        $productInfo = [];

        $replaceBreadCrumbsData = $this->simpleConfigurableHelper->replaceBreadCrumbsData();
        if($replaceBreadCrumbsData) {
            $productInfo['breadCrumb'] = [
                'selector' => 'div .breadcrumbs .items .product',
                'value' => '<span aria-hidden="true" class="separator text-slate-600 px-2">/</span>' . $product->getName()
            ];
        }

        $layout = $this->layoutFactory->create();

        foreach ($reloadValues as $reloadValue) {
            $selector = $this->scopeConfig->getValue(
                'simpleconfigurable_config/simpleconfigurable_reload/' . $reloadValue,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            );

            if (!$selector && strpos($reloadValue, 'meta_') !== false) {
                $selector = $metaSelector[$reloadValue] ?? null;
            }

            if (!$selector && strpos($reloadValue, 'canonical') !== false) {
                $selector = $metaSelector[$reloadValue] ?? null;
            }

            if (!$selector) {
                continue;
            }

            if ($reloadValue === 'attributes') {
                $block = $layout->createBlock(
                    \Magento\Catalog\Block\Product\View\Attributes::class,
                    'product.attributes',
                    ['data' => []]
                )->setTemplate('product/view/attributes.phtml');

                $currentProduct = $this->coreRegistry->registry('product');
                $this->coreRegistry->unregister('product');
                $this->coreRegistry->register('product', $product);

                $value = $block->setProduct($product)->toHtml();
            } elseif ($reloadValue === 'canonical') {
                $value = $this->getProductFullUrlByProduct($product);
            } else {
                $product = $this->productObj->load($product->getId());
                $value = $this->output->productAttribute($product, $product->getData($reloadValue), $reloadValue);
            }

            // if ($value) {
                $productInfo[$reloadValue] = [
                    'selector' => $selector,
                    'value' => $value
                ];
            // }
        }

        return $productInfo;
    }

    /**
     * Get full product URL by appending URL suffix if set
     *
     * @param object $product
     * @return string
     */
    public function getProductFullUrlByProduct($product)
    {
        $suffixValue = $this->scopeConfig->getValue(
            \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );

        $urlKey = $product->getUrlKey();
        $baseUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);

        if (!empty($suffixValue)) {
            return $baseUrl . $urlKey . $suffixValue;
        }

        return $baseUrl . $urlKey;
    }
}
