68 lines
2.5 KiB
JavaScript
68 lines
2.5 KiB
JavaScript
// static/js/book.js
|
|
|
|
import { getAuthHeaders, handleApiError } from './utils.js';
|
|
|
|
document.addEventListener('DOMContentLoaded', async () => {
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
const bookId = urlParams.get('id');
|
|
const bookDetails = document.getElementById('book-details');
|
|
|
|
if (!bookId) {
|
|
bookDetails.innerHTML = `
|
|
<div class="col-12 text-center py-5">
|
|
<h2 class="text-danger">Nieprawidłowe ID książki</h2>
|
|
<a href="/" class="btn mt-3">Powrót do strony głównej</a>
|
|
</div>
|
|
`;
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`/api/ksiazki/${bookId}`);
|
|
if (!response.ok) throw new Error(`Status: ${response.status}`);
|
|
const book = await response.json();
|
|
|
|
document.getElementById('book-title').textContent = book.tytul;
|
|
document.getElementById('book-author').textContent = `Autor: ${book.autor}`;
|
|
document.getElementById('book-price').textContent = `Cena: ${book.cena} PLN`;
|
|
document.getElementById('book-description').textContent = book.opis;
|
|
document.getElementById('book-cover').src = book.obraz_url;
|
|
|
|
// Dodaj do koszyka
|
|
document.querySelector('.btn-add-to-cart').addEventListener('click', async () => {
|
|
const token = localStorage.getItem('token');
|
|
if (!token) {
|
|
alert('Musisz być zalogowany, aby dodać książkę do koszyka');
|
|
window.location.href = '/login.html';
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch('/api/add-to-cart', {
|
|
method: 'POST',
|
|
headers: getAuthHeaders(),
|
|
body: JSON.stringify({
|
|
book_id: parseInt(bookId),
|
|
quantity: 1
|
|
})
|
|
});
|
|
|
|
if (response.ok) {
|
|
alert('Dodano do koszyka!');
|
|
} else {
|
|
throw new Error('Wystąpił błąd');
|
|
}
|
|
} catch (error) {
|
|
handleApiError(error);
|
|
}
|
|
});
|
|
} catch (error) {
|
|
bookDetails.innerHTML = `
|
|
<div class="col-12 text-center py-5">
|
|
<h2 class="text-danger">Błąd ładowania książki</h2>
|
|
<p>${error.message}</p>
|
|
<a href="/" class="btn mt-3">Powrót do strony głównej</a>
|
|
</div>
|
|
`;
|
|
}
|
|
});
|