document.addEventListener('DOMContentLoaded', function() {
let usersData = []; // To store user data for CSV export
const userTableContainer = document.getElementById('user-table-container');
const authLinks = document.getElementById('auth-links');
const downloadBtn = document.getElementById('download-users-csv');
// --- Auth Logic (for header consistency) ---
const updateAuthUI = (user) => {
if (user) {
let adminLink = user.role === 'admin' ? 'Admin' : '';
authLinks.innerHTML = `
${adminLink}
Welcome, ${user.username}
`;
document.getElementById('logout-btn').addEventListener('click', logout);
} else {
authLinks.innerHTML = `
Login
Register
`;
}
};
const logout = () => {
fetch('/api/logout.php').then(() => window.location.href = '/');
};
const checkSession = () => {
fetch('/api/check_session.php')
.then(response => response.json())
.then(data => {
updateAuthUI(data.loggedIn ? data.user : null);
});
};
// --- User Management Logic ---
const renderUserTable = (users) => {
const roles = ['regular', 'sports_analyst', 'sports_bettor', 'admin'];
let tableHtml = `
| ID |
Username |
Email |
Role |
Joined |
Action |
`;
users.forEach(user => {
tableHtml += `
| ${user.id} |
${user.username} |
${user.email} |
|
${new Date(user.created_at).toLocaleDateString()} |
|
`;
});
tableHtml += '
';
userTableContainer.innerHTML = tableHtml;
document.querySelectorAll('.save-role-btn').forEach(button => {
button.addEventListener('click', function() {
const userId = this.dataset.userId;
const roleSelector = document.querySelector(`select[data-user-id="${userId}"]`);
const newRole = roleSelector.value;
updateUserRole(userId, newRole);
});
});
};
const updateUserRole = (userId, role) => {
fetch('/api/update_user_role.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: userId, role: role })
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
alert('User role updated!');
} else {
alert(`Error: ${data.message}`);
}
});
};
const loadUsers = () => {
fetch('/api/get_users.php')
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
usersData = data.users; // Store for CSV export
renderUserTable(usersData);
} else {
userTableContainer.innerHTML = `${data.message}
`;
}
});
};
// --- Event Listeners ---
if (downloadBtn) {
downloadBtn.addEventListener('click', () => {
exportToCsv('stattracker_users.csv', usersData);
});
}
// --- Initial Load ---
checkSession();
loadUsers();
});