<?php
/**
 * Maho
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://magento.com)
 * @copyright   Copyright (c) 2022 The OpenMage Contributors (https://openmage.org)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<script type="text/javascript">
    class DateOption {
        getDaysInMonth(month, year) {
            const curDate = new Date();
            if (!month) {
                month = curDate.getMonth();
            }
            if (2 == month && !year) { // leap year assumption for unknown year
                return 29;
            }
            if (!year) {
                year = curDate.getFullYear();
            }
            return 32 - new Date(year, month - 1, 32).getDate();
        }

        reloadMonth(event) {
            const selectEl = event.target;
            const idParts = selectEl.id.split("_");
            if (idParts.length != 3) {
                return false;
            }
            const optionIdPrefix = idParts[0] + "_" + idParts[1];
            const month = parseInt(document.getElementById(optionIdPrefix + "_month").value);
            const year = parseInt(document.getElementById(optionIdPrefix + "_year").value);
            const dayEl = document.getElementById(optionIdPrefix + "_day");
            const days = this.getDaysInMonth(month, year);

            //remove days
            for (let i = dayEl.options.length - 1; i >= 0; i--) {
                if (dayEl.options[i].value > days) {
                    dayEl.remove(i);
                }
            }

            // add days
            const lastDay = parseInt(dayEl.options[dayEl.options.length-1].value);
            for (let i = lastDay + 1; i <= days; i++) {
                this.addOption(dayEl, i, i);
            }
        }

        addOption(select, text, value) {
            const option = document.createElement('OPTION');
            option.value = value;
            option.text = text;
            select.appendChild(option);
        }
    }

    const dateOption = new DateOption();
</script>
