const initializedElements = new Set();

function openModal(modalId, inputId) {
        // Remove any previous backdrops or modal-open class that may remain
        document.querySelectorAll('.modal-backdrop').forEach(backdrop => backdrop.remove());
        document.body.classList.remove('modal-open');

        const modalElement = document.getElementById(modalId);
        const inputElement = document.getElementById(inputId);

        const modal = new bootstrap.Modal(modalElement);
        modal.show();

        modalElement.addEventListener('shown.bs.modal', function () {
                inputElement?.focus();
        });

        // Ensure that closing the modal clears any backdrop or classes
        modalElement.addEventListener('hidden.bs.modal', function () {
                document.querySelectorAll('.modal-backdrop').forEach(backdrop => backdrop.remove());
                document.body.classList.remove('modal-open');
        }, { once: true });
}

function addClickListener(button, modalId, inputId) {
	if (!initializedElements.has('modalId')) {
		button.addEventListener("click", function () {
			openModal(modalId, inputId);
		});
		initializedElements.add('modalId');
	}
}

function bootstrap4To5() {

    document.querySelectorAll('[data-target]').forEach(function (element) {
        element.setAttribute('data-bs-target', element.getAttribute('data-target'));
        element.removeAttribute('data-target');
    });

    document.querySelectorAll('[data-toggle]').forEach(function (element) {
        element.setAttribute('data-bs-toggle', element.getAttribute('data-toggle'));
        element.removeAttribute('data-toggle');
    });

    document.querySelectorAll('[data-dismiss]').forEach(function (element) {
        element.setAttribute('data-bs-dismiss', element.getAttribute('data-dismiss'));
        element.removeAttribute('data-dismiss');
    });

    document.querySelectorAll('[data-spy]').forEach(function (element) {
        element.setAttribute('data-bs-spy', element.getAttribute('data-spy'));
        element.removeAttribute('data-spy');
    });

    document.querySelectorAll('[data-offset]').forEach(function (element) {
        element.setAttribute('data-bs-offset', element.getAttribute('data-offset'));
        element.removeAttribute('data-offset');
    });

    document.querySelectorAll('[data-ride]').forEach(function (element) {
        element.setAttribute('data-bs-ride', element.getAttribute('data-ride'));
        element.removeAttribute('data-ride');
    });

    document.querySelectorAll('[data-parent]').forEach(function (element) {
        element.setAttribute('data-bs-parent', element.getAttribute('data-parent'));
        element.removeAttribute('data-parent');
    });

    const classMap = {
        'form-inline': '',
        'custom-control': 'form-check',
        'custom-checkbox': 'form-check',
        'custom-radio': 'form-check',
        'custom-select': 'form-select',
        'custom-file': 'form-control',
        'custom-range': 'form-range',
        'card-deck': 'row row-cols-1 row-cols-md-2',
        'card-group': 'row',
        'card-columns': 'row row-cols-1',
        'float-left': 'float-start',
        'float-right': 'float-end',
        'text-left': 'text-start',
        'text-right': 'text-end',
        'ml-auto': 'ms-auto',
        'mr-auto': 'me-auto',
        'pl-': 'ps-',
        'pr-': 'pe-',
        'ml-': 'ms-',
        'mr-': 'me-',
        'left': 'start',
        'right': 'end'
    };

    Object.keys(classMap).forEach(oldClass => {
        const newClass = classMap[oldClass];
        document.querySelectorAll(`.${oldClass}`).forEach(element => {
            element.classList.remove(oldClass);
            if (newClass) {
                element.classList.add(newClass);
            }
        });
    });


    const button = document.querySelector('.btn-info[onclick]');

    if (button) {

        button.addEventListener('click', function (event) {
            event.preventDefault();

            const modalElement = document.getElementById('findProductModal');
            const inputElement = document.getElementById('productModalInput');

            if (modalElement) {
							button.removeAttribute('onclick');
                const modal = new bootstrap.Modal(modalElement);
                modal.show();

                modalElement.addEventListener('shown.bs.modal', function () {
                    if (inputElement) {
                        inputElement.select();
                    }
                });
            } else {
            }
        });

    } else {
    }

	document.querySelectorAll('button[onclick]').forEach(button => {
		let onclickValue = button.getAttribute('onclick');

		if (onclickValue.includes("$('#findCustomerModal').modal(); $('#findCustomerInput').focus(); return false;")) {
			button.removeAttribute('onclick');
			button.addEventListener('click', () => {
				const modal = new bootstrap.Modal(document.getElementById('findCustomerModal'));
				modal.show();
			});
		}
	});





    const btnFindSupplier = document.getElementById("btnFindSupplierModal");
    const btnFindCustomer = document.getElementById("btnFindCustomerModal");

		if(btnFindSupplier){
    	addClickListener(btnFindSupplier, "findSupplierModal", "findSupplierInput");
		}
		if(btnFindCustomer){
    	addClickListener(btnFindCustomer, "findCustomerModal", "findCustomerInput");
		}


}


document.addEventListener('DOMContentLoaded', bootstrap4To5);


$(document).ready(function () {

	if (
		document.forms['salesForm'] && 
		document.forms['salesForm']['codcliente'] && 
		document.forms['salesForm']['codcliente'].value === ''
	) {
		const findCustomerModal = new bootstrap.Modal(document.getElementById('findCustomerModal'));
		findCustomerModal.show();
	}

	if (
		document.forms['purchasesForm'] && 
		document.forms['purchasesForm']['codproveedor'] && 
		document.forms['purchasesForm']['codproveedor'].value === ''
	) {
		const findSupplierModal = new bootstrap.Modal(document.getElementById('findSupplierModal'));
		findSupplierModal.show();
	}


	if ($("#salesFormLines").length > 0) {
		$("#salesFormLines").find(".col-lg").each(function() {
			$(this).removeClass("col-lg").addClass("col-lg-3");
		});
		$("#salesFormLines").find("[class*='col-sm-10'][class*='col-md-12']").each(function() {
			$(this).removeClass("col-md-12").addClass("col-sm-10");
		});
	}

});
