This commit is contained in:
Flatlogic Bot 2025-10-24 11:33:18 +00:00
parent 008dda1d41
commit b4250586c9
3 changed files with 138 additions and 103 deletions

View File

@ -4,6 +4,29 @@ header('Content-Type: application/json');
$response = ['success' => false, 'error' => 'Invalid request']; $response = ['success' => false, 'error' => 'Invalid request'];
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (isset($_GET['lineup_id']) && is_numeric($_GET['lineup_id'])) {
try {
$lineup_id = intval($_GET['lineup_id']);
$pdo = db();
$stmt = $pdo->prepare("
SELECT s.*, ls.song_order FROM songs s
JOIN lineup_songs ls ON s.id = ls.song_id
WHERE ls.lineup_id = ?
ORDER BY ls.song_order ASC
");
$stmt->execute([$lineup_id]);
$songs = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($songs);
exit;
} catch (PDOException $e) {
$response['error'] = 'Database error: ' . $e->getMessage();
}
} else {
$response['error'] = 'Lineup ID is required.';
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);

View File

@ -1,118 +1,130 @@
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function () {
const lineupId = document.getElementById('lineup-id').value; const lineupId = new URLSearchParams(window.location.search).get('id');
const searchInput = document.getElementById('song-search-input'); const songSearchInput = document.getElementById('song-search-input');
const searchResultsContainer = document.getElementById('search-results'); const searchResultsContainer = document.getElementById('search-results');
const lineupSongList = document.getElementById('lineup-song-list'); const lineupSongsContainer = document.getElementById('lineup-song-list');
// 1. Search for songs // Function to fetch and display songs already in the lineup
searchInput.addEventListener('keyup', function () { function fetchLineupSongs() {
const query = this.value; if (!lineupId) return;
fetch(`/api/lineups_api.php?lineup_id=${lineupId}`)
.then(response => response.json())
.then(data => {
renderLineupSongs(data);
})
.catch(error => console.error('Error fetching lineup songs:', error));
}
if (query.length < 2) { // Function to render the list of songs in the lineup
searchResultsContainer.innerHTML = ''; function renderLineupSongs(songs) {
lineupSongsContainer.innerHTML = '';
if (songs.length === 0) {
lineupSongsContainer.innerHTML = '<p>אין עדיין שירים בליינאפ זה.</p>';
return; return;
} }
const list = document.createElement('ul');
list.className = 'list-group';
songs.forEach(song => {
const listItem = document.createElement('li');
listItem.className = 'list-group-item d-flex justify-content-between align-items-center';
listItem.textContent = `${song.artist || 'Unknown Artist'} - ${song.name}`;
fetch('api/search_songs.php', { const removeBtn = document.createElement('button');
removeBtn.className = 'btn btn-danger btn-sm';
removeBtn.textContent = 'הסר';
removeBtn.onclick = () => removeSongFromLineup(song.id); // Use song.id from the songs table
listItem.appendChild(removeBtn);
list.appendChild(listItem);
});
lineupSongsContainer.appendChild(list);
}
// Function to search for songs
function searchSongs(query) {
fetch(`/api/search_songs.php?q=${encodeURIComponent(query)}`)
.then(response => response.json())
.then(data => {
renderSearchResults(data);
})
.catch(error => console.error('Error searching songs:', error));
}
// Function to render search results
function renderSearchResults(songs) {
searchResultsContainer.innerHTML = '';
if (songs.length === 0) {
searchResultsContainer.innerHTML = '<p>לא נמצאו שירים.</p>';
return;
}
const list = document.createElement('ul');
list.className = 'list-group';
songs.forEach(song => {
const listItem = document.createElement('li');
listItem.className = 'list-group-item d-flex justify-content-between align-items-center';
listItem.textContent = `${song.artist || 'Unknown Artist'} - ${song.name}`;
const addBtn = document.createElement('button');
addBtn.className = 'btn btn-primary btn-sm';
addBtn.textContent = 'הוסף';
addBtn.onclick = () => addSongToLineup(song.id);
listItem.appendChild(addBtn);
list.appendChild(listItem);
});
searchResultsContainer.appendChild(list);
}
// Function to add a song to the lineup
function addSongToLineup(songId) {
fetch('/api/add_song_to_lineup.php', {
method: 'POST', method: 'POST',
headers: { headers: { 'Content-Type': 'application/json' },
'Content-Type': 'application/x-www-form-urlencoded', body: JSON.stringify({ lineup_id: lineupId, song_id: songId })
}, })
body: `query=${encodeURIComponent(query)}&lineup_id=${lineupId}` .then(response => response.json().then(data => ({ status: response.status, body: data })))
.then(({ status, body }) => {
if (status === 200 && body.success) {
fetchLineupSongs(); // Refresh the lineup list
const currentQuery = searchInput.value.trim();
searchSongs(currentQuery); // Refresh search results to remove the added song
} else {
// Use the specific message from the server, or a default one
alert(body.message || 'לא ניתן היה להוסיף את השיר.');
}
})
.catch(error => console.error('Error adding song:', error));
}
// Function to remove a song from the lineup
function removeSongFromLineup(songId) {
fetch('/api/remove_song_from_lineup.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ lineup_id: lineupId, song_id: songId })
}) })
.then(response => response.json()) .then(response => response.json())
.then(songs => { .then(data => {
searchResultsContainer.innerHTML = ''; if (data.success) {
if (songs.length > 0) { fetchLineupSongs(); // Refresh the lineup list
const list = document.createElement('ul'); const currentQuery = searchInput.value.trim();
list.className = 'list-group'; searchSongs(currentQuery); // Refresh search results to show the removed song
songs.forEach(song => {
const listItem = document.createElement('li');
listItem.className = 'list-group-item d-flex justify-content-between align-items-center';
listItem.innerHTML = `
<span><strong>${song.artist}</strong> - ${song.name}</span>
<button class="btn btn-sm btn-primary add-song-btn" data-song-id="${song.id}">הוסף</button>
`;
list.appendChild(listItem);
});
searchResultsContainer.appendChild(list);
} else { } else {
searchResultsContainer.innerHTML = '<p class="text-muted">לא נמצאו שירים תואמים.</p>'; alert('Failed to remove song: ' + (data.error || 'Unknown error'));
} }
}) })
.catch(error => { .catch(error => console.error('Error removing song:', error));
console.error('Error searching for songs:', error); }
searchResultsContainer.innerHTML = '<p class="text-danger">אירעה שגיאה בחיפוש.</p>';
});
});
// 2. Add a song to the lineup // Initial fetch of lineup songs and all songs for searching
searchResultsContainer.addEventListener('click', function (e) { if (lineupId) {
if (e.target && e.target.classList.contains('add-song-btn')) { fetchLineupSongs();
const songId = e.target.dataset.songId; searchSongs(''); // Load all songs initially
}
fetch('api/add_song_to_lineup.php', { // Event Listener for the search input
method: 'POST', searchInput.addEventListener('input', () => {
headers: { const query = searchInput.value.trim();
'Content-Type': 'application/x-www-form-urlencoded', searchSongs(query);
},
body: `song_id=${songId}&lineup_id=${lineupId}`
})
.then(response => response.json())
.then(result => {
if (result.success) {
// Reload the page to see the updated list. It's simple and reliable.
location.reload();
} else {
alert('ההוספה נכשלה: ' + (result.message || 'שגיאה לא ידועה'));
}
})
.catch(error => {
console.error('Error adding song:', error);
alert('אירעה שגיאה קריטית בעת ההוספה.');
});
}
});
// 3. Remove a song from the lineup
lineupSongList.addEventListener('click', function (e) {
if (e.target && e.target.classList.contains('remove-song-btn')) {
const songId = e.target.dataset.songId;
if (!confirm('האם אתה בטוח שברצונך להסיר את השיר הזה?')) {
return;
}
fetch('api/remove_song_from_lineup.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `song_id=${songId}&lineup_id=${lineupId}`
})
.then(response => response.json())
.then(result => {
if (result.success) {
// Remove the song from the list in the UI
e.target.closest('li.list-group-item').remove();
// If the list is now empty, show the "empty" message
if (lineupSongList.children.length === 0) {
const emptyMessage = document.createElement('li');
emptyMessage.id = 'empty-lineup-message';
emptyMessage.className = 'list-group-item text-center text-muted';
emptyMessage.textContent = 'אין עדיין שירים בליינאפ זה.';
lineupSongList.appendChild(emptyMessage);
}
} else {
alert('ההסרה נכשלה: ' + (result.message || 'שגיאה לא ידועה'));
}
})
.catch(error => {
console.error('Error removing song:', error);
alert('אירעה שגיאה קריטית בעת ההסרה.');
});
}
}); });
}); });

View File

@ -50,7 +50,7 @@ $songs = $songs_stmt->fetchAll(PDO::FETCH_ASSOC);
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<div class="mb-3"> <div class="mb-3">
<label for="song-search-input" class="form-label">חפש שיר</label> <label for="search-song-input" class="form-label">חפש שיר</label>
<input type="text" class="form-control" id="song-search-input" placeholder="הקלד שם שיר או אמן..."> <input type="text" class="form-control" id="song-search-input" placeholder="הקלד שם שיר או אמן...">
</div> </div>
<div id="search-results" style="max-height: 300px; overflow-y: auto;"> <div id="search-results" style="max-height: 300px; overflow-y: auto;">