260 lines
8.6 KiB
JavaScript
260 lines
8.6 KiB
JavaScript
document.addEventListener('DOMContentLoaded', () => {
|
|
updateNavVisibility();
|
|
checkAuthStatus();
|
|
});
|
|
|
|
function updateNavVisibility() {
|
|
const token = localStorage.getItem('token');
|
|
document.querySelectorAll('.anonymous-links, .user-links').forEach(el => {
|
|
el.style.display = 'none';
|
|
});
|
|
|
|
if (token) {
|
|
document.querySelector('.user-links').style.display = 'flex';
|
|
} else {
|
|
document.querySelector('.anonymous-links').style.display = 'flex';
|
|
}
|
|
}
|
|
|
|
async function checkAuthStatus() {
|
|
try {
|
|
const response = await fetch('/api/check-auth');
|
|
const data = await response.json();
|
|
|
|
if (data.authenticated) {
|
|
localStorage.setItem('token', data.token);
|
|
localStorage.setItem('imie', data.user.imie);
|
|
updateNavVisibility();
|
|
}
|
|
} catch (error) {
|
|
console.error('Błąd sprawdzania autentykacji:', error);
|
|
}
|
|
}
|
|
|
|
document.getElementById('logoutLink')?.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
localStorage.removeItem('token');
|
|
localStorage.removeItem('imie');
|
|
updateNavVisibility();
|
|
window.location.href = '/';
|
|
});
|
|
|
|
document.getElementById('loginForm')?.addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const email = document.getElementById('loginEmail').value;
|
|
const password = document.getElementById('loginPassword').value;
|
|
|
|
try {
|
|
const response = await fetch('/login', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ email, haslo: password }),
|
|
});
|
|
|
|
const data = await response.json();
|
|
if (response.ok) {
|
|
localStorage.setItem('token', data.token);
|
|
localStorage.setItem('imie', data.imie);
|
|
updateNavVisibility();
|
|
window.location.href = '/';
|
|
} else {
|
|
alert(data.message || 'Logowanie nieudane');
|
|
}
|
|
} catch (error) {
|
|
console.error('Błąd logowania:', error);
|
|
alert('Wystąpił błąd podczas logowania');
|
|
}
|
|
});
|
|
|
|
document.getElementById('registerForm')?.addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const name = document.getElementById('registerName').value;
|
|
const email = document.getElementById('registerEmail').value;
|
|
const password = document.getElementById('registerPassword').value;
|
|
const confirmPassword = document.getElementById('registerConfirmPassword').value;
|
|
|
|
if (password !== confirmPassword) {
|
|
alert('Hasła nie są identyczne');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch('/rejestracja', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ imie: name, email, haslo: password, confirmPassword }),
|
|
});
|
|
|
|
if (response.ok) {
|
|
alert('Rejestracja udana');
|
|
window.location.href = '/login.html';
|
|
} else {
|
|
const data = await response.text();
|
|
alert(data || 'Rejestracja nieudana');
|
|
}
|
|
} catch (error) {
|
|
console.error('Błąd rejestracji:', error);
|
|
alert('Wystąpił błąd podczas rejestracji');
|
|
}
|
|
});
|
|
|
|
async function loadBooks(searchTerm = '', sortBy = 'default') {
|
|
try {
|
|
const response = await fetch(`/api/ksiazki?search=${encodeURIComponent(searchTerm)}&sort=${sortBy}`);
|
|
if (!response.ok) throw new Error(`Błąd HTTP: ${response.status}`);
|
|
const books = await response.json();
|
|
renderBooks(books);
|
|
} catch (error) {
|
|
console.error('Błąd ładowania książek:', error);
|
|
showError('Wystąpił błąd podczas ładowania książek');
|
|
}
|
|
}
|
|
|
|
function renderBooks(books) {
|
|
const container = document.getElementById('books-container');
|
|
if (!container) return;
|
|
|
|
if (books.length === 0) {
|
|
container.innerHTML = `
|
|
<div class="col-12 text-center py-5">
|
|
<h3>Nie znaleziono książek</h3>
|
|
</div>
|
|
`;
|
|
return;
|
|
}
|
|
|
|
container.innerHTML = books.map(book => `
|
|
<div class="col-md-4 mb-4">
|
|
<div class="book-card card h-100">
|
|
<a href="/book.html?id=${book.id}" class="book-link">
|
|
<div class="book-cover">
|
|
<img src="${book.obraz_url}"
|
|
class="card-img-top"
|
|
alt="${book.tytul}"
|
|
onerror="this.src='/images/placeholder.jpg'">
|
|
<div class="book-overlay">
|
|
<h5 class="book-title">${book.tytul}</h5>
|
|
</div>
|
|
</div>
|
|
</a>
|
|
<div class="card-body">
|
|
<h5 class="card-title">${book.tytul}</h5>
|
|
<p class="card-text">${book.autor}</p>
|
|
<p class="card-text">${book.cena} PLN</p>
|
|
<button class="btn btn-gothic add-to-cart" data-book-id="${book.id}">Dodaj do koszyka</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`).join('');
|
|
|
|
// Dodaj obsługę przycisków "Dodaj do koszyka"
|
|
document.querySelectorAll('.add-to-cart').forEach(button => {
|
|
button.addEventListener('click', async (e) => {
|
|
e.preventDefault();
|
|
const token = localStorage.getItem('token');
|
|
if (!token) {
|
|
alert('Musisz być zalogowany, aby dodać książkę do koszyka');
|
|
window.location.href = '/login.html';
|
|
return;
|
|
}
|
|
|
|
const bookId = e.target.getAttribute('data-book-id');
|
|
|
|
try {
|
|
const response = await fetch('/api/add-to-cart', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${token}`
|
|
},
|
|
body: JSON.stringify({
|
|
book_id: parseInt(bookId),
|
|
quantity: 1
|
|
})
|
|
});
|
|
|
|
if (response.ok) {
|
|
alert('Dodano do koszyka!');
|
|
} else {
|
|
const error = await response.json();
|
|
alert(error.error || 'Wystąpił błąd');
|
|
}
|
|
} catch (error) {
|
|
console.error('Błąd:', error);
|
|
alert('Wystąpił błąd podczas dodawania do koszyka');
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function showError(message) {
|
|
const container = document.getElementById('books-container');
|
|
if (!container) return;
|
|
|
|
container.innerHTML = `
|
|
<div class="col-12 text-center py-5">
|
|
<div class="alert alert-danger">
|
|
${message}<br>
|
|
<button class="btn btn-gothic mt-3" onclick="location.reload()">
|
|
Spróbuj ponownie
|
|
</button>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
// Inicjalizacja przy pierwszym załadowaniu
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
if (document.getElementById('books-container')) {
|
|
loadBooks();
|
|
}
|
|
|
|
// Nasłuchiwanie wyszukiwania
|
|
document.getElementById('searchInput')?.addEventListener('input', (e) => {
|
|
loadBooks(e.target.value, document.getElementById('sortSelect')?.value || 'default');
|
|
});
|
|
|
|
// Nasłuchiwanie zmiany sortowania
|
|
document.getElementById('sortSelect')?.addEventListener('change', (e) => {
|
|
loadBooks(document.getElementById('searchInput')?.value || '', e.target.value);
|
|
});
|
|
});
|
|
|
|
function getAuthHeaders() {
|
|
const token = localStorage.getItem('token');
|
|
return {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': token ? `Bearer ${token}` : ''
|
|
};
|
|
}
|
|
|
|
async function updateNavbar() {
|
|
try {
|
|
const response = await fetch('/api/check-auth', {
|
|
headers: getAuthHeaders()
|
|
});
|
|
|
|
const authInfo = await response.json();
|
|
const userLinks = document.querySelector('.user-links');
|
|
const anonLinks = document.querySelector('.anonymous-links');
|
|
|
|
if (authInfo.authenticated) {
|
|
userLinks.style.display = 'flex';
|
|
anonLinks.style.display = 'none';
|
|
} else {
|
|
userLinks.style.display = 'none';
|
|
anonLinks.style.display = 'flex';
|
|
}
|
|
} catch (error) {
|
|
console.error('Error checking auth:', error);
|
|
}
|
|
}
|
|
|
|
// Wywołaj przy każdym załadowaniu strony
|
|
document.addEventListener('DOMContentLoaded', updateNavbar);
|
|
|
|
localStorage.setItem('token', response.token);
|