document.addEventListener('DOMContentLoaded', async () => { try { const token = localStorage.getItem('token'); if (!token) { window.location.href = '/login.html'; return; } const response = await fetch('/api/cart', { headers: { 'Authorization': `Bearer ${token}` } }); if (!response.ok) throw new Error('Błąd ładowania koszyka'); const cartItems = await response.json(); const container = document.getElementById('cart-items'); container.innerHTML = ''; if (cartItems.length === 0) { container.innerHTML = '

Twój koszyk jest pusty

'; return; } let totalCartValue = 0; cartItems.forEach(item => { // Formatowanie cen const price = parseFloat(item.cena); const formattedPrice = price.toFixed(2); const itemTotal = price * item.quantity; const formattedTotal = itemTotal.toFixed(2); totalCartValue += itemTotal; const itemHTML = `
${item.tytul}
${item.tytul}

${item.autor}

Cena jednostkowa ${formattedPrice} PLN
Ilość
${item.quantity}
Suma ${formattedTotal} PLN
`; container.insertAdjacentHTML('beforeend', itemHTML); }); // Dodaj całkowitą sumę koszyka const totalHTML = `

Suma całkowita

${totalCartValue.toFixed(2)} PLN

`; container.insertAdjacentHTML('beforeend', totalHTML); // Obsługa przycisku zmniejszania ilości document.querySelectorAll('.decrease-quantity').forEach(button => { button.addEventListener('click', function() { const bookId = this.getAttribute('data-book-id'); updateCartItemQuantity(bookId, 'decrease'); }); }); // Obsługa przycisku usuwania document.querySelectorAll('.remove-from-cart').forEach(button => { button.addEventListener('click', function() { const bookId = this.getAttribute('data-book-id'); updateCartItemQuantity(bookId, 'remove'); }); }); } catch (error) { console.error('Error:', error); alert('Nie udało się załadować koszyka'); } }); async function updateCartItemQuantity(bookId, action) { try { const token = localStorage.getItem('token'); if (!token) { window.location.href = '/login.html'; return; } let endpoint, method; if (action === 'decrease') { endpoint = `/api/decrease-cart-item/${bookId}`; method = 'POST'; } else if (action === 'remove') { endpoint = `/api/remove-from-cart/${bookId}`; method = 'DELETE'; } else { throw new Error('Nieznana akcja'); } const response = await fetch(endpoint, { method: method, headers: { 'Authorization': `Bearer ${token}` } }); if (!response.ok) throw new Error('Błąd aktualizacji koszyka'); // Odśwież koszyk location.reload(); } catch (error) { console.error('Error:', error); alert('Nie udało się zaktualizować koszyka'); } } async function removeFromCart(bookId) { try { const token = localStorage.getItem('token'); if (!token) { window.location.href = '/login.html'; return; } const response = await fetch(`/api/remove-from-cart/${bookId}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` } }); if (!response.ok) throw new Error('Błąd usuwania z koszyka'); // Odśwież koszyk location.reload(); } catch (error) { console.error('Error:', error); alert('Nie udało się usunąć z koszyka'); } } document.getElementById('checkoutBtn').addEventListener('click', async () => { try { const token = localStorage.getItem('token'); if (!token) { window.location.href = '/login.html'; return; } // Pobierz aktualną zawartość koszyka const cartResponse = await fetch('/api/cart', { headers: { 'Authorization': `Bearer ${token}` } }); const cartItems = await cartResponse.json(); // Przygotuj dane do zamówienia const checkoutData = { items: cartItems.map(item => ({ book_id: item.book_id, quantity: item.quantity })), total: cartItems.reduce((sum, item) => sum + (parseFloat(item.cena) * item.quantity), 0) }; // Wyślij zamówienie const response = await fetch('/api/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify(checkoutData) }); if (!response.ok) throw new Error('Błąd podczas składania zamówienia'); window.location.href = '/thankyou.html'; } catch (error) { console.error('Error:', error); alert('Nie udało się złożyć zamówienia: ' + error.message); } });