$(document).ready(function () {
    $('#uorgmodal').on('shown.bs.modal', function () {
        const udealerSelect = document.getElementById("udealerid");

        if (udealerSelect) {
            udealerSelect.dataset.previousIndex = udealerSelect.selectedIndex;

            udealerSelect.removeEventListener("change", handleDealerChange);
            udealerSelect.addEventListener("change", handleDealerChange);
        }
    });

    $('#upropmodal').on('shown.bs.modal', function () {
        const uorgSelect = document.getElementById("uorganization_id");

        if (uorgSelect) {
            uorgSelect.dataset.previousIndex = uorgSelect.selectedIndex;

            uorgSelect.removeEventListener("change", handleOrgChange);
            uorgSelect.addEventListener("change", handleOrgChange);
        }
    });

    function handleDealerChange(event) {
        const udealerSelect = event.target;
        const selectedText = udealerSelect.options[udealerSelect.selectedIndex].text;
        const modal = $('#uorgmodal');

        modal.modal('hide');

        showConfirmModal(
            `Are you sure you want to re-assign this organization to ${selectedText}?`,
            function () {
                const submitButton = document.getElementById("uupdateOrg");
                if (submitButton) {
                    submitButton.click();
                } else {
                    console.error("Error: Submit button for dealer not found.");
                }
            },
            function () {
                udealerSelect.selectedIndex = udealerSelect.dataset.previousIndex;
                modal.modal('show');
            }
        );
    }

    function handleOrgChange(event) {
        const uorgSelect = event.target;
        const selectedText = uorgSelect.options[uorgSelect.selectedIndex].text;
        const modal = $('#upropmodal');

        modal.modal('hide');

        showConfirmModal(
            `Are you sure you want to re-assign this organization to ${selectedText}?`,
            function () {
                const submitButton = document.getElementById("updateprop");
                if (submitButton) {
                    submitButton.click();
                } else {
                    console.error("Error: Submit button for property not found.");
                }
            },
            function () {
                uorgSelect.selectedIndex = uorgSelect.dataset.previousIndex;
                modal.modal('show');
            }
        );
    }
});
















