<?php
/**
 * Maho
 *
 * @category    design
 * @package     base_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)
 */
/** @var Mage_Catalog_Block_Product_View_Options $this */
?>

<?php $_options = Mage::helper('core')->decorateArray($this->getOptions()) ?>
<?php if (count($_options)):?>
    <script type="text/javascript">
        const optionFileUpload = {
            productForm: document.getElementById('product_addtocart_form'),
            formAction: '',
            formElements: {},

            upload: function(element) {
                this.formElements = Array.from(this.productForm.querySelectorAll('input, select, textarea, button'));
                const optionId = element.id.replace('option_', '');
                this.removeRequire(optionId);

                const template = '<iframe id="upload_target" name="upload_target" style="width:0; height:0; border:0;"></iframe>';

                const uploadedFileEl = document.getElementById(`option_${optionId}_uploaded_file`);
                uploadedFileEl.insertAdjacentHTML('afterend', template);

                this.formAction = this.productForm.action;

                const baseUrl = '<?= $this->getUrl('*/product/upload') ?>';
                const urlExt = `option_id/${optionId}`;

                this.productForm.action = parseSidUrl(baseUrl, urlExt);
                this.productForm.target = 'upload_target';
                this.productForm.submit();
                this.productForm.target = '';
                this.productForm.action = this.formAction;
            },

            removeRequire: function(skipElementId) {
                this.formElements.forEach(element => {
                    if (element.id !== `option_${skipElementId}_file` && element.type !== 'button') {
                        element.disabled = true;
                    }
                });
            },

            addRequire: function(skipElementId) {
                this.formElements.forEach(element => {
                    if (element.getAttribute('name') !== `options_${skipElementId}_file` && element.type !== 'button') {
                        element.disabled = false;
                    }
                });
            },

            uploadCallback: function(data) {
                this.addRequire(data.optionId);
                document.getElementById('upload_target').remove();

                if (data.error) {
                    // Handle error case
                } else {
                    const uploadedFileEl = document.getElementById(`option_${data.optionId}_uploaded_file`);
                    const fileEl = document.getElementById(`option_${data.optionId}_file`);
                    const optionEl = document.getElementById(`option_${data.optionId}`);

                    uploadedFileEl.value = data.fileName;
                    fileEl.value = '';
                    fileEl.style.display = 'none';
                    optionEl.style.display = 'none';

                    const template = `
                        <div id="option_${data.optionId}_file_box">
                            <a href="#"><img src="var/options/${data.fileName}" alt=""></a>
                            <a href="#" onclick="optionFileUpload.removeFile(${data.optionId})" title="Remove file">Remove file</a>
                        </div>`;
                    uploadedFileEl.insertAdjacentHTML('afterend', template);
                }
            },

            removeFile: function(optionId) {
                const uploadedFileEl = document.getElementById(`option_${optionId}_uploaded_file`);
                const fileEl = document.getElementById(`option_${optionId}_file`);
                const optionEl = document.getElementById(`option_${optionId}`);
                const fileBoxEl = document.getElementById(`option_${optionId}_file_box`);

                uploadedFileEl.value = '';
                fileEl.style.display = 'block';
                optionEl.style.display = 'block';
                fileBoxEl.remove();
            }
        };

        const optionTextCounter = {
            count: function(field, cntfield, maxlimit) {
                if (field.value.length > maxlimit) {
                    field.value = field.value.slice(0, maxlimit);
                } else {
                    cntfield.textContent = maxlimit - field.value.length;
                }
            }
        };

        class ProductOptions {
            constructor(config) {
                this.config = config;
                this.reloadPrice();
                document.addEventListener('DOMContentLoaded', () => this.reloadPrice());
            }

            reloadPrice() {
                const config = this.config;
                const skipIds = [];

                document.querySelectorAll('body .product-custom-option').forEach(element => {
                    let optionId = 0;
                    const match = element.name.match(/[0-9]+/);
                    if (match) {
                        optionId = parseInt(match[0], 10);
                    }

                    if (config[optionId]) {
                        const configOptions = config[optionId];
                        let curConfig = {price: 0};

                        if (element.type === 'checkbox' || element.type === 'radio') {
                            if (element.checked) {
                                if (typeof configOptions[element.value] !== 'undefined') {
                                    curConfig = configOptions[element.value];
                                }
                            }
                        } else if (element.classList.contains('datetime-picker') && !skipIds.includes(optionId)) {
                            let dateSelected = true;
                            document.querySelectorAll(`.product-custom-option[id^="options_${optionId}"]`)
                                .forEach(dt => {
                                    if (dt.value === '') {
                                        dateSelected = false;
                                    }
                                });

                            if (dateSelected) {
                                curConfig = configOptions;
                                skipIds[optionId] = optionId;
                            }
                        } else if (element.type === 'select-one' || element.type === 'select-multiple') {
                            if ('options' in element) {
                                Array.from(element.options).forEach(selectOption => {
                                    if ('selected' in selectOption && selectOption.selected) {
                                        if (typeof configOptions[selectOption.value] !== 'undefined') {
                                            curConfig = configOptions[selectOption.value];
                                        }
                                    }
                                });
                            }
                        } else {
                            if (element.value.trim() !== '') {
                                curConfig = configOptions;
                            }
                        }

                        if (element.type === 'select-multiple' && ('options' in element)) {
                            Array.from(element.options).forEach(selectOption => {
                                if ('selected' in selectOption &&
                                    typeof configOptions[selectOption.value] !== 'undefined') {
                                    if (selectOption.selected) {
                                        curConfig = configOptions[selectOption.value];
                                    } else {
                                        curConfig = {price: 0};
                                    }
                                    optionsPrice.addCustomPrices(`${optionId}-${selectOption.value}`, curConfig);
                                    optionsPrice.reload();
                                }
                            });
                        } else {
                            optionsPrice.addCustomPrices(element.id || optionId, curConfig);
                            optionsPrice.reload();
                        }
                    }
                });
            }
        }

        function validateOptionsCallback(elmId, result) {
            const element = document.getElementById(elmId);
            const container = element.closest('ul.options-list');

            if (result === 'failed') {
                container.classList.remove('validation-passed');
                container.classList.add('validation-failed');
            } else {
                container.classList.remove('validation-failed');
                container.classList.add('validation-passed');
            }
        }

        const opConfig = new ProductOptions(<?= $this->getJsonConfig() ?>);
    </script>
    <dl>
    <?php foreach($_options as $_option): ?>
        <?= $this->getOptionHtml($_option) ?>
    <?php endforeach ?>
    </dl>
<?php endif ?>
