-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
261 lines (237 loc) · 8.08 KB
/
script.js
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
// API Base URL
let API_URL = 'http://localhost:5037/api';
// Function to handle API errors
function handleError(error) {
console.error('Error:', error);
alert('An error occurred. Please try again.');
}
// Products API calls
async function getProducts() {
try {
const response = await fetch(`${API_URL}/products`);
const products = await response.json();
return products;
} catch (error) {
handleError(error);
return [];
}
}
async function getProduct(id) {
try {
const response = await fetch(`${API_URL}/products/${id}`);
const product = await response.json();
return product;
} catch (error) {
handleError(error);
return null;
}
}
// Categories API calls
async function getCategories() {
try {
const response = await fetch(`${API_URL}/categories`);
const categories = await response.json();
return categories;
} catch (error) {
handleError(error);
return [];
}
}
// Users API calls
async function login(email, password) {
try {
const response = await fetch(`${API_URL}/users`);
const users = await response.json();
const user = users.find(u => u.email === email && u.password === password);
if (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
return true;
}
return false;
} catch (error) {
handleError(error);
return false;
}
}
async function register(userData) {
try {
const response = await fetch(`${API_URL}/users`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const newUser = await response.json();
return newUser;
} catch (error) {
handleError(error);
return null;
}
}
// Orders API calls
async function createOrder(orderData) {
try {
const response = await fetch(`${API_URL}/orders`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(orderData)
});
const newOrder = await response.json();
return newOrder;
} catch (error) {
handleError(error);
return null;
}
}
async function createOrderDetails(orderDetailsData) {
try {
const response = await fetch(`${API_URL}/orderdetails`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(orderDetailsData)
});
const newOrderDetails = await response.json();
return newOrderDetails;
} catch (error) {
handleError(error);
return null;
}
}
// Cart functionality
let cart = JSON.parse(localStorage.getItem('cart')) || [];
function removeFromCart(productId) {
cart = cart.filter(item => item.productId !== productId);
localStorage.setItem('cart', JSON.stringify(cart));
updateCartDisplay();
}
function updateCartDisplay() {
const cartCount = cart.reduce((total, item) => total + item.quantity, 0);
const cartCountElement = document.getElementById('cart-count');
if (cartCountElement) {
cartCountElement.textContent = cartCount;
}
}
// Load and display products on the home page
async function loadFeaturedProducts() {
const products = await getProducts();
const container = document.querySelector('#product1 .pro-container');
if (container) {
container.innerHTML = products.map(product => `
<div class="pro" onclick="window.location.href='sproduct.html?id=${product.productId}'">
<img src="${product.imagePath || `img/product/f${product.productId}.jpg`}" alt="${product.productName}">
<div class="des">
<span>${product.categoryName || 'Category'}</span>
<h5>${product.productName}</h5>
<div class="star">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
</div>
<h4>$${product.price}</h4>
</div>
<a href="sproduct.html?id=${product.productId}">
<i class="fal fa-shopping-cart cart"></i>
</a>
</div>
`).join('');
}
}
// Initialize cart display, load products and check login state
document.addEventListener('DOMContentLoaded', () => {
updateCartDisplay();
if (window.location.pathname.includes('shop.html')) {
loadProducts();
} else {
loadFeaturedProducts();
}
checkLoginState();
});
// Load all products for the shop page
async function loadProducts() {
try {
const products = await getProducts();
const container = document.querySelector('.pro-container');
if (!container) return;
container.innerHTML = ''; // Clear existing products
products.forEach(product => {
const productElement = document.createElement('div');
productElement.classList.add('pro');
productElement.innerHTML = `
<img src="${product.imagePath || `img/product/f${product.productId}.jpg`}" alt="${product.productName}">
<div class="des">
<span>${product.categoryName || 'Category'}</span>
<h5>${product.productName}</h5>
<div class="star">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
</div>
<h4>$${product.price}</h4>
</div>
<a href="sproduct.html?id=${product.productId}">
<i class="fal fa-shopping-cart cart"></i>
</a>
`;
container.appendChild(productElement);
});
} catch (error) {
console.error('Error loading products:', error);
}
}
// Function to check login state and update UI
function checkLoginState() {
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
const loginNav = document.querySelector('.login-nav a');
const popup = document.querySelector('.create-account-popup');
if (currentUser && loginNav) {
loginNav.textContent = currentUser.userName;
loginNav.href = '#';
loginNav.classList.remove('active');
if (popup) {
popup.innerHTML = `
<a href="#" onclick="logout()">Logout</a>
`;
}
}
}
// Logout function
function logout() {
localStorage.removeItem('currentUser');
localStorage.removeItem('userToken');
const loginNav = document.querySelector('.login-nav a');
if (loginNav) {
loginNav.textContent = 'Login';
loginNav.href = 'login.html';
loginNav.classList.add('active');
const popup = document.querySelector('.create-account-popup');
if (popup) {
popup.innerHTML = `
<a href="register.html">Create Account</a>
`;
}
}
window.location.href = 'login.html';
}
// Mobile menu functionality
const bar = document.getElementById('bar');
const nav = document.getElementById('navbar');
const close = document.getElementById('close');
if (bar) {
bar.addEventListener('click', () => {
nav.classList.add('active');
});
}
if (close) {
close.addEventListener('click', () => {
nav.classList.remove('active');
});
}