<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var \Magento\Customer\Block\Adminhtml\System\Config\Validatevat $block */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>

<?php
 $merchantCountryField = $block->escapeJs($block->getMerchantCountryField());
 $merchantVatNumberField = $block->escapeJs($block->getMerchantVatNumberField());
 $ajaxUrl = $block->escapeJs($block->getAjaxUrl());
 $errorMessage = $block->escapeJs($block->escapeHtml(__('Error during VAT Number verification.')));

 $scriptString = <<<script
require(['prototype'], function(){

//<![CDATA[
    function validateVat() {
        var validationMessage = $('validation_result');

        params = {
            country: $('{$merchantCountryField}').value,
            vat: $('{$merchantVatNumberField}').value
        };

        new Ajax.Request('{$ajaxUrl}', {
            parameters: params,
            onSuccess: function(response) {
                var result = '{$errorMessage}';
                try {
                    if (response.responseText.isJSON()) {
                        response = response.responseText.evalJSON();
                        result = response.message;
                    }
                    if (response.valid == 1) {
                        validationMessage.removeClassName('hidden').removeClassName('admin__field-error').
                        addClassName('note');
                        validationMessage.setStyle({color:'green'});
                    } else {
                        validationMessage.removeClassName('hidden').addClassName('admin__field-error');
                        if (validationMessage.style.removeProperty) {
                            validationMessage.style.removeProperty('color');
                        } else {
                            validationMessage.style.removeAttribute('color');
                        }
                    }
                } catch (e) {
                    validationMessage.removeClassName('hidden').addClassName('admin__field-error');
                }
                validationMessage.update(result);
            }
        });
    }

    window.validateVat = validateVat;
//]]>

});
script;
?>
<?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false); ?>

<div class="actions actions-validate-vat">
    <p class="admin__field-error hidden" id="validation_result"></p>
    <button class="action-validate-vat" type="button" id="<?= /* @noEscape */ $block->getHtmlId() ?>"
            style="display:none">
        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>
    </button>
</div>
<?= /* @noEscape */ $secureRenderer->renderTag('style', [], '#validation_result {margin-bottom: 10px;}', false); ?>
<?= /* @noEscape */ $secureRenderer->renderEventListenerAsTag(
    'onclick',
    'validateVat();event.preventDefault();',
    '#' . /* @noEscape */ $block->getHtmlId()
); ?>
