document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('uploadModal');
    const openButton = document.getElementById('createButton');
    const closeButton = modal.querySelector('.close');
    const submitButton = document.getElementById('submitBtn');

    // Open the modal
    openButton.addEventListener('click', function() {
        modal.style.display = 'block';
    });

    // Close the modal
    closeButton.addEventListener('click', function() {
        modal.style.display = 'none';
    });

    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    });

    // Handle form submission
    submitButton.addEventListener('click', function(event) {
        event.preventDefault();  // Prevent default form submission

        const form = document.getElementById('uploadForm');
        const formData = new FormData(form);

        fetch(form.action, {
            method: 'POST',
            body: formData
        })

        .then(response => response.json())
        .then(data => {
            const messageDiv = document.getElementById('message');
            let message = '';
            if (data.status === 'error') {
                message = `<div class="popup error">${data.message}</div>`;
            } else if (data.status === 'success') {
                message = `Users successfully created: ${data.successCount}<br>`;
                message += `Existing users (PIDs): ${data.existingCount}`;
                if (data.csvFile) {
                    message += `<br><a href="downloads/${data.csvFile}" download>Download existing users list</a>`;
                }
                message = `<div class="popup success">${message}</div>`;
                setTimeout(() => {
                    window.location.href = 'userlist.php';
                }, 3000);
            }
            messageDiv.innerHTML = message;
        })
        .catch(error => {
            const messageDiv = document.getElementById('message');
            messageDiv.innerHTML = `<div class="popup error">An error occurred: ${error.message}</div>`;
        });
    });
});
