83 lines
2.5 KiB
PHP
83 lines
2.5 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
require_once 'db/config.php';
|
|
|
|
$response = [
|
|
'status' => 'error',
|
|
'message' => 'Invalid request.'
|
|
];
|
|
|
|
// Get the posted data
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!$data) {
|
|
echo json_encode($response);
|
|
exit();
|
|
}
|
|
|
|
// Basic validation
|
|
$session_code = $data['sessionCode'] ?? null;
|
|
$track_title = $data['title'] ?? null;
|
|
$artist_name = $data['artist'] ?? null;
|
|
$album_art_url = $data['albumArt'] ?? null;
|
|
$source = $data['source'] ?? null;
|
|
|
|
if (!$session_code || !$track_title || !$artist_name) {
|
|
$response['message'] = 'Missing required song data.';
|
|
echo json_encode($response);
|
|
exit();
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
// 1. Get session ID from session code
|
|
$stmt = $pdo->prepare("SELECT id FROM sessions WHERE session_code = ? AND status = 'active'");
|
|
$stmt->execute([$session_code]);
|
|
$session = $stmt->fetch();
|
|
|
|
if (!$session) {
|
|
$response['message'] = 'Invalid or inactive session.';
|
|
echo json_encode($response);
|
|
exit();
|
|
}
|
|
$session_id = $session['id'];
|
|
|
|
// 2. Check for duplicates
|
|
$stmt = $pdo->prepare("SELECT id FROM queue_items WHERE session_id = ? AND track_title = ? AND artist_name = ?");
|
|
$stmt->execute([$session_id, $track_title, $artist_name]);
|
|
if ($stmt->fetch()) {
|
|
$response['message'] = 'This song is already in the queue.';
|
|
echo json_encode($response);
|
|
exit();
|
|
}
|
|
|
|
// 3. Insert the new song
|
|
$sql = "INSERT INTO queue_items (session_id, track_title, artist_name, album_art_url, source, added_by) VALUES (?, ?, ?, ?, ?, ?)";
|
|
$stmt = $pdo->prepare($sql);
|
|
|
|
// For now, added_by is anonymous. This can be updated later with user profiles.
|
|
$added_by = 'Guest';
|
|
|
|
if ($stmt->execute([$session_id, $track_title, $artist_name, $album_art_url, $source, $added_by])) {
|
|
$new_song_id = $pdo->lastInsertId();
|
|
|
|
// Fetch the newly added song to return to the client
|
|
$stmt = $pdo->prepare("SELECT * FROM queue_items WHERE id = ?");
|
|
$stmt->execute([$new_song_id]);
|
|
$new_song_data = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
$response['status'] = 'success';
|
|
$response['message'] = 'Song added successfully!';
|
|
$response['data'] = $new_song_data;
|
|
} else {
|
|
$response['message'] = 'Failed to add song to the database.';
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
// In a real app, log this error instead of exposing it.
|
|
$response['message'] = 'Database error: ' . $e->getMessage();
|
|
}
|
|
|
|
echo json_encode($response);
|