document.addEventListener('DOMContentLoaded', function() {
    const table = document.getElementById('user_table');
    const form = document.getElementById('pid_form');
    const pidInput = document.getElementById('pid_input');
    const popup = document.getElementById("popup");
    const popupMessage = document.getElementById("popup-message");
    const confirmButton = document.getElementById("confirm-button");
    const cancelButton = document.getElementById("cancel-button");
    let currentPid = null;

    table.addEventListener('click', function(event) {
        const target = event.target;
        if (target.classList.contains('btn_delete')) {
            // Handle delete button click
            currentPid = target.getAttribute('data-pid');
            if (currentPid) {
                popupMessage.textContent = "Do you really want to delete the user: " + currentPid + "?";
                popup.style.display = "block";
            }
            event.stopPropagation();
        } 
        else if (target.classList.contains('btn_modify')) {
            // Handle modify button click
            const pid = target.getAttribute('data-pid');
            if (pid) {
                pidInput.value = pid;
                form.action = '../configuration/role_edit.php';
                form.submit();
            }
        } 
        else {
            // Handle row click
            const row = target.closest('tr');
            if (row) {
                const pid = row.getAttribute('data-pid');
                if (pid) {
                    pidInput.value = pid;
                    form.submit();
                }
            }
        }
    });

    confirmButton.addEventListener('click', function() {
        const deleteForm = document.createElement('form');
        deleteForm.action = '../configuration/role_delete.php';
        deleteForm.method = 'POST';

        const pidInputField = document.createElement('input');
        pidInputField.type = 'hidden';
        pidInputField.name = 'id';
        pidInputField.value = currentPid;
        deleteForm.appendChild(pidInputField);

        document.body.appendChild(deleteForm);
        deleteForm.submit();
        popup.style.display = "none";
    });

    cancelButton.addEventListener('click', function() {
        popup.style.display = "none";
    });

    // Close popup when clicking outside of it
    window.addEventListener('click', function(event) {
        if (event.target == popup) {
            popup.style.display = "none";
        }
    });

});
