-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadmin-products.js
More file actions
267 lines (236 loc) · 8.23 KB
/
admin-products.js
File metadata and controls
267 lines (236 loc) · 8.23 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
// استدعاء Firebase config
import { auth, database } from './firebase-config.js';
import {
onAuthStateChanged,
signOut
} from "https://www.gstatic.com/firebasejs/12.1.0/firebase-auth.js";
import {
ref as dbRef,
onValue,
push,
set,
remove,
get
} from "https://www.gstatic.com/firebasejs/12.1.0/firebase-database.js";
// اخفاء الصفحة مبدئيًا
// document.body.style.display = 'none';
// عناصر الـ DOM
const alertContainer = document.getElementById('alertContainer');
const mainContent = document.getElementById('mainContent');
const categorySelect = document.getElementById('categorySelect');
const productForm = document.getElementById('productForm');
const productsTbody = document.getElementById('productsTbody'); // تأكد الاسم صح هنا
const saveBtn = document.getElementById('saveBtn');
const cancelEditBtn = document.getElementById('cancelEditBtn');
const logoutBtn = document.getElementById('logoutBtn');
const btnDashboardCats = document.getElementById('btn-dashboard-cats');
const productIdField = document.getElementById('productId');
const nameInput = document.getElementById('name');
const priceInput = document.getElementById('price');
const stockInput = document.getElementById('stock');
const descriptionInput = document.getElementById('description');
const imageURLInput = document.getElementById('imageURL');
mainContent.style.display = 'none'; // إخفاء المحتوى الرئيسي حتى يتم التحقق من تسجيل الدخول
let categoriesMap = {}; // id -> name
// دالة عرض تنبيه
function showAlert(msg, type='success') {
alertContainer.innerHTML = `
<div class="alert alert-${type} alert-dismissible fade show" role="alert">
${msg}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>`;
setTimeout(() => alertContainer.innerHTML = '', 3500);
}
function redirectToLogin() {
window.location.href = './login/login.html';
}
// التحقق من تسجيل الدخول وصلاحية الأدمن
onAuthStateChanged(auth, async (user) => {
if (!user) {
console.log("User not logged in");
redirectToLogin();
return;
}
try {
const userSnap = await get(dbRef(database, 'users/' + user.uid));
const ud = userSnap.exists() ? userSnap.val() : null;
if (!ud || (ud.type !== 'admin' )) {
alert('Access denied: admin only');
redirectToLogin();
return;
}
// المستخدم ادمن => إظهار الصفحة
// document.body.style.display = 'block';
mainContent.style.display = 'block';
// استمع للأقسام والمنتجات
listenCategories();
listenProducts();
} catch (err) {
console.error(err);
alert('Auth check error');
redirectToLogin();
}
});
// تسجيل الخروج
logoutBtn?.addEventListener('click', async () => {
await signOut(auth);
redirectToLogin();
});
// الانتقال لصفحة الأقسام
btnDashboardCats?.addEventListener('click', () => {
window.location.href = './admin-categories.html';
});
// جلب الأقسام
function listenCategories() {
const categoriesRef = dbRef(database, 'categories');
onValue(categoriesRef, (snap) => {
categorySelect.innerHTML = `<option value="">-- Select category --</option>`;
categoriesMap = {};
snap.forEach(child => {
const id = child.key;
const data = child.val();
const name = data.name || data.title || '';
categoriesMap[id] = name;
const opt = document.createElement('option');
opt.value = id;
opt.textContent = name;
categorySelect.appendChild(opt);
});
if (Object.keys(categoriesMap).length === 0) {
const opt = document.createElement('option');
opt.value = '';
opt.textContent = 'No categories';
categorySelect.appendChild(opt);
}
}, err => console.error('categories onValue error', err));
}
// إضافة أو تعديل منتج
productForm.addEventListener('submit', async (e) => {
e.preventDefault();
const id = productIdField.value || null;
const name = nameInput.value.trim();
const price = Number(priceInput.value);
const stock = Number(stockInput.value);
const description = descriptionInput.value.trim();
const categoryId = categorySelect.value;
const categoryName = categoriesMap[categoryId] || '';
const imageURL = imageURLInput.value.trim();
if (!name || !categoryId || Number.isNaN(price) || Number.isNaN(stock) || !imageURL) {
showAlert('Please fill required fields correctly and enter image URL', 'danger');
return;
}
saveBtn.disabled = true;
saveBtn.textContent = id ? 'Updating...' : 'Saving...';
try {
const productData = {
id: id || null,
name,
price,
stock,
description,
categoryId,
categoryName,
imageURL
};
if (id) {
await set(dbRef(database, 'products/' + id), productData);
showAlert('Product updated', 'success');
} else {
const newRef = push(dbRef(database, 'products'));
productData.id = newRef.key;
await set(newRef, productData);
showAlert('Product added', 'success');
}
productForm.reset();
productIdField.value = '';
cancelEditBtn.style.display = 'none';
saveBtn.textContent = 'Add Product';
} catch (err) {
console.error(err);
showAlert('Error saving product: ' + err.message, 'danger');
} finally {
saveBtn.disabled = false;
}
});
// عرض المنتجات
function listenProducts() {
const productsRef = dbRef(database, 'products');
onValue(productsRef, (snap) => {
productsTbody.innerHTML = '';
snap.forEach(child => {
const id = child.key;
const p = child.val();
const tr = document.createElement('tr');
const imgHtml = p.imageURL ? `<img src="${p.imageURL}" class="thumb" alt=""/>` : '';
tr.innerHTML = `
<td>${imgHtml}</td>
<td>${escapeHtml(p.name)}</td>
<td>${Number(p.price).toFixed(2)}</td>
<td>${p.stock ?? 0}</td>
<td>${escapeHtml(p.categoryName || p.categoryId || '')}</td>
<td>${escapeHtml(p.description || '')}</td>
<td>
<button class="btn btn-sm btn-outline-primary me-1 edit-btn" data-id="${id}">Edit</button>
<button class="btn btn-sm btn-outline-danger delete-btn" data-id="${id}">Delete</button>
</td>
`;
productsTbody.appendChild(tr);
});
document.querySelectorAll('.edit-btn').forEach(b => b.onclick = onEditClick);
document.querySelectorAll('.delete-btn').forEach(b => b.onclick = onDeleteClick);
}, err => console.error('products onValue error', err));
}
// تعديل منتج
async function onEditClick(e) {
const id = e.target.dataset.id;
try {
const snap = await get(dbRef(database, 'products/' + id));
if (!snap.exists()) {
showAlert('Product not found', 'danger');
return;
}
const p = snap.val();
productIdField.value = id;
nameInput.value = p.name || '';
priceInput.value = p.price ?? '';
stockInput.value = p.stock ?? '';
descriptionInput.value = p.description || '';
if (p.categoryId) categorySelect.value = p.categoryId;
if (p.imageURL) imageURLInput.value = p.imageURL;
cancelEditBtn.style.display = 'block';
saveBtn.textContent = 'Update Product';
window.scrollTo({ top: 0, behavior: 'smooth' });
} catch (err) {
console.error(err);
showAlert('Error loading product: ' + err.message, 'danger');
}
}
// حذف منتج
async function onDeleteClick(e) {
const id = e.target.dataset.id;
if (!confirm('Delete this product?')) return;
try {
await remove(dbRef(database, 'products/' + id));
showAlert('Product deleted', 'success');
} catch (err) {
console.error(err);
showAlert('Error deleting product: ' + err.message, 'danger');
}
}
// إلغاء التعديل
cancelEditBtn.addEventListener('click', () => {
productForm.reset();
productIdField.value = '';
cancelEditBtn.style.display = 'none';
saveBtn.textContent = 'Add Product';
});
// حماية النصوص من الـ HTML injection
function escapeHtml(text) {
if (!text) return '';
return String(text)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}