// Modal functions
function showModal(modalId) {
    document.getElementById(modalId).classList.add('show');
}

function closeModal(modalId) {
    document.getElementById(modalId).classList.remove('show');
}

function showAddUserModal() {
    document.getElementById('addUserForm').reset();
    showModal('addUserModal');
}

// Close modal when clicking outside
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.classList.remove('show');
    }
}

// Add user form
document.getElementById('addUserForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'add_user');
    
    try {
        const response = await fetch('api/users.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('User added successfully!');
            closeModal('addUserModal');
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    } catch (error) {
        alert('Failed to add user. Please try again.');
        console.error(error);
    }
});

// Edit user
async function editUser(userId) {
    try {
        const formData = new FormData();
        formData.append('action', 'get_user');
        formData.append('user_id', userId);
        
        const response = await fetch('api/users.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            document.getElementById('edit_user_id').value = data.user.id;
            document.getElementById('edit_name').value = data.user.user_name || '';
            document.getElementById('edit_email').value = data.user.email;
            document.getElementById('edit_level').value = data.user.user_level || 'registered';
            document.getElementById('edit_verified').checked = data.user.is_verified == 1;
            
            showModal('editUserModal');
        } else {
            alert('Error: ' + data.message);
        }
    } catch (error) {
        alert('Failed to load user data. Please try again.');
        console.error(error);
    }
}

// Edit user form
document.getElementById('editUserForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'update_user');
    formData.set('email_verified', document.getElementById('edit_verified').checked);
    
    try {
        const response = await fetch('api/users.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('User updated successfully!');
            closeModal('editUserModal');
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    } catch (error) {
        alert('Failed to update user. Please try again.');
        console.error(error);
    }
});

// Delete user
async function deleteUser(userId) {
    if (!confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
        return;
    }
    
    try {
        const formData = new FormData();
        formData.append('action', 'delete_user');
        formData.append('user_id', userId);
        
        const response = await fetch('api/users.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('User deleted successfully!');
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    } catch (error) {
        alert('Failed to delete user. Please try again.');
        console.error(error);
    }
}

// Auto-hide alerts
document.querySelectorAll('.alert').forEach(function(alert) {
    setTimeout(function() {
        alert.style.opacity = '0';
        setTimeout(function() {
            alert.remove();
        }, 300);
    }, 5000);
});
