<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Plugin\ConfigurableProduct\Block\Product\View\Type;


use Magento\ConfigurableProduct\Block\Product\View\Type\Configurable as MagentoConfigurableBlock;
use Magento\Framework\Json\EncoderInterface;
use Magento\Framework\Json\DecoderInterface;
use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Magento\Framework\Exception\LocalizedException;

class Configurable
{
    /**
     * @var EncoderInterface
     */
    private $jsonEncoder;

    /**
     * @var DecoderInterface
     */
    private $jsonDecoder;

    /**
     * @var PreOrderHelper
     */
    private $preOrderHelper;

    /**
     * @param EncoderInterface $jsonEncoder
     * @param DecoderInterface $jsonDecoder
     * @param PreOrderHelper $preOrderHelper
     */
    public function __construct(
        EncoderInterface $jsonEncoder,
        DecoderInterface $jsonDecoder,
        PreOrderHelper $preOrderHelper
    ) {
        $this->jsonDecoder = $jsonDecoder;
        $this->jsonEncoder = $jsonEncoder;
        $this->preOrderHelper = $preOrderHelper;
    }

    /**
     * @param MagentoConfigurableBlock $block
     * @param $config
     * @return string
     * @throws LocalizedException
     */
    public function afterGetJsonConfig(MagentoConfigurableBlock $block, $config)
    {
        $configArray = $this->jsonDecoder->decode($config);
        $productsData = [];
        $childProducts = $block->getAllowProducts();
        foreach ($childProducts as $childProduct) {
            $stockMessage = '';
            $buttonLabel = '';
            $productId = $childProduct->getId();
            if ($this->preOrderHelper->isProductPreOrder($productId)) {
                $stockMessage = $this->preOrderHelper->getPreOrderStatusLabelByProductId($productId);
                $buttonLabel = __('Pre-Order');
            }
            $productsData[$productId] = [
                'stockMessage' => $stockMessage,
                'buttonTitle' => $buttonLabel
            ];
        }
        $configArray['aitoc_pre_order_product_data'] = $productsData;
        $config = $this->jsonEncoder->encode($configArray);
        return $config;
    }
}
