// DigiMobiz Application JavaScript
// Supplement to main.js

$(document).ready(function() {
    // Initialize all Select2 dropdowns
    $('.select2').each(function() {
        if (!$(this).data('select2')) {
            $(this).select2({
                theme: 'bootstrap-5',
                width: '100%',
                dropdownParent: $(this).closest('.modal') || $(document.body)
            });
        }
    });

    // Re-initialize Select2 inside modals when shown
    $('.modal').on('shown.bs.modal', function() {
        $(this).find('.select2').each(function() {
            if (!$(this).data('select2')) {
                $(this).select2({
                    theme: 'bootstrap-5',
                    width: '100%',
                    dropdownParent: $(this).closest('.modal')
                });
            }
        });
    });

    // Form validation enhancement
    $(document).on('submit', 'form[data-validate]', function(e) {
        var valid = true;
        $(this).find('[required]').each(function() {
            if (!$(this).val()) {
                $(this).addClass('is-invalid');
                valid = false;
            } else {
                $(this).removeClass('is-invalid');
            }
        });
        if (!valid) {
            e.preventDefault();
            toastr?.error?.('Please fill all required fields.') || alert('Please fill all required fields.');
        }
    });

    // Number input formatting (allow only digits and decimals)
    $(document).on('input', 'input[type="number"]', function() {
        var val = $(this).val();
        if (val && !/^\d*\.?\d{0,2}$/.test(val)) {
            $(this).val(val.slice(0, -1));
        }
    });

    // Print handler
    $(document).on('click', '.btn-print', function(e) {
        e.preventDefault();
        window.print();
    });

    // Go back handler
    $(document).on('click', '.btn-back', function(e) {
        e.preventDefault();
        history.back();
    });
});
