Initial commit
This commit is contained in:
+125
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
require_once 'config.php';
|
||||
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
$action = $_GET['action'] ?? '';
|
||||
|
||||
switch ($method) {
|
||||
case 'POST':
|
||||
if ($action === 'register') {
|
||||
register();
|
||||
} elseif ($action === 'login') {
|
||||
login();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'GET':
|
||||
if ($action === 'me') {
|
||||
getCurrentUserInfo();
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
jsonResponse(['error' => 'Méthode non autorisée'], 405);
|
||||
}
|
||||
|
||||
function register() {
|
||||
$data = getJsonInput();
|
||||
|
||||
if (!isset($data['username']) || !isset($data['email']) || !isset($data['password'])) {
|
||||
jsonResponse(['error' => 'Tous les champs sont requis'], 400);
|
||||
}
|
||||
|
||||
$username = trim($data['username']);
|
||||
$email = trim($data['email']);
|
||||
$password = $data['password'];
|
||||
|
||||
// Validation
|
||||
if (strlen($username) < 3) {
|
||||
jsonResponse(['error' => 'Le nom d\'utilisateur doit contenir au moins 3 caractères'], 400);
|
||||
}
|
||||
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
jsonResponse(['error' => 'Email invalide'], 400);
|
||||
}
|
||||
|
||||
if (strlen($password) < 6) {
|
||||
jsonResponse(['error' => 'Le mot de passe doit contenir au moins 6 caractères'], 400);
|
||||
}
|
||||
|
||||
$db = getDB();
|
||||
|
||||
// Vérifier si l'utilisateur existe déjà
|
||||
$stmt = $db->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
|
||||
$stmt->execute([$username, $email]);
|
||||
|
||||
if ($stmt->fetch()) {
|
||||
jsonResponse(['error' => 'Ce nom d\'utilisateur ou cet email existe déjà'], 409);
|
||||
}
|
||||
|
||||
// Créer l'utilisateur
|
||||
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
|
||||
$stmt = $db->prepare("INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, 'user')");
|
||||
$stmt->execute([$username, $email, $hashedPassword]);
|
||||
|
||||
$userId = $db->lastInsertId();
|
||||
$token = generateToken($userId);
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'message' => 'Compte créé avec succès',
|
||||
'token' => $token,
|
||||
'user' => [
|
||||
'id' => $userId,
|
||||
'username' => $username,
|
||||
'email' => $email,
|
||||
'role' => 'user',
|
||||
'points' => 0
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
function login() {
|
||||
$data = getJsonInput();
|
||||
|
||||
if (!isset($data['username']) || !isset($data['password'])) {
|
||||
jsonResponse(['error' => 'Nom d\'utilisateur et mot de passe requis'], 400);
|
||||
}
|
||||
|
||||
$username = trim($data['username']);
|
||||
$password = $data['password'];
|
||||
|
||||
$db = getDB();
|
||||
$stmt = $db->prepare("SELECT id, username, email, password, role, points FROM users WHERE username = ?");
|
||||
$stmt->execute([$username]);
|
||||
$user = $stmt->fetch();
|
||||
|
||||
if (!$user || !password_verify($password, $user['password'])) {
|
||||
jsonResponse(['error' => 'Identifiants incorrects'], 401);
|
||||
}
|
||||
|
||||
$token = generateToken($user['id']);
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'message' => 'Connexion réussie',
|
||||
'token' => $token,
|
||||
'user' => [
|
||||
'id' => $user['id'],
|
||||
'username' => $user['username'],
|
||||
'email' => $user['email'],
|
||||
'role' => $user['role'],
|
||||
'points' => (int)$user['points']
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
function getCurrentUserInfo() {
|
||||
$user = requireAuth();
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'user' => $user
|
||||
]);
|
||||
}
|
||||
?>
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
// Configuration de la base de données
|
||||
define('DB_HOST', 'localhost');
|
||||
define('DB_NAME', 'mon_pari');
|
||||
define('DB_USER', 'root');
|
||||
define('DB_PASS', '');
|
||||
define('DB_CHARSET', 'utf8mb4');
|
||||
|
||||
// Configuration de l'application
|
||||
define('JWT_SECRET', 'mon-petit-pari-secret-key-2026-change-this-in-production');
|
||||
define('JWT_EXPIRY', 86400); // 24 heures en secondes
|
||||
define('POINTS_CORRECT_PREDICTION', 50);
|
||||
define('POINTS_NEW_PREDICTION', 10);
|
||||
|
||||
// Headers CORS
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
|
||||
header('Access-Control-Allow-Headers: Content-Type, Authorization');
|
||||
|
||||
// Gestion des requêtes OPTIONS (preflight)
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||||
http_response_code(200);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Connexion à la base de données
|
||||
function getDB() {
|
||||
static $pdo = null;
|
||||
|
||||
if ($pdo === null) {
|
||||
try {
|
||||
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
|
||||
$options = [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
];
|
||||
$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
|
||||
} catch (PDOException $e) {
|
||||
http_response_code(500);
|
||||
echo json_encode(['error' => 'Erreur de connexion à la base de données: ' . $e->getMessage()]);
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
return $pdo;
|
||||
}
|
||||
|
||||
// Fonction pour générer un token JWT simple
|
||||
function generateToken($userId) {
|
||||
$header = base64_encode(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
|
||||
$payload = base64_encode(json_encode([
|
||||
'user_id' => $userId,
|
||||
'exp' => time() + JWT_EXPIRY
|
||||
]));
|
||||
$signature = hash_hmac('sha256', "$header.$payload", JWT_SECRET);
|
||||
return "$header.$payload.$signature";
|
||||
}
|
||||
|
||||
// Fonction pour vérifier un token
|
||||
function verifyToken($token) {
|
||||
$parts = explode('.', $token);
|
||||
if (count($parts) !== 3) return false;
|
||||
|
||||
list($header, $payload, $signature) = $parts;
|
||||
|
||||
$expectedSignature = hash_hmac('sha256', "$header.$payload", JWT_SECRET);
|
||||
if (!hash_equals($expectedSignature, $signature)) return false;
|
||||
|
||||
$data = json_decode(base64_decode($payload), true);
|
||||
if (!$data || !isset($data['exp']) || $data['exp'] < time()) return false;
|
||||
|
||||
return $data['user_id'];
|
||||
}
|
||||
|
||||
// Fonction pour obtenir l'utilisateur actuel
|
||||
function getCurrentUser() {
|
||||
$headers = getallheaders();
|
||||
$authHeader = $headers['Authorization'] ?? '';
|
||||
|
||||
if (preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
|
||||
$token = $matches[1];
|
||||
$userId = verifyToken($token);
|
||||
|
||||
if ($userId) {
|
||||
$db = getDB();
|
||||
$stmt = $db->prepare("SELECT id, username, email, role, points FROM users WHERE id = ?");
|
||||
$stmt->execute([$userId]);
|
||||
return $stmt->fetch();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Fonction pour vérifier si l'utilisateur est admin
|
||||
function requireAdmin() {
|
||||
$user = getCurrentUser();
|
||||
if (!$user || $user['role'] !== 'admin') {
|
||||
http_response_code(403);
|
||||
echo json_encode(['error' => 'Accès refusé. Droits administrateur requis.']);
|
||||
exit();
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
// Fonction pour vérifier si l'utilisateur est authentifié
|
||||
function requireAuth() {
|
||||
$user = getCurrentUser();
|
||||
if (!$user) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['error' => 'Authentification requise.']);
|
||||
exit();
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
// Fonction pour obtenir les données JSON de la requête
|
||||
function getJsonInput() {
|
||||
$input = file_get_contents('php://input');
|
||||
return json_decode($input, true);
|
||||
}
|
||||
|
||||
// Fonction de réponse JSON
|
||||
function jsonResponse($data, $statusCode = 200) {
|
||||
http_response_code($statusCode);
|
||||
echo json_encode($data, JSON_UNESCAPED_UNICODE);
|
||||
exit();
|
||||
}
|
||||
?>
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
require_once 'config.php';
|
||||
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
$action = $_GET['action'] ?? '';
|
||||
$id = $_GET['id'] ?? null;
|
||||
|
||||
switch ($method) {
|
||||
case 'GET':
|
||||
if ($id) {
|
||||
getMatch($id);
|
||||
} else {
|
||||
getAllMatches();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'POST':
|
||||
requireAdmin();
|
||||
addMatch();
|
||||
break;
|
||||
|
||||
case 'PUT':
|
||||
requireAdmin();
|
||||
updateMatch($id);
|
||||
break;
|
||||
|
||||
case 'DELETE':
|
||||
requireAdmin();
|
||||
deleteMatch($id);
|
||||
break;
|
||||
|
||||
default:
|
||||
jsonResponse(['error' => 'Méthode non autorisée'], 405);
|
||||
}
|
||||
|
||||
function getAllMatches() {
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->query("
|
||||
SELECT m.*,
|
||||
p1.id as p1_id, p1.name as p1_name, p1.photo_url as p1_photo, p1.ranking as p1_ranking,
|
||||
p1.nationality as p1_nationality, p1.handedness as p1_handedness,
|
||||
p2.id as p2_id, p2.name as p2_name, p2.photo_url as p2_photo, p2.ranking as p2_ranking,
|
||||
p2.nationality as p2_nationality, p2.handedness as p2_handedness,
|
||||
pw.name as winner_name
|
||||
FROM matches m
|
||||
JOIN players p1 ON m.player1_id = p1.id
|
||||
JOIN players p2 ON m.player2_id = p2.id
|
||||
LEFT JOIN players pw ON m.winner_id = pw.id
|
||||
ORDER BY m.match_date DESC,
|
||||
CASE m.round
|
||||
WHEN 'Finale' THEN 1
|
||||
WHEN 'Demi-finale' THEN 2
|
||||
WHEN 'Quart de finale' THEN 3
|
||||
WHEN '8ème de finale' THEN 4
|
||||
ELSE 5
|
||||
END
|
||||
");
|
||||
|
||||
$matches = [];
|
||||
while ($row = $stmt->fetch()) {
|
||||
$matches[] = [
|
||||
'id' => $row['id'],
|
||||
'round' => $row['round'],
|
||||
'player1' => [
|
||||
'id' => $row['p1_id'],
|
||||
'name' => $row['p1_name'],
|
||||
'photo' => $row['p1_photo'],
|
||||
'ranking' => $row['p1_ranking'],
|
||||
'nationality' => $row['p1_nationality'],
|
||||
'handedness' => $row['p1_handedness']
|
||||
],
|
||||
'player2' => [
|
||||
'id' => $row['p2_id'],
|
||||
'name' => $row['p2_name'],
|
||||
'photo' => $row['p2_photo'],
|
||||
'ranking' => $row['p2_ranking'],
|
||||
'nationality' => $row['p2_nationality'],
|
||||
'handedness' => $row['p2_handedness']
|
||||
],
|
||||
'date' => $row['match_date'],
|
||||
'court' => $row['court'],
|
||||
'status' => $row['status'],
|
||||
'winner' => $row['winner_id'] ? [
|
||||
'id' => $row['winner_id'],
|
||||
'name' => $row['winner_name']
|
||||
] : null,
|
||||
'score' => $row['score']
|
||||
];
|
||||
}
|
||||
|
||||
jsonResponse(['success' => true, 'matches' => $matches]);
|
||||
}
|
||||
|
||||
function getMatch($id) {
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->prepare("
|
||||
SELECT m.*,
|
||||
p1.id as p1_id, p1.name as p1_name, p1.photo_url as p1_photo, p1.ranking as p1_ranking,
|
||||
p1.nationality as p1_nationality, p1.handedness as p1_handedness,
|
||||
p2.id as p2_id, p2.name as p2_name, p2.photo_url as p2_photo, p2.ranking as p2_ranking,
|
||||
p2.nationality as p2_nationality, p2.handedness as p2_handedness,
|
||||
pw.name as winner_name
|
||||
FROM matches m
|
||||
JOIN players p1 ON m.player1_id = p1.id
|
||||
JOIN players p2 ON m.player2_id = p2.id
|
||||
LEFT JOIN players pw ON m.winner_id = pw.id
|
||||
WHERE m.id = ?
|
||||
");
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
|
||||
if (!$row) {
|
||||
jsonResponse(['error' => 'Match non trouvé'], 404);
|
||||
}
|
||||
|
||||
$match = [
|
||||
'id' => $row['id'],
|
||||
'round' => $row['round'],
|
||||
'player1' => [
|
||||
'id' => $row['p1_id'],
|
||||
'name' => $row['p1_name'],
|
||||
'photo' => $row['p1_photo'],
|
||||
'ranking' => $row['p1_ranking'],
|
||||
'nationality' => $row['p1_nationality'],
|
||||
'handedness' => $row['p1_handedness']
|
||||
],
|
||||
'player2' => [
|
||||
'id' => $row['p2_id'],
|
||||
'name' => $row['p2_name'],
|
||||
'photo' => $row['p2_photo'],
|
||||
'ranking' => $row['p2_ranking'],
|
||||
'nationality' => $row['p2_nationality'],
|
||||
'handedness' => $row['p2_handedness']
|
||||
],
|
||||
'date' => $row['match_date'],
|
||||
'court' => $row['court'],
|
||||
'status' => $row['status'],
|
||||
'winner' => $row['winner_id'] ? [
|
||||
'id' => $row['winner_id'],
|
||||
'name' => $row['winner_name']
|
||||
] : null,
|
||||
'score' => $row['score']
|
||||
];
|
||||
|
||||
jsonResponse(['success' => true, 'match' => $match]);
|
||||
}
|
||||
|
||||
function addMatch() {
|
||||
$data = getJsonInput();
|
||||
|
||||
$required = ['round', 'player1_id', 'player2_id', 'match_date'];
|
||||
foreach ($required as $field) {
|
||||
if (!isset($data[$field])) {
|
||||
jsonResponse(['error' => "Le champ $field est requis"], 400);
|
||||
}
|
||||
}
|
||||
|
||||
$db = getDB();
|
||||
|
||||
// Vérifier que les joueurs existent
|
||||
$stmt = $db->prepare("SELECT id FROM players WHERE id IN (?, ?)");
|
||||
$stmt->execute([$data['player1_id'], $data['player2_id']]);
|
||||
if ($stmt->rowCount() !== 2) {
|
||||
jsonResponse(['error' => 'Un ou les deux joueurs n\'existent pas'], 404);
|
||||
}
|
||||
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO matches (round, player1_id, player2_id, match_date, court, status)
|
||||
VALUES (?, ?, ?, ?, ?, 'upcoming')
|
||||
");
|
||||
|
||||
$stmt->execute([
|
||||
$data['round'],
|
||||
$data['player1_id'],
|
||||
$data['player2_id'],
|
||||
$data['match_date'],
|
||||
$data['court'] ?? null
|
||||
]);
|
||||
|
||||
jsonResponse(['success' => true, 'message' => 'Match ajouté avec succès', 'match_id' => $db->lastInsertId()]);
|
||||
}
|
||||
|
||||
function updateMatch($id) {
|
||||
$data = getJsonInput();
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->prepare("SELECT id, status FROM matches WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
$match = $stmt->fetch();
|
||||
|
||||
if (!$match) {
|
||||
jsonResponse(['error' => 'Match non trouvé'], 404);
|
||||
}
|
||||
|
||||
$fields = [];
|
||||
$values = [];
|
||||
|
||||
$allowedFields = ['round', 'player1_id', 'player2_id', 'match_date', 'court', 'status', 'winner_id', 'score'];
|
||||
|
||||
foreach ($allowedFields as $field) {
|
||||
if (isset($data[$field])) {
|
||||
$fields[] = "$field = ?";
|
||||
$values[] = $data[$field];
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($fields)) {
|
||||
jsonResponse(['error' => 'Aucune donnée à mettre à jour'], 400);
|
||||
}
|
||||
|
||||
$values[] = $id;
|
||||
$stmt = $db->prepare("UPDATE matches SET " . implode(', ', $fields) . " WHERE id = ?");
|
||||
$stmt->execute($values);
|
||||
|
||||
jsonResponse(['success' => true, 'message' => 'Match mis à jour avec succès']);
|
||||
}
|
||||
|
||||
function deleteMatch($id) {
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->prepare("DELETE FROM matches WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
|
||||
if ($stmt->rowCount() === 0) {
|
||||
jsonResponse(['error' => 'Match non trouvé'], 404);
|
||||
}
|
||||
|
||||
jsonResponse(['success' => true, 'message' => 'Match supprimé avec succès']);
|
||||
}
|
||||
?>
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
<?php
|
||||
require_once 'config.php';
|
||||
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
$action = $_GET['action'] ?? '';
|
||||
$id = $_GET['id'] ?? null;
|
||||
|
||||
switch ($method) {
|
||||
case 'GET':
|
||||
if ($action === 'matchup' && isset($_GET['player1']) && isset($_GET['player2'])) {
|
||||
getMatchupAnalysis($_GET['player1'], $_GET['player2']);
|
||||
} elseif ($id) {
|
||||
getPlayer($id);
|
||||
} else {
|
||||
getAllPlayers();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'POST':
|
||||
requireAdmin();
|
||||
addPlayer();
|
||||
break;
|
||||
|
||||
case 'PUT':
|
||||
requireAdmin();
|
||||
updatePlayer($id);
|
||||
break;
|
||||
|
||||
case 'DELETE':
|
||||
requireAdmin();
|
||||
deletePlayer($id);
|
||||
break;
|
||||
|
||||
default:
|
||||
jsonResponse(['error' => 'Méthode non autorisée'], 405);
|
||||
}
|
||||
|
||||
function getAllPlayers() {
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->query("
|
||||
SELECT p.*,
|
||||
(SELECT GROUP_CONCAT(strength SEPARATOR '|') FROM player_strengths WHERE player_id = p.id) as strengths,
|
||||
(SELECT GROUP_CONCAT(weakness SEPARATOR '|') FROM player_weaknesses WHERE player_id = p.id) as weaknesses
|
||||
FROM players p
|
||||
ORDER BY p.ranking ASC
|
||||
");
|
||||
|
||||
$players = [];
|
||||
while ($row = $stmt->fetch()) {
|
||||
$row['strengths'] = $row['strengths'] ? explode('|', $row['strengths']) : [];
|
||||
$row['weaknesses'] = $row['weaknesses'] ? explode('|', $row['weaknesses']) : [];
|
||||
|
||||
// Convertir les décimaux en float
|
||||
$row['clay_win_rate'] = (float)$row['clay_win_rate'];
|
||||
$row['hard_win_rate'] = (float)$row['hard_win_rate'];
|
||||
$row['grass_win_rate'] = (float)$row['grass_win_rate'];
|
||||
|
||||
$players[] = $row;
|
||||
}
|
||||
|
||||
jsonResponse(['success' => true, 'players' => $players]);
|
||||
}
|
||||
|
||||
function getPlayer($id) {
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->prepare("
|
||||
SELECT p.*,
|
||||
(SELECT GROUP_CONCAT(strength SEPARATOR '|') FROM player_strengths WHERE player_id = p.id) as strengths,
|
||||
(SELECT GROUP_CONCAT(weakness SEPARATOR '|') FROM player_weaknesses WHERE player_id = p.id) as weaknesses
|
||||
FROM players p
|
||||
WHERE p.id = ?
|
||||
");
|
||||
$stmt->execute([$id]);
|
||||
$player = $stmt->fetch();
|
||||
|
||||
if (!$player) {
|
||||
jsonResponse(['error' => 'Joueur non trouvé'], 404);
|
||||
}
|
||||
|
||||
$player['strengths'] = $player['strengths'] ? explode('|', $player['strengths']) : [];
|
||||
$player['weaknesses'] = $player['weaknesses'] ? explode('|', $player['weaknesses']) : [];
|
||||
|
||||
jsonResponse(['success' => true, 'player' => $player]);
|
||||
}
|
||||
|
||||
function getMatchupAnalysis($player1Id, $player2Id) {
|
||||
$db = getDB();
|
||||
|
||||
// Récupérer les deux joueurs
|
||||
$stmt = $db->prepare("SELECT * FROM players WHERE id = ?");
|
||||
$stmt->execute([$player1Id]);
|
||||
$player1 = $stmt->fetch();
|
||||
|
||||
$stmt = $db->prepare("SELECT * FROM players WHERE id = ?");
|
||||
$stmt->execute([$player2Id]);
|
||||
$player2 = $stmt->fetch();
|
||||
|
||||
if (!$player1 || !$player2) {
|
||||
jsonResponse(['error' => 'Un ou les deux joueurs n\'existent pas'], 404);
|
||||
}
|
||||
|
||||
// Récupérer les forces et faiblesses
|
||||
$stmt = $db->prepare("SELECT strength FROM player_strengths WHERE player_id = ?");
|
||||
$stmt->execute([$player1Id]);
|
||||
$player1['strengths'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
|
||||
|
||||
$stmt = $db->prepare("SELECT weakness FROM player_weaknesses WHERE player_id = ?");
|
||||
$stmt->execute([$player1Id]);
|
||||
$player1['weaknesses'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
|
||||
|
||||
$stmt = $db->prepare("SELECT strength FROM player_strengths WHERE player_id = ?");
|
||||
$stmt->execute([$player2Id]);
|
||||
$player2['strengths'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
|
||||
|
||||
$stmt = $db->prepare("SELECT weakness FROM player_weaknesses WHERE player_id = ?");
|
||||
$stmt->execute([$player2Id]);
|
||||
$player2['weaknesses'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
|
||||
|
||||
// Calculer les probabilités
|
||||
$probabilities = calculateWinProbability($player1, $player2, 'clay');
|
||||
|
||||
// Analyser le matchup
|
||||
$analysis = analyzeMatchup($player1, $player2);
|
||||
|
||||
// Récupérer H2H si disponible
|
||||
$stmt = $db->prepare("
|
||||
SELECT * FROM head_to_head
|
||||
WHERE (player1_id = ? AND player2_id = ?)
|
||||
OR (player1_id = ? AND player2_id = ?)
|
||||
");
|
||||
$stmt->execute([$player1Id, $player2Id, $player2Id, $player1Id]);
|
||||
$h2h = $stmt->fetch();
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'player1' => $player1,
|
||||
'player2' => $player2,
|
||||
'probabilities' => $probabilities,
|
||||
'analysis' => $analysis,
|
||||
'head_to_head' => $h2h
|
||||
]);
|
||||
}
|
||||
|
||||
function calculateWinProbability($player1, $player2, $surface = 'clay') {
|
||||
$prob1 = 50;
|
||||
$prob2 = 50;
|
||||
|
||||
// Facteur ranking
|
||||
$rankingDiff = $player2['ranking'] - $player1['ranking'];
|
||||
$prob1 += $rankingDiff * 2;
|
||||
$prob2 -= $rankingDiff * 2;
|
||||
|
||||
// Facteur surface
|
||||
$surfaceField = $surface . '_win_rate';
|
||||
$p1Surface = $player1[$surfaceField] * 100;
|
||||
$p2Surface = $player2[$surfaceField] * 100;
|
||||
$surfaceDiff = $p1Surface - $p2Surface;
|
||||
$prob1 += $surfaceDiff * 0.5;
|
||||
$prob2 -= $surfaceDiff * 0.5;
|
||||
|
||||
// Normalisation
|
||||
$total = $prob1 + $prob2;
|
||||
$prob1 = round(($prob1 / $total) * 100);
|
||||
$prob2 = 100 - $prob1;
|
||||
|
||||
// Limiter entre 10 et 90
|
||||
$prob1 = max(10, min(90, $prob1));
|
||||
$prob2 = 100 - $prob1;
|
||||
|
||||
return [
|
||||
'player1' => $prob1,
|
||||
'player2' => $prob2
|
||||
];
|
||||
}
|
||||
|
||||
function analyzeMatchup($player1, $player2) {
|
||||
$analysis = [
|
||||
'player1_advantages' => [],
|
||||
'player1_disadvantages' => [],
|
||||
'player2_advantages' => [],
|
||||
'player2_disadvantages' => []
|
||||
];
|
||||
|
||||
// Analyser les forces
|
||||
foreach ($player1['strengths'] as $strength) {
|
||||
if (!in_array($strength, $player2['strengths']) && !in_array($strength, $player2['weaknesses'])) {
|
||||
$analysis['player1_advantages'][] = $strength;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($player2['strengths'] as $strength) {
|
||||
if (!in_array($strength, $player1['strengths']) && !in_array($strength, $player1['weaknesses'])) {
|
||||
$analysis['player2_advantages'][] = $strength;
|
||||
}
|
||||
}
|
||||
|
||||
// Exploitation des faiblesses
|
||||
foreach ($player1['weaknesses'] as $weakness) {
|
||||
foreach ($player2['strengths'] as $strength) {
|
||||
if (stripos($strength, explode(' ', $weakness)[0]) !== false) {
|
||||
$analysis['player2_advantages'][] = "Exploite: $weakness";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($player2['weaknesses'] as $weakness) {
|
||||
foreach ($player1['strengths'] as $strength) {
|
||||
if (stripos($strength, explode(' ', $weakness)[0]) !== false) {
|
||||
$analysis['player1_advantages'][] = "Exploite: $weakness";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $analysis;
|
||||
}
|
||||
|
||||
function addPlayer() {
|
||||
$data = getJsonInput();
|
||||
|
||||
$required = ['player_code', 'name', 'nationality', 'age', 'handedness', 'ranking', 'points'];
|
||||
foreach ($required as $field) {
|
||||
if (!isset($data[$field])) {
|
||||
jsonResponse(['error' => "Le champ $field est requis"], 400);
|
||||
}
|
||||
}
|
||||
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO players (player_code, name, nationality, age, handedness, photo_url, ranking, points,
|
||||
clay_win_rate, hard_win_rate, grass_win_rate)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
");
|
||||
|
||||
$stmt->execute([
|
||||
$data['player_code'],
|
||||
$data['name'],
|
||||
$data['nationality'],
|
||||
$data['age'],
|
||||
$data['handedness'],
|
||||
$data['photo_url'] ?? null,
|
||||
$data['ranking'],
|
||||
$data['points'],
|
||||
$data['clay_win_rate'] ?? 0.50,
|
||||
$data['hard_win_rate'] ?? 0.50,
|
||||
$data['grass_win_rate'] ?? 0.50
|
||||
]);
|
||||
|
||||
$playerId = $db->lastInsertId();
|
||||
|
||||
// Ajouter les forces
|
||||
if (isset($data['strengths']) && is_array($data['strengths'])) {
|
||||
$stmt = $db->prepare("INSERT INTO player_strengths (player_id, strength) VALUES (?, ?)");
|
||||
foreach ($data['strengths'] as $strength) {
|
||||
$stmt->execute([$playerId, $strength]);
|
||||
}
|
||||
}
|
||||
|
||||
// Ajouter les faiblesses
|
||||
if (isset($data['weaknesses']) && is_array($data['weaknesses'])) {
|
||||
$stmt = $db->prepare("INSERT INTO player_weaknesses (player_id, weakness) VALUES (?, ?)");
|
||||
foreach ($data['weaknesses'] as $weakness) {
|
||||
$stmt->execute([$playerId, $weakness]);
|
||||
}
|
||||
}
|
||||
|
||||
jsonResponse(['success' => true, 'message' => 'Joueur ajouté avec succès', 'player_id' => $playerId]);
|
||||
}
|
||||
|
||||
function updatePlayer($id) {
|
||||
$data = getJsonInput();
|
||||
$db = getDB();
|
||||
|
||||
// Vérifier que le joueur existe
|
||||
$stmt = $db->prepare("SELECT id FROM players WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
if (!$stmt->fetch()) {
|
||||
jsonResponse(['error' => 'Joueur non trouvé'], 404);
|
||||
}
|
||||
|
||||
$db->beginTransaction();
|
||||
|
||||
try {
|
||||
$fields = [];
|
||||
$values = [];
|
||||
|
||||
$allowedFields = ['name', 'nationality', 'age', 'handedness', 'photo_url', 'ranking', 'points',
|
||||
'clay_win_rate', 'hard_win_rate', 'grass_win_rate'];
|
||||
|
||||
foreach ($allowedFields as $field) {
|
||||
if (isset($data[$field])) {
|
||||
$fields[] = "$field = ?";
|
||||
$values[] = $data[$field];
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($fields)) {
|
||||
$values[] = $id;
|
||||
$stmt = $db->prepare("UPDATE players SET " . implode(', ', $fields) . " WHERE id = ?");
|
||||
$stmt->execute($values);
|
||||
}
|
||||
|
||||
// Mettre à jour les forces si fourni
|
||||
if (isset($data['strengths'])) {
|
||||
$stmt = $db->prepare("DELETE FROM player_strengths WHERE player_id = ?");
|
||||
$stmt->execute([$id]);
|
||||
|
||||
$stmt = $db->prepare("INSERT INTO player_strengths (player_id, strength) VALUES (?, ?)");
|
||||
foreach ($data['strengths'] as $strength) {
|
||||
$stmt->execute([$id, $strength]);
|
||||
}
|
||||
}
|
||||
|
||||
// Mettre à jour les faiblesses si fourni
|
||||
if (isset($data['weaknesses'])) {
|
||||
$stmt = $db->prepare("DELETE FROM player_weaknesses WHERE player_id = ?");
|
||||
$stmt->execute([$id]);
|
||||
|
||||
$stmt = $db->prepare("INSERT INTO player_weaknesses (player_id, weakness) VALUES (?, ?)");
|
||||
foreach ($data['weaknesses'] as $weakness) {
|
||||
$stmt->execute([$id, $weakness]);
|
||||
}
|
||||
}
|
||||
|
||||
$db->commit();
|
||||
jsonResponse(['success' => true, 'message' => 'Joueur mis à jour avec succès']);
|
||||
|
||||
} catch (Exception $e) {
|
||||
$db->rollBack();
|
||||
jsonResponse(['error' => 'Erreur lors de la mise à jour: ' . $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
|
||||
function deletePlayer($id) {
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->prepare("DELETE FROM players WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
|
||||
if ($stmt->rowCount() === 0) {
|
||||
jsonResponse(['error' => 'Joueur non trouvé'], 404);
|
||||
}
|
||||
|
||||
jsonResponse(['success' => true, 'message' => 'Joueur supprimé avec succès']);
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
require_once 'config.php';
|
||||
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
$action = $_GET['action'] ?? '';
|
||||
|
||||
switch ($method) {
|
||||
case 'GET':
|
||||
if ($action === 'stats') {
|
||||
getUserStats();
|
||||
} elseif ($action === 'leaderboard') {
|
||||
getLeaderboard();
|
||||
} else {
|
||||
getUserPredictions();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'POST':
|
||||
$user = requireAuth();
|
||||
makePrediction($user);
|
||||
break;
|
||||
|
||||
default:
|
||||
jsonResponse(['error' => 'Méthode non autorisée'], 405);
|
||||
}
|
||||
|
||||
function getUserPredictions() {
|
||||
$user = requireAuth();
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->prepare("
|
||||
SELECT p.*, m.match_date, m.round, m.status,
|
||||
p1.name as p1_name, p2.name as p2_name,
|
||||
pw.name as predicted_winner_name,
|
||||
mw.name as actual_winner_name
|
||||
FROM predictions p
|
||||
JOIN matches m ON p.match_id = m.id
|
||||
JOIN players p1 ON m.player1_id = p1.id
|
||||
JOIN players p2 ON m.player2_id = p2.id
|
||||
JOIN players pw ON p.predicted_winner_id = pw.id
|
||||
LEFT JOIN players mw ON m.winner_id = mw.id
|
||||
WHERE p.user_id = ?
|
||||
ORDER BY m.match_date DESC
|
||||
");
|
||||
$stmt->execute([$user['id']]);
|
||||
|
||||
jsonResponse(['success' => true, 'predictions' => $stmt->fetchAll()]);
|
||||
}
|
||||
|
||||
function makePrediction($user) {
|
||||
$data = getJsonInput();
|
||||
|
||||
if (!isset($data['match_id']) || !isset($data['predicted_winner_id'])) {
|
||||
jsonResponse(['error' => 'match_id et predicted_winner_id requis'], 400);
|
||||
}
|
||||
|
||||
$db = getDB();
|
||||
|
||||
// Vérifier que le match existe et est à venir
|
||||
$stmt = $db->prepare("SELECT id, status, player1_id, player2_id FROM matches WHERE id = ?");
|
||||
$stmt->execute([$data['match_id']]);
|
||||
$match = $stmt->fetch();
|
||||
|
||||
if (!$match) {
|
||||
jsonResponse(['error' => 'Match non trouvé'], 404);
|
||||
}
|
||||
|
||||
if ($match['status'] !== 'upcoming') {
|
||||
jsonResponse(['error' => 'Ce match est déjà terminé ou annulé'], 400);
|
||||
}
|
||||
|
||||
// Vérifier que le gagnant prédit est l'un des deux joueurs
|
||||
if ($data['predicted_winner_id'] != $match['player1_id'] && $data['predicted_winner_id'] != $match['player2_id']) {
|
||||
jsonResponse(['error' => 'Le gagnant prédit doit être l\'un des deux joueurs du match'], 400);
|
||||
}
|
||||
|
||||
// Vérifier si l'utilisateur a déjà fait un pronostic pour ce match
|
||||
$stmt = $db->prepare("SELECT id FROM predictions WHERE user_id = ? AND match_id = ?");
|
||||
$stmt->execute([$user['id'], $data['match_id']]);
|
||||
|
||||
if ($stmt->fetch()) {
|
||||
jsonResponse(['error' => 'Vous avez déjà fait un pronostic pour ce match'], 409);
|
||||
}
|
||||
|
||||
// Créer le pronostic
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO predictions (user_id, match_id, predicted_winner_id, points_earned)
|
||||
VALUES (?, ?, ?, ?)
|
||||
");
|
||||
$stmt->execute([
|
||||
$user['id'],
|
||||
$data['match_id'],
|
||||
$data['predicted_winner_id'],
|
||||
POINTS_NEW_PREDICTION
|
||||
]);
|
||||
|
||||
// Ajouter les points à l'utilisateur
|
||||
$stmt = $db->prepare("UPDATE users SET points = points + ? WHERE id = ?");
|
||||
$stmt->execute([POINTS_NEW_PREDICTION, $user['id']]);
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'message' => 'Pronostic enregistré avec succès',
|
||||
'points_earned' => POINTS_NEW_PREDICTION
|
||||
]);
|
||||
}
|
||||
|
||||
function getUserStats() {
|
||||
$user = requireAuth();
|
||||
$db = getDB();
|
||||
|
||||
// Total de pronostics
|
||||
$stmt = $db->prepare("SELECT COUNT(*) as total FROM predictions WHERE user_id = ?");
|
||||
$stmt->execute([$user['id']]);
|
||||
$total = $stmt->fetch()['total'];
|
||||
|
||||
// Pronostics corrects
|
||||
$stmt = $db->prepare("
|
||||
SELECT COUNT(*) as correct
|
||||
FROM predictions p
|
||||
JOIN matches m ON p.match_id = m.id
|
||||
WHERE p.user_id = ? AND p.is_correct = 1
|
||||
");
|
||||
$stmt->execute([$user['id']]);
|
||||
$correct = $stmt->fetch()['correct'];
|
||||
|
||||
// Taux de réussite
|
||||
$rate = $total > 0 ? round(($correct / $total) * 100) : 0;
|
||||
|
||||
// Points totaux
|
||||
$stmt = $db->prepare("SELECT points FROM users WHERE id = ?");
|
||||
$stmt->execute([$user['id']]);
|
||||
$points = $stmt->fetch()['points'];
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'stats' => [
|
||||
'total_predictions' => (int)$total,
|
||||
'correct_predictions' => (int)$correct,
|
||||
'success_rate' => $rate,
|
||||
'total_points' => (int)$points
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
function getLeaderboard() {
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->query("
|
||||
SELECT u.id, u.username, u.points,
|
||||
COUNT(p.id) as total_predictions,
|
||||
SUM(CASE WHEN p.is_correct = 1 THEN 1 ELSE 0 END) as correct_predictions
|
||||
FROM users u
|
||||
LEFT JOIN predictions p ON u.id = p.user_id
|
||||
WHERE u.role = 'user'
|
||||
GROUP BY u.id
|
||||
ORDER BY u.points DESC, correct_predictions DESC
|
||||
LIMIT 50
|
||||
");
|
||||
|
||||
$leaderboard = [];
|
||||
$rank = 1;
|
||||
while ($row = $stmt->fetch()) {
|
||||
$leaderboard[] = [
|
||||
'rank' => $rank++,
|
||||
'user_id' => $row['id'],
|
||||
'username' => $row['username'],
|
||||
'points' => (int)$row['points'],
|
||||
'total_predictions' => (int)$row['total_predictions'],
|
||||
'correct_predictions' => (int)$row['correct_predictions']
|
||||
];
|
||||
}
|
||||
|
||||
jsonResponse(['success' => true, 'leaderboard' => $leaderboard]);
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
require_once 'config.php';
|
||||
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
|
||||
// Vérifier les droits admin
|
||||
$user = requireAdmin();
|
||||
|
||||
if ($method !== 'POST') {
|
||||
jsonResponse(['error' => 'Méthode non autorisée'], 405);
|
||||
}
|
||||
|
||||
$data = getJsonInput();
|
||||
|
||||
if (!isset($data['match_id']) || !isset($data['winner_id']) || !isset($data['score'])) {
|
||||
jsonResponse(['error' => 'match_id, winner_id et score requis'], 400);
|
||||
}
|
||||
|
||||
$db = getDB();
|
||||
|
||||
// Vérifier que le match existe
|
||||
$stmt = $db->prepare("SELECT id, player1_id, player2_id, status FROM matches WHERE id = ?");
|
||||
$stmt->execute([$data['match_id']]);
|
||||
$match = $stmt->fetch();
|
||||
|
||||
if (!$match) {
|
||||
jsonResponse(['error' => 'Match non trouvé'], 404);
|
||||
}
|
||||
|
||||
if ($match['status'] === 'completed') {
|
||||
jsonResponse(['error' => 'Ce match a déjà un résultat'], 400);
|
||||
}
|
||||
|
||||
// Vérifier que le gagnant est l'un des deux joueurs
|
||||
if ($data['winner_id'] != $match['player1_id'] && $data['winner_id'] != $match['player2_id']) {
|
||||
jsonResponse(['error' => 'Le gagnant doit être l\'un des deux joueurs du match'], 400);
|
||||
}
|
||||
|
||||
$db->beginTransaction();
|
||||
|
||||
try {
|
||||
// Mettre à jour le match
|
||||
$stmt = $db->prepare("
|
||||
UPDATE matches
|
||||
SET status = 'completed', winner_id = ?, score = ?
|
||||
WHERE id = ?
|
||||
");
|
||||
$stmt->execute([$data['winner_id'], $data['score'], $data['match_id']]);
|
||||
|
||||
// Mettre à jour les pronostics
|
||||
$stmt = $db->prepare("
|
||||
UPDATE predictions
|
||||
SET is_correct = CASE
|
||||
WHEN predicted_winner_id = ? THEN 1
|
||||
ELSE 0
|
||||
END
|
||||
WHERE match_id = ?
|
||||
");
|
||||
$stmt->execute([$data['winner_id'], $data['match_id']]);
|
||||
|
||||
// Ajouter les points bonus pour les pronostics corrects
|
||||
$stmt = $db->prepare("
|
||||
UPDATE users u
|
||||
JOIN predictions p ON u.id = p.user_id
|
||||
SET u.points = u.points + ?
|
||||
WHERE p.match_id = ? AND p.predicted_winner_id = ?
|
||||
");
|
||||
$stmt->execute([POINTS_CORRECT_PREDICTION, $data['match_id'], $data['winner_id']]);
|
||||
|
||||
$db->commit();
|
||||
|
||||
// Compter les pronostics corrects
|
||||
$stmt = $db->prepare("
|
||||
SELECT COUNT(*) as correct_count
|
||||
FROM predictions
|
||||
WHERE match_id = ? AND predicted_winner_id = ?
|
||||
");
|
||||
$stmt->execute([$data['match_id'], $data['winner_id']]);
|
||||
$correctCount = $stmt->fetch()['correct_count'];
|
||||
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'message' => 'Résultat enregistré avec succès',
|
||||
'correct_predictions' => (int)$correctCount,
|
||||
'points_distributed' => $correctCount * POINTS_CORRECT_PREDICTION
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
$db->rollBack();
|
||||
jsonResponse(['error' => 'Erreur lors de l\'enregistrement du résultat: ' . $e->getMessage()], 500);
|
||||
}
|
||||
?>
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
require_once 'config.php';
|
||||
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
$action = $_GET['action'] ?? '';
|
||||
$id = $_GET['id'] ?? null;
|
||||
|
||||
// Vérifier les droits admin
|
||||
$user = requireAdmin();
|
||||
|
||||
switch ($method) {
|
||||
case 'GET':
|
||||
if ($id) {
|
||||
getUser($id);
|
||||
} else {
|
||||
getAllUsers();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'PUT':
|
||||
updateUser($id);
|
||||
break;
|
||||
|
||||
case 'DELETE':
|
||||
deleteUser($id);
|
||||
break;
|
||||
|
||||
default:
|
||||
jsonResponse(['error' => 'Méthode non autorisée'], 405);
|
||||
}
|
||||
|
||||
function getAllUsers() {
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->query("
|
||||
SELECT u.id, u.username, u.email, u.role, u.points, u.created_at,
|
||||
COUNT(p.id) as total_predictions,
|
||||
SUM(CASE WHEN p.is_correct = 1 THEN 1 ELSE 0 END) as correct_predictions
|
||||
FROM users u
|
||||
LEFT JOIN predictions p ON u.id = p.user_id
|
||||
GROUP BY u.id
|
||||
ORDER BY u.created_at DESC
|
||||
");
|
||||
|
||||
$users = [];
|
||||
while ($row = $stmt->fetch()) {
|
||||
$users[] = [
|
||||
'id' => $row['id'],
|
||||
'username' => $row['username'],
|
||||
'email' => $row['email'],
|
||||
'role' => $row['role'],
|
||||
'points' => (int)$row['points'],
|
||||
'created_at' => $row['created_at'],
|
||||
'total_predictions' => (int)$row['total_predictions'],
|
||||
'correct_predictions' => (int)$row['correct_predictions']
|
||||
];
|
||||
}
|
||||
|
||||
jsonResponse(['success' => true, 'users' => $users]);
|
||||
}
|
||||
|
||||
function getUser($id) {
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->prepare("
|
||||
SELECT u.id, u.username, u.email, u.role, u.points, u.created_at,
|
||||
COUNT(p.id) as total_predictions,
|
||||
SUM(CASE WHEN p.is_correct = 1 THEN 1 ELSE 0 END) as correct_predictions
|
||||
FROM users u
|
||||
LEFT JOIN predictions p ON u.id = p.user_id
|
||||
WHERE u.id = ?
|
||||
GROUP BY u.id
|
||||
");
|
||||
$stmt->execute([$id]);
|
||||
$user = $stmt->fetch();
|
||||
|
||||
if (!$user) {
|
||||
jsonResponse(['error' => 'Utilisateur non trouvé'], 404);
|
||||
}
|
||||
|
||||
jsonResponse(['success' => true, 'user' => $user]);
|
||||
}
|
||||
|
||||
function updateUser($id) {
|
||||
$data = getJsonInput();
|
||||
$db = getDB();
|
||||
|
||||
$stmt = $db->prepare("SELECT id, role FROM users WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
$targetUser = $stmt->fetch();
|
||||
|
||||
if (!$targetUser) {
|
||||
jsonResponse(['error' => 'Utilisateur non trouvé'], 404);
|
||||
}
|
||||
|
||||
$fields = [];
|
||||
$values = [];
|
||||
|
||||
$allowedFields = ['role', 'points'];
|
||||
|
||||
foreach ($allowedFields as $field) {
|
||||
if (isset($data[$field])) {
|
||||
$fields[] = "$field = ?";
|
||||
$values[] = $data[$field];
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($fields)) {
|
||||
jsonResponse(['error' => 'Aucune donnée à mettre à jour'], 400);
|
||||
}
|
||||
|
||||
$values[] = $id;
|
||||
$stmt = $db->prepare("UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?");
|
||||
$stmt->execute($values);
|
||||
|
||||
jsonResponse(['success' => true, 'message' => 'Utilisateur mis à jour avec succès']);
|
||||
}
|
||||
|
||||
function deleteUser($id) {
|
||||
$db = getDB();
|
||||
|
||||
// Empêcher la suppression de soi-même
|
||||
global $user;
|
||||
if ($user['id'] == $id) {
|
||||
jsonResponse(['error' => 'Vous ne pouvez pas supprimer votre propre compte'], 400);
|
||||
}
|
||||
|
||||
$stmt = $db->prepare("DELETE FROM users WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
|
||||
if ($stmt->rowCount() === 0) {
|
||||
jsonResponse(['error' => 'Utilisateur non trouvé'], 404);
|
||||
}
|
||||
|
||||
jsonResponse(['success' => true, 'message' => 'Utilisateur supprimé avec succès']);
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user