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

/** @var $block \Magento\Bundle\Block\Adminhtml\Catalog\Product\Edit\Tab\Attributes\Extend */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
$elementHtml = $block->getParentElementHtml();

$attributeCode = $block->getAttribute()
    ->getAttributeCode();

$switchAttributeCode = "{$attributeCode}_type";
$switchAttributeValue = $block->getProduct()
    ->getData($switchAttributeCode);

$isElementReadonly = $block->getElement()
    ->getReadonly();
?>

<?php if (!($attributeCode === 'price' && $block->getCanReadPrice() === false)): ?>
    <div class="<?= $block->escapeHtmlAttr($attributeCode) ?> "><?= /* @noEscape */ $elementHtml ?></div>
<?php endif; ?>

<?= $block->getExtendedElement($switchAttributeCode)->toHtml() ?>

<?php if (!$isElementReadonly && $block->getDisableChild()) {
    $switchAttributeCode = /* @noEscape */ $switchAttributeCode;
    $scriptString = <<<script
        require(['prototype'], function () {
            function {$switchAttributeCode}_change() {
                var $attribute = $('{$block->escapeJs($attributeCode)}');
                if ($('{$switchAttributeCode}').value == '{$block->escapeJs($block::DYNAMIC)}') {
                    if ($attribute) {
                        $attribute.disabled = true;
                        $attribute.value = '';
                        $attribute.removeClassName('required-entry');
                    }
                    if ($('dynamic-price-warning')) {
                        $('dynamic-price-warning').show();
                    }
                } else {
                    if ($attribute) {
script;
    if ($attributeCode === 'price' && !$block->getCanEditPrice() &&
        $block->getCanReadPrice() && $block->getProduct()->isObjectNew()):
        $defaultProductPrice = $block->getDefaultProductPrice() ?: "''";
        $scriptString .= '$attribute.value = ' . /* @noEscape */ (string)$defaultProductPrice . ';';
    else:
        $scriptString = <<<script
            $attribute.disabled = false;
            $attribute.addClassName('required-entry');
script;
    endif;
    $scriptString .= <<<script
            }
                if ($('dynamic-price-warning')) {
                    $('dynamic-price-warning').hide();
                }
            }
        }
script;
    if (!($attributeCode === 'price' && !$block->getCanEditPrice() && !$block->getProduct()->isObjectNew())):
        $scriptString .= <<<script
            $('{$switchAttributeCode}').observe('change', {$switchAttributeCode}_change);
script;
    endif;
    $scriptString .= <<<script
            Event.observe(window, 'load', function(){
                {$switchAttributeCode}_change();
            });
        });
script;
    ?>
    <?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false) ?>
<?php } ?>
