-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
323 lines (272 loc) · 10.9 KB
/
Copy pathscript.js
File metadata and controls
323 lines (272 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
document.addEventListener("DOMContentLoaded", () => {
/* -------------------- Navbar Mobile Menu -------------------- */
const menuOpenButton = document.querySelector("#menu-open-button");
const menuCloseButton = document.querySelector("#menu-close-button");
if (menuOpenButton && menuCloseButton) {
menuOpenButton.addEventListener("click", () => {
document.body.classList.toggle("show-mobile-menu");
});
menuCloseButton.addEventListener("click", () => {
document.body.classList.remove("show-mobile-menu");
});
}
/* -------------------- Reviews Slider -------------------- */
const sliderWrapper = document.querySelector(".slider-wrapper");
const leftBtn = document.querySelector(".left-btn");
const rightBtn = document.querySelector(".right-btn");
if (sliderWrapper && leftBtn && rightBtn) {
let currentIndex = 0;
function updateSlider() {
const offset = currentIndex * -320; // Adjust based on your CSS width and margin
sliderWrapper.style.transform = `translateX(${offset}px)`;
}
leftBtn.addEventListener("click", () => {
currentIndex = Math.max(0, currentIndex - 1);
updateSlider();
});
rightBtn.addEventListener("click", () => {
const reviewCount = document.querySelectorAll(".review").length;
currentIndex = Math.min(reviewCount - 1, currentIndex + 1);
updateSlider();
});
}
/* -------------------- Cart Functionality -------------------- */
const cart = [];
const cartCount = document.getElementById("cart-count");
const cartContainer = document.getElementById("cart-container");
const totalPriceElement = document.getElementById("total-price");
const cartModal = document.getElementById("cart-modal");
const checkoutButton = document.getElementById("checkout-button");
const cartCloseButton = document.getElementById("cart-close-button"); // Çarpı butonunun id'si
document.getElementById("cart-link").addEventListener("click", (event) => {
event.preventDefault();
cartModal.classList.toggle("hidden");
});
if (cartCloseButton) {
cartCloseButton.addEventListener("click", () => {
cartModal.classList.add("hidden"); // Sepet modalını kapat
});
}
document.getElementById("product-list").addEventListener("click", (event) => {
if (event.target.classList.contains("add-to-cart")) {
const button = event.target;
const productCard = button.closest(".product");
if (!productCard) return;
const productId = button.getAttribute("data-id");
const productName = productCard.querySelector("h3").textContent;
const productPrice = parseFloat(
productCard.querySelector("span").textContent.replace("$", "")
);
const existingProduct = cart.find((item) => item.id === productId);
if (existingProduct) {
existingProduct.quantity += 1;
} else {
cart.push({ id: productId, name: productName, price: productPrice, quantity: 1 });
}
updateCartUI();
}
});
function updateCartUI() {
const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
cartCount.textContent = totalItems;
cartCount.classList.toggle("hidden", totalItems === 0);
cartContainer.innerHTML = "";
let totalPrice = 0;
cart.forEach((item) => {
const cartItem = document.createElement("div");
cartItem.classList.add("cart-item");
cartItem.innerHTML = `<p>${item.name} x${item.quantity} - $${(item.price * item.quantity).toFixed(2)}</p>`;
cartContainer.appendChild(cartItem);
totalPrice += item.price * item.quantity;
});
totalPriceElement.textContent = totalPrice.toFixed(2);
}
if (checkoutButton) {
checkoutButton.addEventListener("click", async () => {
if (cart.length === 0) {
alert("Sepetiniz boş. Lütfen ürün ekleyin.");
return;
}
try {
const response = await fetch("http://localhost:3000/create-order", {
method: "POST", // POST metodu eklendi
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({
products: cart.map((item) => ({
product_id: item.id,
quantity: item.quantity,
price: item.price,
})),
total_price: cart.reduce((sum, item) => sum + item.price * item.quantity, 0),
status: "pending",
}),
});
if (response.ok) {
alert("Ödeme başarılı! Sipariş oluşturuldu.");
cart.length = 0;
updateCartUI();
} else {
alert("Sipariş oluşturulamadı. Lütfen tekrar deneyin.");
}
} catch (error) {
console.error("Hata:", error);
alert("Bir hata oluştu. Lütfen tekrar deneyin.");
}
});
}
// Çarpı butonunu hedefleyen event listener
const closeCartModal = document.getElementById("close-cart-modal");
if (closeCartModal) {
closeCartModal.addEventListener("click", () => {
const cartModal = document.getElementById("cart-modal");
if (cartModal) {
cartModal.classList.add("hidden"); // Sepet modalını kapatır
}
});
}
/* -------------------- Membership Modals -------------------- */
const signinModal = document.getElementById("signin-modal");
const signupModal = document.getElementById("signup-modal");
const closeSigninModal = document.getElementById("close-signin-modal");
const closeSignupModal = document.getElementById("close-signup-modal");
const membershipLink = document.getElementById("membership-link");
if (membershipLink && signinModal && closeSigninModal && closeSignupModal) {
membershipLink.addEventListener("click", () => signinModal.classList.remove("hidden"));
closeSigninModal.addEventListener("click", () => signinModal.classList.add("hidden"));
closeSignupModal.addEventListener("click", () => signupModal.classList.add("hidden"));
document.getElementById("open-signup-modal").addEventListener("click", () => {
signinModal.classList.add("hidden");
signupModal.classList.remove("hidden");
});
}
//Sign in
document.getElementById("signin-form").addEventListener("submit", async (e) => {
e.preventDefault();
const email = document.getElementById("signin-email").value.trim();
const password = document.getElementById("signin-password").value.trim();
if (!email || !password) {
alert("Email ve şifre boş bırakılamaz.");
return;
}
try {
const response = await fetch("http://localhost:3000/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
});
if (response.ok) {
const data = await response.json();
localStorage.setItem("token", data.token); // Token'ı sakla
localStorage.setItem("userName", `${data.firstName} ${data.lastName}`); // Adı ve soyadı sakla
alert("Giriş başarılı!");
document.getElementById("signin-modal").classList.add("hidden");
updateMembershipName();
} else {
const error = await response.json();
alert(error.message || "Giriş başarısız.");
}
} catch (error) {
console.error("Giriş hatası:", error);
alert("Bir hata oluştu. Lütfen tekrar deneyin.");
}
});
// Kullanıcı adını Membership alanında güncelleme
function updateMembershipName() {
const userName = localStorage.getItem("userName");
const membershipText = document.getElementById("membership-text");
if (userName && membershipText) {
membershipText.textContent = `Welcome, ${userName}`;
}
}
// Sayfa yüklendiğinde Membership adını güncelle
document.addEventListener("DOMContentLoaded", updateMembershipName);
//Sign Up
document.getElementById("signup-form").addEventListener("submit", async (e) => {
e.preventDefault();
const firstName = document.getElementById("signup-firstname").value.trim();
const lastName = document.getElementById("signup-lastname").value.trim();
const email = document.getElementById("signup-email").value.trim();
const password = document.getElementById("signup-password").value.trim();
if (!firstName || !lastName || !email || !password) {
alert("Tüm alanları doldurun.");
return;
}
try {
const response = await fetch("http://localhost:3000/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ firstName, lastName, email, password }),
});
if (response.ok) {
alert("Kayıt başarılı!");
document.getElementById("signup-modal").classList.add("hidden"); // Modalı kapat
document.getElementById("signin-modal").classList.remove("hidden"); // Giriş modalını aç
} else {
const error = await response.json();
alert(error.message || "Kayıt başarısız.");
}
} catch (error) {
console.error("Kayıt hatası:", error);
alert("Bir hata oluştu. Lütfen tekrar deneyin.");
}
});
/* -------------------- Fetch Categories and Products -------------------- */
async function fetchCategories() {
try {
const response = await fetch("http://localhost:3000/categories");
const categories = await response.json();
displayCategories(categories);
} catch (error) {
console.error("Kategoriler alınırken hata oluştu:", error);
}
}
function displayCategories(categories) {
const categoryList = document.getElementById("category-list");
categoryList.innerHTML = "";
categories.forEach((category) => {
const categoryButton = document.createElement("button");
categoryButton.textContent = category.name;
categoryButton.onclick = () => fetchProducts(category.id);
categoryList.appendChild(categoryButton);
});
}
async function fetchProducts(categoryId) {
try {
const response = await fetch(`http://localhost:3000/products/${categoryId}`);
const products = await response.json();
displayProducts(products);
} catch (error) {
console.error("Ürünler alınırken hata oluştu:", error);
}
}
function displayProducts(products) {
const productList = document.getElementById("product-list");
productList.innerHTML = "";
products.forEach((product) => {
const productDiv = document.createElement("div");
productDiv.classList.add("product");
productDiv.innerHTML = `
<img src="${product.image}" alt="${product.name}">
<h3>${product.name}</h3>
<p>${product.description}</p>
<span>$${product.price}</span>
<button class="add-to-cart" data-id="${product.id}">Add to Cart</button>
`;
productList.appendChild(productDiv);
});
}
// Sayfa yüklendiğinde varsayılan kategori ürünlerini getir
document.addEventListener("DOMContentLoaded", () => {
const defaultCategoryId = 1;
fetchProducts(defaultCategoryId);
});
// Sayfa yüklendiğinde kategorileri al
window.onload = fetchCategories;
});