Actualiser js/admin.js
This commit is contained in:
+106
-135
@@ -1,15 +1,37 @@
|
||||
// Vérification admin
|
||||
const API_BASE_URL = 'https://monpetitpari.fr/api';
|
||||
|
||||
async function apiCall(endpoint, method = 'GET', data = null) {
|
||||
const options = {
|
||||
method: method,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
};
|
||||
|
||||
const token = localStorage.getItem('authToken');
|
||||
if (token) options.headers['Authorization'] = `Bearer ${token}`;
|
||||
|
||||
if (data && (method === 'POST' || method === 'PUT')) {
|
||||
options.body = JSON.stringify(data);
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/${endpoint}`, options);
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error || 'Erreur serveur');
|
||||
return result;
|
||||
}
|
||||
|
||||
window.onload = function() {
|
||||
const user = JSON.parse(localStorage.getItem('currentUser'));
|
||||
if (!user || user.role !== 'admin') {
|
||||
window.location.href = 'index.html';
|
||||
return;
|
||||
}
|
||||
document.getElementById('adminName').textContent = user.username;
|
||||
loadAdminData();
|
||||
loadAdminStats();
|
||||
};
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem('currentUser');
|
||||
localStorage.removeItem('authToken');
|
||||
window.location.href = 'index.html';
|
||||
}
|
||||
|
||||
@@ -24,42 +46,40 @@ function showAdminSection(sectionId) {
|
||||
if (sectionId === 'results') loadResultsDropdown();
|
||||
}
|
||||
|
||||
function loadAdminData() {
|
||||
document.getElementById('totalMatches').textContent = tournamentMatches.length;
|
||||
document.getElementById('totalPlayers').textContent = Object.keys(playersData).length;
|
||||
document.getElementById('totalUsers').textContent = typeof users !== 'undefined' ? users.length : 0;
|
||||
async function loadAdminStats() {
|
||||
try {
|
||||
const users = await apiCall('users.php');
|
||||
const matches = await apiCall('matches.php');
|
||||
const players = await apiCall('players.php');
|
||||
|
||||
const allPredictions = JSON.parse(localStorage.getItem('userPredictions') || '[]');
|
||||
document.getElementById('totalPredictions').textContent = allPredictions.length;
|
||||
document.getElementById('totalUsers').textContent = users.users ? users.users.length : 0;
|
||||
document.getElementById('totalMatches').textContent = matches.matches ? matches.matches.length : 0;
|
||||
document.getElementById('totalPlayers').textContent = players.players ? players.players.length : 0;
|
||||
|
||||
// Populate player selects
|
||||
const playerSelects = ['matchPlayer1', 'matchPlayer2'];
|
||||
playerSelects.forEach(selectId => {
|
||||
const select = document.getElementById(selectId);
|
||||
select.innerHTML = '';
|
||||
Object.values(playersData).forEach(player => {
|
||||
const option = document.createElement('option');
|
||||
option.value = player.id;
|
||||
option.textContent = player.name;
|
||||
select.appendChild(option);
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur stats admin', error);
|
||||
}
|
||||
}
|
||||
|
||||
function loadMatchesTable() {
|
||||
async function loadMatchesTable() {
|
||||
try {
|
||||
const result = await apiCall('matches.php');
|
||||
const tbody = document.getElementById('matchesTable');
|
||||
if(!tbody) return;
|
||||
tbody.innerHTML = '';
|
||||
|
||||
tournamentMatches.forEach(match => {
|
||||
const p1 = playersData[match.player1];
|
||||
const p2 = playersData[match.player2];
|
||||
|
||||
if(result.matches) {
|
||||
result.matches.forEach(match => {
|
||||
const row = document.createElement('tr');
|
||||
// Gestion de l'affichage selon le format retourné par getAllMatches()
|
||||
const p1Name = match.p1_name || (match.player1 && match.player1.name) || 'Inconnu';
|
||||
const p2Name = match.p2_name || (match.player2 && match.player2.name) || 'Inconnu';
|
||||
|
||||
row.innerHTML = `
|
||||
<td>${match.round}</td>
|
||||
<td>${p1.name}</td>
|
||||
<td>${p2.name}</td>
|
||||
<td>${new Date(match.date).toLocaleDateString('fr-FR')}</td>
|
||||
<td>${p1Name}</td>
|
||||
<td>${p2Name}</td>
|
||||
<td>${new Date(match.match_date || match.date).toLocaleDateString('fr-FR')}</td>
|
||||
<td>${match.status === 'completed' ? 'Terminé' : 'À venir'}</td>
|
||||
<td>
|
||||
<button class="btn-danger" onclick="deleteMatch(${match.id})">Supprimer</button>
|
||||
@@ -68,12 +88,18 @@ function loadMatchesTable() {
|
||||
tbody.appendChild(row);
|
||||
});
|
||||
}
|
||||
} catch(e) { console.error(e); }
|
||||
}
|
||||
|
||||
function loadUsersTable() {
|
||||
async function loadUsersTable() {
|
||||
try {
|
||||
const result = await apiCall('users.php');
|
||||
const tbody = document.getElementById('usersTable');
|
||||
if(!tbody) return;
|
||||
tbody.innerHTML = '';
|
||||
|
||||
users.forEach(user => {
|
||||
if(result.users) {
|
||||
result.users.forEach(user => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${user.id}</td>
|
||||
@@ -88,143 +114,88 @@ function loadUsersTable() {
|
||||
tbody.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
function addMatch() {
|
||||
const newMatch = {
|
||||
id: Date.now(),
|
||||
round: document.getElementById('matchRound').value,
|
||||
player1: document.getElementById('matchPlayer1').value,
|
||||
player2: document.getElementById('matchPlayer2').value,
|
||||
date: document.getElementById('matchDate').value,
|
||||
court: document.getElementById('matchCourt').value,
|
||||
status: 'upcoming'
|
||||
};
|
||||
|
||||
tournamentMatches.push(newMatch);
|
||||
alert('Match ajouté avec succès!');
|
||||
loadAdminData();
|
||||
loadMatchesTable();
|
||||
} catch(e) { console.error(e); }
|
||||
}
|
||||
|
||||
function deleteMatch(id) {
|
||||
if (confirm('Êtes-vous sûr de vouloir supprimer ce match?')) {
|
||||
const index = tournamentMatches.findIndex(m => m.id === id);
|
||||
if (index > -1) {
|
||||
tournamentMatches.splice(index, 1);
|
||||
loadMatchesTable();
|
||||
loadAdminData();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addPlayer() {
|
||||
const newPlayer = {
|
||||
id: document.getElementById('playerName').value.toLowerCase().replace(' ', ''),
|
||||
name: document.getElementById('playerName').value,
|
||||
nationality: document.getElementById('playerNationality').value,
|
||||
age: parseInt(document.getElementById('playerAge').value),
|
||||
handedness: document.getElementById('playerHandedness').value,
|
||||
ranking: parseInt(document.getElementById('playerRanking').value),
|
||||
photo: 'https://www.atptour.com/-/media/tennis/players/head-shot/2024/default.png',
|
||||
strengths: ['Nouveau joueur'],
|
||||
weaknesses: ['À définir'],
|
||||
surfaceStats: {
|
||||
clay: { winRate: 0.5, titles: 0 },
|
||||
hard: { winRate: 0.5, titles: 0 },
|
||||
grass: { winRate: 0.5, titles: 0 }
|
||||
},
|
||||
recentForm: ['W', 'L', 'W', 'L', 'W']
|
||||
};
|
||||
|
||||
playersData[newPlayer.id] = newPlayer;
|
||||
alert('Joueur ajouté avec succès!');
|
||||
loadAdminData();
|
||||
}
|
||||
|
||||
function deleteUser(id) {
|
||||
async function deleteUser(id) {
|
||||
if (confirm('Êtes-vous sûr de vouloir supprimer cet utilisateur ?')) {
|
||||
const index = users.findIndex(u => u.id === id);
|
||||
if (index > -1) {
|
||||
users.splice(index, 1);
|
||||
localStorage.setItem('users', JSON.stringify(users));
|
||||
try {
|
||||
await apiCall(`users.php?id=${id}`, 'DELETE');
|
||||
loadUsersTable();
|
||||
loadAdminData();
|
||||
}
|
||||
loadAdminStats();
|
||||
} catch(e) { alert(e.message); }
|
||||
}
|
||||
}
|
||||
|
||||
function loadResultsDropdown() {
|
||||
async function deleteMatch(id) {
|
||||
if (confirm('Êtes-vous sûr de vouloir supprimer ce match ?')) {
|
||||
try {
|
||||
await apiCall(`matches.php?id=${id}`, 'DELETE');
|
||||
loadMatchesTable();
|
||||
loadAdminStats();
|
||||
} catch(e) { alert(e.message); }
|
||||
}
|
||||
}
|
||||
|
||||
async function loadResultsDropdown() {
|
||||
try {
|
||||
const result = await apiCall('matches.php');
|
||||
const select = document.getElementById('resultMatch');
|
||||
if(!select) return;
|
||||
select.innerHTML = '';
|
||||
|
||||
tournamentMatches.filter(m => m.status === 'upcoming').forEach(match => {
|
||||
const p1 = playersData[match.player1];
|
||||
const p2 = playersData[match.player2];
|
||||
window.currentAdminMatches = result.matches || [];
|
||||
|
||||
window.currentAdminMatches.filter(m => m.status !== 'completed').forEach(match => {
|
||||
const option = document.createElement('option');
|
||||
option.value = match.id;
|
||||
option.textContent = `${match.round}: ${p1.name} vs ${p2.name}`;
|
||||
option.dataset.p1 = match.player1;
|
||||
option.dataset.p2 = match.player2;
|
||||
const p1Name = match.p1_name || (match.player1 && match.player1.name);
|
||||
const p2Name = match.p2_name || (match.player2 && match.player2.name);
|
||||
option.textContent = `${match.round} : ${p1Name} vs ${p2Name}`;
|
||||
select.appendChild(option);
|
||||
});
|
||||
|
||||
updateWinnerSelect();
|
||||
|
||||
select.addEventListener('change', updateWinnerSelect);
|
||||
} catch(e) { console.error(e); }
|
||||
}
|
||||
|
||||
function updateWinnerSelect() {
|
||||
const select = document.getElementById('resultMatch');
|
||||
const winnerSelect = document.getElementById('resultWinner');
|
||||
const selectedOption = select.options[select.selectedIndex];
|
||||
|
||||
if(select.selectedIndex === -1 || !window.currentAdminMatches) return;
|
||||
const matchId = parseInt(select.value);
|
||||
const match = window.currentAdminMatches.find(m => m.id === matchId);
|
||||
|
||||
winnerSelect.innerHTML = '';
|
||||
if (selectedOption.dataset.p1) {
|
||||
const p1 = playersData[selectedOption.dataset.p1];
|
||||
const p2 = playersData[selectedOption.dataset.p2];
|
||||
if (match) {
|
||||
const p1Id = match.p1_id || (match.player1 && match.player1.id);
|
||||
const p1Name = match.p1_name || (match.player1 && match.player1.name);
|
||||
const p2Id = match.p2_id || (match.player2 && match.player2.id);
|
||||
const p2Name = match.p2_name || (match.player2 && match.player2.name);
|
||||
|
||||
winnerSelect.innerHTML = `
|
||||
<option value="${p1.id}">${p1.name}</option>
|
||||
<option value="${p2.id}">${p2.name}</option>
|
||||
<option value="${p1Id}">${p1Name}</option>
|
||||
<option value="${p2Id}">${p2Name}</option>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
function updateResult() {
|
||||
async function updateResult() {
|
||||
const matchId = parseInt(document.getElementById('resultMatch').value);
|
||||
const winner = document.getElementById('resultWinner').value;
|
||||
const winnerId = parseInt(document.getElementById('resultWinner').value);
|
||||
const score = document.getElementById('resultScore').value;
|
||||
|
||||
const match = tournamentMatches.find(m => m.id === matchId);
|
||||
if (match) {
|
||||
match.status = 'completed';
|
||||
match.winner = winner;
|
||||
match.score = score;
|
||||
|
||||
// Calculer les points pour les utilisateurs
|
||||
calculateUserPoints(matchId, winner);
|
||||
|
||||
alert('Résultat mis à jour avec succès!');
|
||||
loadAdminData();
|
||||
}
|
||||
}
|
||||
|
||||
function calculateUserPoints(matchId, winner) {
|
||||
const allPredictions = JSON.parse(localStorage.getItem('userPredictions') || '[]');
|
||||
const matchPredictions = allPredictions.filter(p => p.matchId === matchId);
|
||||
|
||||
matchPredictions.forEach(pred => {
|
||||
const user = users.find(u => u.id === pred.userId);
|
||||
if (user && pred.predictedWinner === winner) {
|
||||
user.points = (user.points || 0) + 50; // 50 points pour un pronostic juste
|
||||
|
||||
// Mettre à jour localStorage
|
||||
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
|
||||
if (currentUser && currentUser.id === user.id) {
|
||||
localStorage.setItem('currentUser', JSON.stringify(user));
|
||||
}
|
||||
}
|
||||
try {
|
||||
await apiCall('results.php', 'POST', {
|
||||
match_id: matchId,
|
||||
winner_id: winnerId,
|
||||
score: score
|
||||
});
|
||||
|
||||
localStorage.setItem('users', JSON.stringify(users));
|
||||
alert('Résultat mis à jour avec succès ! Les points ont été distribués.');
|
||||
loadResultsDropdown();
|
||||
} catch (error) {
|
||||
alert(error.message);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user