<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>

	// =====================================================
	// 🔥 FORMAT NUMBER
	// contoh:
	// 1000       => 1,000
	// 1000.5     => 1,000.5
	// 1000.55    => 1,000.55
	// =====================================================

	function formatNumber(value){

	    if(value === null || value === undefined){
	        return '';
	    }

	    value = value.toString();

	    // hanya angka dan titik
	    value = value.replace(/[^0-9.]/g, '');

	    // hanya boleh 1 titik
	    let parts = value.split('.');

	    let integerPart = parts[0] || '';
	    let decimalPart = parts[1] || '';

	    // format ribuan pakai koma
	    integerPart = integerPart.replace(/,/g, '');
	    integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

	    // max 2 digit decimal
	    decimalPart = decimalPart.substring(0,2);

	    // kalau ada desimal
	    if(parts.length > 1 || value.endsWith('.')){
	        return integerPart + '.' + decimalPart;
	    }

	    return integerPart;
	}

	// =====================================================
	// 🔥 CLEAN NUMBER
	// hasil:
	// 1,000.25 => 1000.25
	// =====================================================

	function cleanNumber(value){

	    if(!value) return '';

	    return value.toString().replace(/,/g, '');

	}

	// =====================================================
	// 🔥 AUTO FORMAT INPUT
	// =====================================================

	$(document).on('input', '.format-rupiah', function(){

	    let cursorPos = this.selectionStart;

	    let beforeLength = $(this).val().length;

	    let formatted = formatNumber($(this).val());

	    $(this).val(formatted);

	    let afterLength = formatted.length;

	    cursorPos = cursorPos + (afterLength - beforeLength);

	    this.setSelectionRange(cursorPos, cursorPos);

	});

	// =====================================================
	// 🔥 FORMAT SAAT BLUR
	// =====================================================

	$(document).on('blur', '.format-rupiah', function(){

	    $(this).val(
	        formatNumber($(this).val())
	    );

	});

	// =====================================================
	// 🔥 AUTO CLEAN SAAT SUBMIT
	// =====================================================

	$(document).on('submit', 'form', function(){

	    $(this).find('.format-rupiah').each(function(){

	        $(this).val(
	            cleanNumber($(this).val())
	        );

	    });

	});

	// =====================================================
	// 🔥 AUTO FORMAT VALUE AWAL
	// =====================================================

	$(document).ready(function(){

	    $('.format-rupiah').each(function(){

	        let val = $(this).val();

	        if(val !== ''){

	            $(this).val(
	                formatNumber(val)
	            );

	        }

	    });

	});

	// =====================================================
	// 🔥 OVERRIDE jQuery .val()
	// =====================================================

	(function($){

	    const originalVal = $.fn.val;

	    $.fn.val = function(value){

	        // setter
	        if(typeof value !== 'undefined'){

	            if(this.hasClass('format-rupiah')){

	                return originalVal.call(
	                    this,
	                    formatNumber(value)
	                );

	            }

	            return originalVal.apply(this, arguments);
	        }

	        // getter
	        if(this.hasClass('format-rupiah')){

	            return cleanNumber(
	                originalVal.call(this)
	            );

	        }

	        return originalVal.call(this);
	    };

	})(jQuery);

</script>

<script>

	function formatRupiah(num){
	    return 'Rp ' + new Intl.NumberFormat('id-ID').format(num || 0);
	}

	function formatTglIndo(dateString){

	    if(!dateString) return '-';

	    let date = new Date(dateString);

	    const bulan = [
	        "Januari","Februari","Maret","April","Mei","Juni",
	        "Juli","Agustus","September","Oktober","November","Desember"
	    ];

	    let tgl = date.getDate();
	    let bln = bulan[date.getMonth()];
	    let thn = date.getFullYear();

	    return `${tgl} ${bln} ${thn}`;
	}
</script>

<script>
	
$(function(){

    function initSelectSearch(scope = document){
    
        if (typeof $.fn.select2 === 'undefined') {
            console.error('Select2 belum ke-load!');
            return;
        }
    
        $(scope).find('select.select-search').each(function(){
    
            let $this = $(this);
    
            if ($this.hasClass("select2-hidden-accessible")) return;
    
            let parent = $this.closest('.modal');
            parent = parent.length ? parent : $(document.body);
    
            $this.select2({
                width: '100%',
                placeholder: $this.attr('placeholder') || '-- Pilih --',
                allowClear: true,
                dropdownParent: parent
            });
    
        });
    }

    // ✅ INIT AWAL
    initSelectSearch();
    
    // $(window).on('load', function(){
    //     setTimeout(() => {
    //         initSelectSearch();
    //     }, 100);
    // });

    // ✅ AUTO INIT untuk dynamic content (modal, ajax, dll)
    const observer = new MutationObserver(function(mutations){

        mutations.forEach(function(mutation){

            mutation.addedNodes.forEach(function(node){

                if (node.nodeType === 1){ // element
                    initSelectSearch(node);
                }

            });

        });

    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

});
</script>
</body>
</html>
