<?php
/**
 * Maho
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://magento.com)
 * @copyright   Copyright (c) 2021-2024 The OpenMage Contributors (https://openmage.org)
 * @copyright   Copyright (c) 2024 Maho (https://mahocommerce.com)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>

<?php /** @var Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Bundle $this */ ?>
<?php $options = Mage::helper('core')->decorateArray($this->getOptions()); ?>
<?php if (count($options)): ?>
<div id="catalog_product_composite_configure_fields_bundle" class="<?= $this->getIsLastFieldset() ? 'last-fieldset' : '' ?>">
    <h4><?= Mage::helper('catalog')->__('Bundle Items') ?></h4>
    <div class="product-options">
        <dl>
            <?php foreach ($options as $option) : ?>
                <?php if ($option->getSelections()) : ?>
                    <?= $this->getOptionHtml($option) ?>
                <?php endif ?>
            <?php endforeach ?>
        </dl>
    </div>
</div>

<script>
    class BundleControl {
        constructor(config) {
            this.config = config;
        }

        changeSelection(selection) {
            if (selection.multiple) {
                return;
            }
            const parts = selection.id.split('-');
            const optionId = parts[2];
            const showQtyInput = selection.value && selection.value !== 'none';
            const options = this.config.options[optionId];
            const selectionOptions = options && options.selections && options.selections[selection.value] || {};

            selectionOptions.can_change_qty = Number(selectionOptions.can_change_qty) && showQtyInput;
            this.updateQtyInput(optionId, selectionOptions);
        }

        updateQtyInput(optionId, selectionOptions) {
            const elem = document.getElementById('bundle-option-' + optionId + '-qty-input');
            const default_qty = Number(selectionOptions.default_qty);
            if (!elem) {
                return;
            }
            if (selectionOptions.can_change_qty) {
                elem.classList.remove('qty-disabled');
                elem.disabled = false;
                if (elem.value === '0') {
                    elem.value = default_qty || 1;
                }
            } else {
                elem.classList.add('qty-disabled');
                elem.disabled = true;
                elem.value = default_qty || 0;
            }
        }

        updateForDefaults() {
            for (const optionId in this.config.options) {
                const selection = document.getElementById('bundle-option-' + optionId);
                if (selection) {
                    this.changeSelection(selection);
                }
            }
        }
    }
    ProductConfigure.bundleControl = new BundleControl(<?= $this->getJsonConfig() ?>);
</script>

<?php endif ?>
