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

namespace Mageants\SimpleConfigurable\Controller\Index;

use Magento\Framework\Controller\ResultFactory;

class AjaxRequest extends \Magento\Framework\App\Action\Action
{
    public $_registry;
    public $_pageFactory;
    public $_productloader;
    public $simpleConfigurableHelper;
    public $_scopeConfig;
    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Catalog\Model\ProductFactory $_productloader
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Mageants\SimpleConfigurable\Helper\Data $simpleConfigurableHelper
     * @param \Magento\Framework\View\Result\PageFactory $pageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Catalog\Model\ProductFactory $_productloader,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Mageants\SimpleConfigurable\Helper\Data $simpleConfigurableHelper,
        \Magento\Framework\View\Result\PageFactory $pageFactory
    ) {
        $this->_registry = $registry;
        $this->_pageFactory = $pageFactory;
        $this->_productloader = $_productloader;
        $this->simpleConfigurableHelper = $simpleConfigurableHelper;
        $this->_scopeConfig = $scopeConfig;
        parent::__construct($context);
    }

    /**
     * @inheritdoc
     */
    public function execute()
    {
        $enable = $this->isEnable();
        $showqtyEnable = $this->showQtyEnable();
        if ($enable == 1 && $showqtyEnable == 1) {
            $productId = $this->getRequest()->getParam('id');
            $productData = $this->_productloader->create()->load($productId);
            $qty = $productData->getQuantityAndStockStatus();
            $availableQty = $qty['qty'];
            $qtyDiv = " <div> Available Quantity : $availableQty </div>";
            $responseArray['status'] = "success";
            $responseArray['success_message'] = $qtyDiv;
        } else {
            $responseArray['status'] = "error";
        }
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData($responseArray);
        return $resultJson;
    }

    /**
     * Check is enable
     *
     * @return string
     */
    public function isEnable()
    {
        return $this->simpleConfigurableHelper->isEnable();
    }

    /**
     * Show qty enable
     *
     * @return string
     */
    public function showQtyEnable()
    {
        return $this->simpleConfigurableHelper->showQtyEnable();
    }
}
