<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_MpPayPal
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\MpPayPal\Block\Adminhtml\System\Config;

use Magento\Framework\App\Config\ScopeConfigInterface;

class Button extends \Magento\Config\Block\System\Config\Form\Field
{
    protected $_template = 'Webkul_MpPayPal::system/config/button.phtml';

    /**
     * dependency initialization
     *
     * @param \Magento\Backend\Block\Template\Context $context
     * @param ScopeConfigInterface $scopeConfig
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        ScopeConfigInterface $scopeConfig,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->scopeConfig = $scopeConfig;
    }

    public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        $element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
        return parent::render($element);
    }
    
    protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        return $this->_toHtml();
    }

    /**
     * get webhook url
     *
     * @return string
     */
    public function getAjaxUrl()
    {
        return $this->getUrl('mppaypal/system/webhook');
    }

    /**
     * button html
     *
     * @return string
     */
    public function getButtonHtml()
    {

        $environment = $this->scopeConfig
        ->getValue('payment/mppaypal/environment', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

        $path = 'payment/mppaypal/webhook_sandbox_id';
        if ($environment == 'production') {
            $path = 'payment/mppaypal/webhook_production_id';
        }

        $webHookId = $this->scopeConfig->getValue(
            $path,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $secretkey = $this->scopeConfig->getValue(
            'payment/mppaypal/secret',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        if (!$webHookId && $secretkey) {
            $button = $this->getLayout()->createBlock(
                \Magento\Backend\Block\Widget\Button::class
            )->setData(
                [
                    'id' => 'webhooks',
                    'label' => __('Generate Webhooks'),
                ]
            );
    
            return $button->toHtml();
        }
        return '';
    }
}
