34705-vm/api/add_favorite.php
Flatlogic Bot 2587a17d37 basic2
2025-10-06 00:19:27 +00:00

59 lines
1.8 KiB
PHP

<?php
require_once __DIR__ . '/../db/config.php';
session_start();
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['status' => 'error', 'message' => 'You must be logged in to add favorites.']);
exit;
}
$userId = $_SESSION['user_id'];
$playerData = json_decode(file_get_contents('php://input'), true);
if (!$playerData || !isset($playerData['idPlayer'])) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid player data.']);
exit;
}
$playerId = $playerData['idPlayer'];
try {
$pdo = db();
$pdo->beginTransaction();
// 1. Insert/update player in the main players table
$stmt = $pdo->prepare(
'INSERT INTO players (id, name, team, sport, image_url) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name = VALUES(name);'
);
$stmt->execute([
$playerId,
$playerData['strPlayer'],
$playerData['strTeam'],
$playerData['strSport'],
$playerData['strCutout']
]);
// 2. Add to user_favorites (ignore if already exists)
$stmt = $pdo->prepare('INSERT IGNORE INTO user_favorites (user_id, player_id) VALUES (?, ?)');
$stmt->execute([$userId, $playerId]);
// 3. Increment the popular player count
$stmt = $pdo->prepare(
'INSERT INTO player_favorites (player_id, favorite_count) VALUES (?, 1) ON DUPLICATE KEY UPDATE favorite_count = favorite_count + 1;'
);
$stmt->execute([$playerId]);
$pdo->commit();
echo json_encode(['status' => 'success', 'message' => 'Player added to favorites.']);
} catch (PDOException $e) {
$pdo->rollBack();
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}