-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.html
More file actions
838 lines (750 loc) · 38.6 KB
/
Copy pathadmin.html
File metadata and controls
838 lines (750 loc) · 38.6 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Panel | SPurno Animation Studio</title>
<meta name="robots" content="noindex, nofollow">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jost:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/admin.css">
</head>
<body>
<div class="admin-wrap">
<!-- Top Bar -->
<div class="admin-top">
<div class="admin-logo">
<span>⚙️ SPurno Admin</span>
</div>
<div class="admin-top-right">
<span class="admin-key-status" id="keyStatus">Not authenticated</span>
<button class="admin-btn" id="adminLogoutBtn" style="display:none;">Sign Out</button>
</div>
</div>
<!-- Auth Screen -->
<div id="authScreen" class="admin-section">
<div class="admin-card" style="max-width:420px;margin:80px auto;">
<h2 class="admin-card-title">🔑 Admin Access</h2>
<p style="color:rgba(255,255,255,0.5);margin-bottom:20px;font-size:0.9rem;">Enter your admin API key to manage orders.</p>
<div class="alert" id="authAlert" role="alert"></div>
<div class="form-row">
<label for="adminKeyInput">Admin API Key</label>
<input type="password" id="adminKeyInput" placeholder="Enter admin API key" autocomplete="off">
</div>
<button class="admin-btn admin-btn-primary" id="authSubmitBtn" style="width:100%;">Authenticate</button>
</div>
</div>
<!-- Dashboard Screen -->
<div id="dashScreen" style="display:none;">
<!-- Stats Bar -->
<div class="stats-bar" id="statsBar"></div>
<!-- Tab Navigation (Orders / Messages / Users) -->
<div class="filter-bar" style="margin-bottom:16px;">
<button class="filter-btn active" data-admin-tab="orders">📋 Orders</button>
<button class="filter-btn" data-admin-tab="messages">💬 Messages <span id="msgBadge" style="background:linear-gradient(135deg,var(--color-primary),var(--color-accent));font-size:0.7rem;padding:2px 8px;border-radius:30px;color:#fff;font-weight:600;margin-left:4px;">0</span></button>
<button class="filter-btn" data-admin-tab="users">👥 Users</button>
</div>
<!-- Orders Panel -->
<div class="admin-panel" id="adminPanelOrders">
<div class="filter-bar">
<button class="filter-btn active" data-filter="all">All</button>
<button class="filter-btn" data-filter="pending">⏳ Pending</button>
<button class="filter-btn" data-filter="quoted">💰 Quoted</button>
<button class="filter-btn" data-filter="accepted">✅ Accepted</button>
<button class="filter-btn" data-filter="in_progress">⚡ In Progress</button>
<button class="filter-btn" data-filter="completed">🎉 Completed</button>
<button class="filter-btn" data-filter="cancelled">❌ Cancelled</button>
</div>
<div class="admin-section" style="margin-top:16px;">
<div class="alert" id="adminAlert" role="alert"></div>
<div class="orders-count" id="ordersCount">Loading orders...</div>
<div id="adminOrdersList"><div class="loading-spinner" style="margin:40px auto;display:block;"></div></div>
</div>
</div>
<!-- Messages Panel -->
<div class="admin-panel" id="adminPanelMessages" style="display:none;">
<div class="admin-section">
<div class="alert" id="adminMsgAlert" role="alert"></div>
<div class="orders-count" id="messagesCount">Loading messages...</div>
<div id="adminMessagesList"><div class="loading-spinner" style="margin:40px auto;display:block;"></div></div>
</div>
</div>
<!-- Users Panel -->
<div class="admin-panel" id="adminPanelUsers" style="display:none;">
<div class="admin-section">
<div class="alert" id="adminUserAlert" role="alert"></div>
<div class="orders-count" id="usersCount">Loading users...</div>
<div id="adminUsersList"><div class="loading-spinner" style="margin:40px auto;display:block;"></div></div>
</div>
</div>
</div>
<!-- Update Order Modal -->
<div class="modal-overlay" id="updateModal">
<div class="modal-content">
<button class="modal-close" id="modalClose">×</button>
<h2 class="admin-card-title" style="margin-bottom:20px;">✏️ Update Order</h2>
<div class="alert" id="modalAlert" role="alert"></div>
<form id="updateForm">
<input type="hidden" id="updateOrderId">
<div class="form-row">
<label>Order Number</label>
<div id="modalOrderNumber" style="font-family:monospace;font-size:0.85rem;color:rgba(255,255,255,0.6);padding:8px 0;"></div>
</div>
<div class="form-row">
<label for="updateStatus">Status</label>
<select id="updateStatus">
<option value="pending">⏳ Pending</option>
<option value="quoted">💰 Quoted</option>
<option value="accepted">✅ Accepted</option>
<option value="in_progress">⚡ In Progress</option>
<option value="completed">🎉 Completed</option>
<option value="cancelled">❌ Cancelled</option>
</select>
</div>
<div class="form-row">
<label for="updatePrice">Quoted Price</label>
<input type="text" id="updatePrice" placeholder="e.g. $350">
</div>
<div class="form-row">
<label for="updateResponse">Admin Response (visible to user)</label>
<textarea id="updateResponse" rows="3" placeholder="Your message to the customer..."></textarea>
</div>
<div class="form-row">
<label for="updateNotes">Admin Notes (internal only)</label>
<textarea id="updateNotes" rows="2" placeholder="Internal notes..."></textarea>
</div>
<div class="modal-actions">
<button type="button" class="admin-btn" id="modalCancelBtn">Cancel</button>
<button type="submit" class="admin-btn admin-btn-primary" id="modalSaveBtn">Update Order</button>
</div>
</form>
</div>
</div>
<!-- Reply to Message Modal -->
<div class="modal-overlay" id="replyModal">
<div class="modal-content">
<button class="modal-close" id="replyModalClose">×</button>
<h2 class="admin-card-title" style="margin-bottom:20px;">💬 Reply to User</h2>
<div class="alert" id="replyModalAlert" role="alert"></div>
<form id="replyForm">
<input type="hidden" id="replyMessageId">
<div class="form-row">
<label>From User</label>
<div id="replyUserInfo" style="font-size:0.85rem;color:rgba(255,255,255,0.6);padding:8px 0;"></div>
</div>
<div class="form-row">
<label>Original Message</label>
<div id="replyOriginalMsg" style="font-size:0.82rem;color:rgba(255,255,255,0.45);padding:12px;background:rgba(255,255,255,0.03);border-radius:10px;line-height:1.5;max-height:100px;overflow-y:auto;"></div>
</div>
<div class="form-row">
<label for="replyText">Your Reply *</label>
<textarea id="replyText" rows="4" placeholder="Write your reply to the user..." required></textarea>
</div>
<div class="modal-actions">
<button type="button" class="admin-btn" id="replyCancelBtn">Cancel</button>
<button type="submit" class="admin-btn admin-btn-primary" id="replySendBtn">Send Reply</button>
</div>
</form>
</div>
</div>
<!-- Compose Message to User Modal -->
<div class="modal-overlay" id="composeModal">
<div class="modal-content">
<button class="modal-close" id="composeModalClose">×</button>
<h2 class="admin-card-title" style="margin-bottom:20px;">✉️ Compose Message to User</h2>
<div class="alert" id="composeModalAlert" role="alert"></div>
<form id="composeForm">
<input type="hidden" id="composeUserId">
<div class="form-row">
<label>Sending To</label>
<div id="composeUserInfo" style="font-size:0.85rem;color:rgba(255,255,255,0.6);padding:8px 0;"></div>
</div>
<div class="form-row">
<label for="composeSubject">Subject</label>
<input type="text" id="composeSubject" placeholder="e.g. Special Offer, Project Update...">
</div>
<div class="form-row">
<label for="composeMessage">Message *</label>
<textarea id="composeMessage" rows="4" placeholder="Write your message to this user..." required></textarea>
</div>
<div class="modal-actions">
<button type="button" class="admin-btn" id="composeCancelBtn">Cancel</button>
<button type="submit" class="admin-btn admin-btn-primary" id="composeSendBtn">Send Message</button>
</div>
</form>
</div>
</div>
</div>
<script>
(function() {
const API_BASE = 'https://spurno-auth.ispurno.workers.dev/api';
const LS_KEY = 'spurno_admin_key';
// ── DOM refs ───────────────────────────────────────
const $ = id => document.getElementById(id);
const authScreen = $('authScreen');
const dashScreen = $('dashScreen');
const keyStatus = $('keyStatus');
const adminKeyInput = $('adminKeyInput');
const authSubmitBtn = $('authSubmitBtn');
const authAlert = $('authAlert');
const adminLogoutBtn = $('adminLogoutBtn');
const statsBar = $('statsBar');
const adminOrdersList = $('adminOrdersList');
const ordersCount = $('ordersCount');
const adminAlert = $('adminAlert');
const filterBtns = document.querySelectorAll('.filter-btn');
const updateModal = $('updateModal');
const modalClose = $('modalClose');
const modalCancelBtn = $('modalCancelBtn');
const modalAlert = $('modalAlert');
const updateForm = $('updateForm');
const updateOrderId = $('updateOrderId');
const modalOrderNumber = $('modalOrderNumber');
const updateStatus = $('updateStatus');
const updatePrice = $('updatePrice');
const updateResponse = $('updateResponse');
const updateNotes = $('updateNotes');
const modalSaveBtn = $('modalSaveBtn');
let adminKey = localStorage.getItem(LS_KEY) || '';
let currentFilter = 'all';
let allOrders = [];
let allStats = [];
// ── Auth ───────────────────────────────────────────
function showAuthAlert(msg, type) {
authAlert.textContent = msg;
authAlert.className = 'alert ' + type;
}
function updateAuthUI() {
if (adminKey) {
keyStatus.textContent = '✅ Authenticated';
adminLogoutBtn.style.display = 'block';
} else {
keyStatus.textContent = '❌ Not authenticated';
adminLogoutBtn.style.display = 'none';
}
}
async function authenticate(key) {
// Test the key by calling the admin API
try {
const res = await fetch(`${API_BASE}/admin/orders`, {
headers: { 'Authorization': `Bearer ${key}` },
});
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || 'Authentication failed');
}
adminKey = key;
localStorage.setItem(LS_KEY, key);
updateAuthUI();
authScreen.style.display = 'none';
dashScreen.style.display = 'block';
showAdminAlert('', '');
loadDashboard();
} catch (e) {
showAuthAlert(e.message || 'Invalid admin key', 'error');
}
}
authSubmitBtn.addEventListener('click', () => {
const key = adminKeyInput.value.trim();
if (!key) {
showAuthAlert('Please enter your admin API key.', 'error');
return;
}
authenticate(key);
});
adminKeyInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') authSubmitBtn.click();
});
adminLogoutBtn.addEventListener('click', () => {
adminKey = '';
localStorage.removeItem(LS_KEY);
updateAuthUI();
dashScreen.style.display = 'none';
authScreen.style.display = 'block';
adminKeyInput.value = '';
authAlert.className = 'alert';
authAlert.textContent = '';
});
// ── API helpers ────────────────────────────────────
async function adminFetch(path, options = {}) {
const res = await fetch(`${API_BASE}${path}`, {
...options,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${adminKey}`,
...(options.headers || {}),
},
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Request failed');
return data;
}
function showAdminAlert(msg, type) {
adminAlert.textContent = msg;
adminAlert.className = 'alert ' + type;
if (msg) setTimeout(() => { adminAlert.className = 'alert'; }, 5000);
}
function showModalAlert(msg, type) {
modalAlert.textContent = msg;
modalAlert.className = 'alert ' + type;
setTimeout(() => { modalAlert.className = 'alert'; }, 4000);
}
// ── Dashboard ──────────────────────────────────────
async function loadDashboard() {
try {
const data = await adminFetch('/admin/orders');
allOrders = data.orders || [];
allStats = data.stats || [];
renderStats();
renderOrders();
} catch (e) {
showAdminAlert('Failed to load orders: ' + e.message, 'error');
}
}
function renderStats() {
const statusLabels = {
pending: '⏳ Pending', quoted: '💰 Quoted', accepted: '✅ Accepted',
in_progress: '⚡ In Progress', completed: '🎉 Completed', cancelled: '❌ Cancelled'
};
const colors = {
pending: '#fde047', quoted: '#93c5fd', accepted: '#86efac',
in_progress: '#d8b4fe', completed: '#86efac', cancelled: '#fca5a5'
};
const total = allOrders.length;
let html = `<div class="stat-card stat-total"><div class="stat-num">${total}</div><div class="stat-label">Total Orders</div></div>`;
allStats.forEach(s => {
html += `<div class="stat-card" style="--stat-color:${colors[s.status] || '#fff'}">
<div class="stat-num">${s.count}</div>
<div class="stat-label">${statusLabels[s.status] || s.status}</div>
</div>`;
});
statsBar.innerHTML = html;
}
function renderOrders() {
let filtered = allOrders;
if (currentFilter !== 'all') {
filtered = allOrders.filter(o => o.status === currentFilter);
}
ordersCount.textContent = `${filtered.length} order${filtered.length !== 1 ? 's' : ''}${currentFilter !== 'all' ? ` (${currentFilter})` : ''}`;
if (!filtered.length) {
adminOrdersList.innerHTML = `<div class="items-empty"><div class="icon">📋</div><p>No orders found.</p></div>`;
return;
}
const statusLabels = {
pending: '⏳ Pending', quoted: '💰 Quoted', accepted: '✅ Accepted',
in_progress: '⚡ In Progress', completed: '🎉 Completed', cancelled: '❌ Cancelled'
};
adminOrdersList.innerHTML = `<div class="admin-orders-list">${filtered.map(o => {
const created = new Date(o.created_at).toLocaleDateString('en-US', {
month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit'
});
return `<div class="admin-order-card" data-order-id="${o.id}">
<div class="admin-order-top">
<div class="admin-order-left">
<span class="admin-order-number">${o.order_number}</span>
<span class="admin-order-user">👤 ${o.user_name || o.user_email || 'Unknown'}</span>
</div>
<span class="order-status status-${o.status}">${statusLabels[o.status] || o.status}</span>
</div>
<div class="admin-order-type">${o.animation_type.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase())}${o.duration_seconds ? ` · ${o.duration_seconds}s` : ''}</div>
<div class="admin-order-desc">${o.description.length > 150 ? o.description.slice(0, 150) + '...' : o.description}</div>
<div class="admin-order-meta">
${o.budget_range ? '💰 ' + o.budget_range : ''}
${o.deadline ? ' 📅 Due: ' + o.deadline : ''}
${o.payment_method ? ' 💳 ' + o.payment_method : ''}
</div>
<div class="admin-order-contact">
${o.contact_email ? '✉️ ' + o.contact_email : ''}
${o.contact_phone ? ' 📞 ' + o.contact_phone : ''}
</div>
<div class="admin-order-footer">
<span class="admin-order-date">${created}</span>
<div class="admin-order-actions">
${o.admin_response ? '<span class="admin-has-response">💬 Has reply</span>' : ''}
${o.quoted_price ? '<span class="admin-has-price">💰 ' + o.quoted_price + '</span>' : ''}
<button class="admin-btn admin-btn-sm admin-update-btn" data-id="${o.id}">✏️ Update</button>
<button class="admin-btn admin-btn-sm admin-delete-order-btn" data-id="${o.id}" style="color:#fca5a5;">🗑️</button>
</div>
</div>
</div>`;
}).join('')}</div>`;
// Attach update and delete button handlers
document.querySelectorAll('.admin-update-btn').forEach(btn => {
btn.addEventListener('click', () => openUpdateModal(btn.dataset.id));
});
document.querySelectorAll('.admin-delete-order-btn').forEach(btn => {
btn.addEventListener('click', () => adminDeleteOrder(btn.dataset.id));
});
}
// ── Admin Delete Order ─────────────────────────────
async function adminDeleteOrder(orderId) {
if (!confirm('Delete this order? This cannot be undone.')) return;
try {
const result = await adminFetch('/admin/orders', {
method: 'DELETE',
body: JSON.stringify({ id: parseInt(orderId, 10) }),
});
showAdminAlert(result.message || 'Order deleted.', 'success');
loadDashboard();
} catch (e) {
showAdminAlert('Failed to delete order: ' + e.message, 'error');
}
}
// ── Admin Messages ─────────────────────────────────
async function loadAdminMessages() {
try {
const data = await adminFetch('/admin/messages');
const messages = data.messages || [];
const stats = data.stats || {};
// Update badge
document.getElementById('msgBadge').textContent = stats.count || messages.length;
const listEl = document.getElementById('adminMessagesList');
const countEl = document.getElementById('messagesCount');
countEl.textContent = `${messages.length} message${messages.length !== 1 ? 's' : ''}`;
if (!messages.length) {
listEl.innerHTML = `<div class="items-empty"><div class="icon">💬</div><p>No messages from users yet.</p></div>`;
return;
}
listEl.innerHTML = `<div class="admin-orders-list">${messages.map(m => {
const created = new Date(m.created_at).toLocaleDateString('en-US', {
month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit'
});
return `<div class="admin-order-card">
<div class="admin-order-top">
<div class="admin-order-left">
<span class="admin-order-user">👤 ${m.name || m.user_name || m.user_email || 'Unknown'}</span>
<span class="admin-order-number">${m.email || ''}</span>
</div>
<span class="admin-order-date">${created}</span>
</div>
<div class="admin-order-type">${m.subject || '(No subject)'}</div>
<div class="admin-order-desc">${m.message}</div>
<div class="admin-order-footer">
<span></span>
<div class="admin-order-actions">
<button class="admin-btn admin-btn-sm admin-delete-msg-btn" data-id="${m.id}" style="color:#fca5a5;">🗑️ Delete</button>
</div>
</div>
</div>`;
}).join('')}</div>`;
document.querySelectorAll('.admin-delete-msg-btn').forEach(btn => {
btn.addEventListener('click', () => adminDeleteMessage(btn.dataset.id));
});
} catch (e) {
document.getElementById('adminMsgAlert').textContent = 'Failed to load messages: ' + e.message;
document.getElementById('adminMsgAlert').className = 'alert error';
}
}
async function adminDeleteMessage(msgId) {
if (!confirm('Delete this message?')) return;
try {
const result = await adminFetch('/admin/messages', {
method: 'DELETE',
body: JSON.stringify({ id: parseInt(msgId, 10) }),
});
document.getElementById('adminMsgAlert').textContent = result.message || 'Message deleted.';
document.getElementById('adminMsgAlert').className = 'alert success';
loadAdminMessages();
} catch (e) {
document.getElementById('adminMsgAlert').textContent = 'Failed: ' + e.message;
document.getElementById('adminMsgAlert').className = 'alert error';
}
}
// ── Admin Tab Switching (Orders / Messages / Users) ─
document.querySelectorAll('[data-admin-tab]').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('[data-admin-tab]').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.admin-panel').forEach(p => p.style.display = 'none');
btn.classList.add('active');
const tab = btn.dataset.adminTab;
document.getElementById('adminPanel' + tab.charAt(0).toUpperCase() + tab.slice(1)).style.display = 'block';
if (tab === 'messages') loadAdminMessages();
if (tab === 'users') loadAdminUsers();
});
});
// ── Filters ────────────────────────────────────────
filterBtns.forEach(btn => {
btn.addEventListener('click', () => {
filterBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentFilter = btn.dataset.filter;
renderOrders();
});
});
// ── Update Modal ───────────────────────────────────
async function openUpdateModal(orderId) {
try {
const data = await adminFetch(`/admin/orders?id=${orderId}`);
const order = data.order;
updateOrderId.value = order.id;
modalOrderNumber.textContent = order.order_number || '—';
updateStatus.value = order.status || 'pending';
updatePrice.value = order.quoted_price || '';
updateResponse.value = order.admin_response || '';
updateNotes.value = order.admin_notes || '';
modalAlert.className = 'alert';
modalAlert.textContent = '';
updateModal.classList.add('show');
} catch (e) {
showAdminAlert('Failed to load order details: ' + e.message, 'error');
}
}
function closeModal() {
updateModal.classList.remove('show');
}
modalClose.addEventListener('click', closeModal);
modalCancelBtn.addEventListener('click', closeModal);
updateModal.addEventListener('click', (e) => {
if (e.target === updateModal) closeModal();
});
updateForm.addEventListener('submit', async (e) => {
e.preventDefault();
modalSaveBtn.disabled = true;
modalSaveBtn.textContent = 'Updating...';
try {
const result = await adminFetch('/admin/orders', {
method: 'PUT',
body: JSON.stringify({
id: parseInt(updateOrderId.value, 10),
status: updateStatus.value,
quoted_price: updatePrice.value.trim() || null,
admin_response: updateResponse.value.trim() || null,
admin_notes: updateNotes.value.trim() || null,
}),
});
showModalAlert(result.message || 'Order updated!', 'success');
closeModal();
showAdminAlert(`Order ${result.order.order_number} updated successfully.`, 'success');
loadDashboard(); // Reload
} catch (e) {
showModalAlert(e.message || 'Failed to update order', 'error');
}
modalSaveBtn.disabled = false;
modalSaveBtn.textContent = 'Update Order';
});
// ── Reply to Message Modal ─────────────────────────
const replyModal = $('replyModal');
const replyModalClose = $('replyModalClose');
const replyCancelBtn = $('replyCancelBtn');
const replyForm = $('replyForm');
const replyMessageId = $('replyMessageId');
const replyUserInfo = $('replyUserInfo');
const replyOriginalMsg = $('replyOriginalMsg');
const replyText = $('replyText');
const replySendBtn = $('replySendBtn');
const replyModalAlert = $('replyModalAlert');
function openReplyModal(msgId, userInfo, originalMsg) {
replyMessageId.value = msgId;
replyUserInfo.textContent = userInfo;
replyOriginalMsg.textContent = originalMsg;
replyText.value = '';
replyModalAlert.className = 'alert';
replyModalAlert.textContent = '';
replyModal.classList.add('show');
}
function closeReplyModal() {
replyModal.classList.remove('show');
}
replyModalClose.addEventListener('click', closeReplyModal);
replyCancelBtn.addEventListener('click', closeReplyModal);
replyModal.addEventListener('click', (e) => {
if (e.target === replyModal) closeReplyModal();
});
replyForm.addEventListener('submit', async (e) => {
e.preventDefault();
const reply = replyText.value.trim();
if (!reply) {
replyModalAlert.textContent = 'Please write a reply.';
replyModalAlert.className = 'alert error';
return;
}
replySendBtn.disabled = true;
replySendBtn.textContent = 'Sending...';
try {
const result = await adminFetch('/admin/messages/reply', {
method: 'POST',
body: JSON.stringify({
id: parseInt(replyMessageId.value, 10),
reply,
}),
});
replyModalAlert.textContent = result.message || 'Reply sent!';
replyModalAlert.className = 'alert success';
closeReplyModal();
document.getElementById('adminMsgAlert').textContent = 'Reply sent successfully.';
document.getElementById('adminMsgAlert').className = 'alert success';
loadAdminMessages();
} catch (e) {
replyModalAlert.textContent = e.message || 'Failed to send reply';
replyModalAlert.className = 'alert error';
}
replySendBtn.disabled = false;
replySendBtn.textContent = 'Send Reply';
});
// ── Admin Users ────────────────────────────────────
async function loadAdminUsers() {
try {
const data = await adminFetch('/admin/users');
const users = data.users || [];
const listEl = document.getElementById('adminUsersList');
const countEl = document.getElementById('usersCount');
const alertEl = document.getElementById('adminUserAlert');
countEl.textContent = `${users.length} registered user${users.length !== 1 ? 's' : ''}`;
if (!users.length) {
listEl.innerHTML = `<div class="items-empty"><div class="icon">👥</div><p>No users registered yet.</p></div>`;
return;
}
listEl.innerHTML = `<div class="admin-orders-list">${users.map(u => {
const created = new Date(u.created_at).toLocaleDateString('en-US', {
month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit'
});
return `<div class="admin-order-card">
<div class="admin-order-top">
<div class="admin-order-left">
<span class="admin-order-user">👤 ${u.name || u.email.split('@')[0]}</span>
<span class="admin-order-number">#${u.id}</span>
</div>
<span class="admin-order-date">Joined ${created}</span>
</div>
<div class="admin-order-type">✉️ ${u.email}</div>
<div class="admin-order-footer">
<span></span>
<div class="admin-order-actions">
<button class="admin-btn admin-btn-sm admin-compose-btn" data-user-id="${u.id}" data-user-name="${(u.name || u.email.split('@')[0]).replace(/"/g, '"')}" data-user-email="${u.email}">✉️ Send Message</button>
</div>
</div>
</div>`;
}).join('')}</div>`;
document.querySelectorAll('.admin-compose-btn').forEach(btn => {
btn.addEventListener('click', () => {
openComposeModal(btn.dataset.userId, btn.dataset.userName, btn.dataset.userEmail);
});
});
} catch (e) {
document.getElementById('adminUserAlert').textContent = 'Failed to load users: ' + e.message;
document.getElementById('adminUserAlert').className = 'alert error';
}
}
// ── Compose Message Modal ──────────────────────────
const composeModal = $('composeModal');
const composeModalClose = $('composeModalClose');
const composeCancelBtn = $('composeCancelBtn');
const composeForm = $('composeForm');
const composeUserId = $('composeUserId');
const composeUserInfo = $('composeUserInfo');
const composeSubject = $('composeSubject');
const composeMessage = $('composeMessage');
const composeSendBtn = $('composeSendBtn');
const composeModalAlert = $('composeModalAlert');
function openComposeModal(userId, userName, userEmail) {
composeUserId.value = userId;
composeUserInfo.textContent = `${userName} (${userEmail})`;
composeSubject.value = '';
composeMessage.value = '';
composeModalAlert.className = 'alert';
composeModalAlert.textContent = '';
composeModal.classList.add('show');
}
function closeComposeModal() {
composeModal.classList.remove('show');
}
composeModalClose.addEventListener('click', closeComposeModal);
composeCancelBtn.addEventListener('click', closeComposeModal);
composeModal.addEventListener('click', (e) => {
if (e.target === composeModal) closeComposeModal();
});
composeForm.addEventListener('submit', async (e) => {
e.preventDefault();
const message = composeMessage.value.trim();
if (!message) {
composeModalAlert.textContent = 'Please write a message.';
composeModalAlert.className = 'alert error';
return;
}
composeSendBtn.disabled = true;
composeSendBtn.textContent = 'Sending...';
try {
const result = await adminFetch('/admin/messages/compose', {
method: 'POST',
body: JSON.stringify({
user_id: composeUserId.value,
subject: composeSubject.value.trim() || 'Message from Admin',
message,
}),
});
composeModalAlert.textContent = result.message || 'Message sent!';
composeModalAlert.className = 'alert success';
setTimeout(() => closeComposeModal(), 1500);
} catch (e) {
composeModalAlert.textContent = e.message || 'Failed to send message';
composeModalAlert.className = 'alert error';
}
composeSendBtn.disabled = false;
composeSendBtn.textContent = 'Send Message';
});
// ── Update the messages render to include reply button ──
loadAdminMessages = async function() {
try {
const data = await adminFetch('/admin/messages');
const messages = data.messages || [];
const stats = data.stats || {};
document.getElementById('msgBadge').textContent = stats.count || messages.length;
const listEl = document.getElementById('adminMessagesList');
const countEl = document.getElementById('messagesCount');
countEl.textContent = `${messages.length} message${messages.length !== 1 ? 's' : ''}`;
if (!messages.length) {
listEl.innerHTML = `<div class="items-empty"><div class="icon">💬</div><p>No messages from users yet.</p></div>`;
return;
}
listEl.innerHTML = `<div class="admin-orders-list">${messages.map(m => {
const created = new Date(m.created_at).toLocaleDateString('en-US', {
month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit'
});
const hasReply = m.admin_reply && m.admin_reply.trim();
return `<div class="admin-order-card">
<div class="admin-order-top">
<div class="admin-order-left">
<span class="admin-order-user">👤 ${m.name || m.user_name || m.user_email || 'Unknown'}</span>
<span class="admin-order-number">${m.email || ''}</span>
</div>
<span class="admin-order-date">${created}</span>
</div>
<div class="admin-order-type">${m.subject || '(No subject)'}</div>
<div class="admin-order-desc">${m.message}</div>
${hasReply ? `<div class="admin-order-meta" style="margin-top:8px;padding:10px;background:rgba(34,197,94,0.06);border-radius:8px;border-left:3px solid #86efac;"><strong style="color:#86efac;">✅ Your Reply:</strong> ${m.admin_reply}${m.admin_replied_at ? ' <span style="color:rgba(255,255,255,0.3);font-size:0.72rem;">(' + new Date(m.admin_replied_at).toLocaleDateString('en-US', {month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}) + ')</span>' : ''}</div>` : ''}
<div class="admin-order-footer">
<span></span>
<div class="admin-order-actions">
${hasReply ? '<span style="font-size:0.72rem;padding:3px 10px;border-radius:20px;background:rgba(34,197,94,0.1);color:#86efac;">✅ Replied</span>' : '<span style="font-size:0.72rem;padding:3px 10px;border-radius:20px;background:rgba(234,179,8,0.1);color:#fde047;">⏳ Awaiting reply</span>'} <button class="admin-btn admin-btn-sm admin-reply-btn" data-id="${m.id}" data-user="${(m.name || m.user_name || m.user_email || 'Unknown').replace(/"/g, '"')}" data-msg="${m.message.replace(/"/g, '"').replace(/\n/g, ' ')}">💬 Reply</button>
<button class="admin-btn admin-btn-sm admin-delete-msg-btn" data-id="${m.id}" style="color:#fca5a5;">🗑️ Delete</button>
</div>
</div>
</div>`;
}).join('')}</div>`;
document.querySelectorAll('.admin-reply-btn').forEach(btn => {
btn.addEventListener('click', () => {
openReplyModal(btn.dataset.id, btn.dataset.user, btn.dataset.msg);
});
});
document.querySelectorAll('.admin-delete-msg-btn').forEach(btn => {
btn.addEventListener('click', () => adminDeleteMessage(btn.dataset.id));
});
} catch (e) {
document.getElementById('adminMsgAlert').textContent = 'Failed to load messages: ' + e.message;
document.getElementById('adminMsgAlert').className = 'alert error';
}
};
// ── Auto-login if key stored ───────────────────────
if (adminKey) {
updateAuthUI();
authenticate(adminKey);
} else {
updateAuthUI();
authScreen.style.display = 'block';
adminKeyInput.focus();
}
})();
</script>
</body>
</html>