console.log('options.js file loaded - i starten.');

// Function to fetch all user data and populate the users tab
async function fetchAndPopulateUserData() {
    try {
        // Fetch all user data from the Excel file
        const allUserData = await fetchAllUserDataFromExcel();

        // Populate the users tab with the fetched data
        populateUsersTab(allUserData);
        
        // Call addCellResizeListeners after populating the table
        addCellResizeListeners();
    } catch (error) {
        console.error('Error fetching and populating user data:', error);
    }
}

// Function to handle tab switching
function openTab(event, tabName) {
    var i, tabcontent, tablinks;

    // Hide all elements with class="tabcontent" by setting display to none
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    // Remove "active" class from all elements with class="tablinks"
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Show the current tab, and add an "active" class to the button that opened the tab
    document.getElementById(tabName).style.display = "block";
    event.currentTarget.className += " active";

    // Check if the "Users" tab is clicked
    if (tabName === "Users") {
        // Call a function to fetch all user data and populate the users tab
        fetchAndPopulateUserData();
    }
}

// Close modal by clicking on X
document.querySelector('.close').addEventListener('click', function() {
    document.getElementById('optionsModal').style.display = "none";
});

// Optional: Close the modal if the user clicks outside of it
window.onclick = function(event) {
    if (event.target == document.getElementById('optionsModal')) {
        document.getElementById('optionsModal').style.display = "none";
    }
};

console.log('options.js file loaded - this point is just before resize funtion.');

// Resize Table CODE
window.addCellResizeListeners = function() {
    console.log('addCellResizeListeners() function called lige efter definition.'); // Add this line

    const overlays = document.querySelectorAll('.resize-overlay');

    overlays.forEach(overlay => {
        let startX, startY, startWidth, startHeight;

        overlay.addEventListener('mousedown', function(event) {
            startX = event.clientX;
            startY = event.clientY;
            startWidth = overlay.parentElement.offsetWidth;
            startHeight = overlay.parentElement.offsetHeight;

            document.documentElement.addEventListener('mousemove', mouseMoveHandler);
            document.documentElement.addEventListener('mouseup', mouseUpHandler);
        });

        const mouseMoveHandler = function(event) {
            const deltaX = event.clientX - startX;
            const deltaY = event.clientY - startY;
            overlay.parentElement.style.width = startWidth + deltaX + 'px';
            overlay.parentElement.style.height = startHeight + deltaY + 'px';
        };

        const mouseUpHandler = function() {
            document.documentElement.removeEventListener('mousemove', mouseMoveHandler);
            document.documentElement.removeEventListener('mouseup', mouseUpHandler);
        };
    });
};

// Function to fetch all user data from the Excel file
async function fetchAllUserDataFromExcel() {
    try {
        // Fetch the Excel file from the server
        const response = await fetch('USER_DATABASE.xlsx');
        if (!response.ok) {
            console.error('Failed to fetch USER_DATABASE.xlsx');
            return null;
        }
         
        const arrayBuffer = await response.arrayBuffer();
        const data = new Uint8Array(arrayBuffer);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);

        // Log the fetched data
        console.log('Fetched all user data from Excel:', jsonData);

        return jsonData;
    } catch (error) {
        console.error("Error fetching or reading Excel data:", error);
        return null;
    }
}

// Function to populate the user table with data
function populateUsersTab(userData) {
    var tableBody = document.getElementById("usersTableBody");
    tableBody.innerHTML = ""; // Clear existing table rows

    userData.forEach(function(user) {
        var row = tableBody.insertRow();

        // Populate table cells with user data
        Object.values(user).forEach(function(value) {
            var cell = row.insertCell();
            cell.textContent = value;
        });

        // Add "Edit" button to each row
        var editCell = row.insertCell();
        var editButton = document.createElement("button");
        editButton.textContent = "Edit 3";
        editButton.onclick = function() {
            openEditUserModal(row); // Pass the user data to the edit modal
        };
        editCell.appendChild(editButton);
    });
}

// Function to update the modal content with user data
async function updateUserModal(username) {
    try {
        // Fetch user data based on the provided username
        const userData = await fetchUserData(username);

        // If user data exists, update the modal content
        if (userData) {
            // Update modal content with user data
            document.getElementById('usernameDisplay').innerText = userData['USER DATABASE'];
            document.getElementById('realnameDisplay').innerText = userData['__EMPTY'];

            // Get the usersTableBody element
            const usersTableBody = document.getElementById('usersTableBody');

            // Clear any existing content
            usersTableBody.innerHTML = '';

            // Loop through user data and populate table rows
            for (const key in userData) {
                if (userData.hasOwnProperty(key)) {
                    const value = userData[key];
                    // Create a new row
                    const newRow = document.createElement('tr');
                    // Create cells for each data item
                    const nameCell = document.createElement('td');
                    nameCell.textContent = value['Name'];
                    newRow.appendChild(nameCell);

                    // Repeat this process for other data fields (Navn, Email, etc.)

                    // Append the new row to the table body
                    usersTableBody.appendChild(newRow);
                }
            }

            // Log the updated modal content
            console.log('Updated modal content with user data:', userData);
        } else {
            console.error('No user data found for username:', username);
        }
    } catch (error) {
        console.error('Error updating modal content:', error);
    }
}


//************Function to handle editing and saving user data***************
//************Function to handle editing and saving user data***************
// Function to open the edit user modal
function openEditUserModal(row) {
    // Get all cells in the row
    var cells = row.getElementsByTagName('td');

    // Loop through each cell
    for (var i = 0; i < cells.length - 1; i++) {
        // Create an input field
        var input = document.createElement('input');
        input.value = cells[i].textContent; // Set input value to cell content
        cells[i].innerHTML = ''; // Clear cell content
        cells[i].appendChild(input); // Append input field to cell
    }

    // Change the button text to "Save"
    var editButton = row.querySelector('button');
    editButton.textContent = 'Save';
    editButton.onclick = function() {
        saveUser(row); // Call function to save user data
    };
}

// Function to save user data
function saveUser(row) {
    var cells = row.getElementsByTagName('td');

    // Loop through each cell
    for (var i = 0; i < cells.length - 1; i++) {
        // Set cell content to input value
        cells[i].textContent = cells[i].querySelector('input').value;
    }

    // Change the button text back to "Edit"
    var editButton = row.querySelector('button');
    editButton.textContent = 'Edit';
    editButton.onclick = function() {
        openEditUserModal(row); // Call function to open edit modal again
    };

    // Call function to update user data in the database
    saveUserToDatabase(cells);
}

// Function to save user data to the database
function saveUserToDatabase(userData) {
    // Send a POST request to the server to update the database
    fetch('/update-user', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
    .then(response => {
        if (response.ok) {
            console.log('User data updated successfully.');
        } else {
            console.error('Failed to update user data.');
        }
    })
    .catch(error => {
        console.error('Error updating user data:', error);
    });
}






// Function to test server connection
function testServerConnection() {
    fetch('options.php')
    .then(response => {
        if (response.ok) {
            return response.text();
        } else {
            throw new Error('Server responded with error status.');
        }
    })
    .then(data => {
        console.log('Server response:', data);
    })
    .catch(error => {
        console.error('Error testing server connection:', error);
    });
}

// Call the function to test server connection
testServerConnection();
