-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstuff.js
More file actions
1950 lines (1720 loc) · 58.5 KB
/
stuff.js
File metadata and controls
1950 lines (1720 loc) · 58.5 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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==========================================
// 1. CONFIGURATION & UTILITIES
// ==========================================
// Initialize Supabase
const SUPABASE_URL = 'https://ovxxnsrqzdlyzdmubwaw.supabase.co';
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im92eHhuc3JxemRseXpkbXVid2F3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM5NzY4MTgsImV4cCI6MjA3OTU1MjgxOH0.uwU9aQGbUO7OEv4HI8Rtq7awANWNubt3yJTSUMZRAJU';
const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
const SUPP_BUCKET = 'supplement-images';
// Helper Functions
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
const fmtBDT = (n) => `৳${Number(n || 0).toFixed(2)}`;
const prettyPaymentMethod = (m) => {
if (!m) return '';
const val = String(m).toLowerCase();
if (val === 'bkash') return 'bKash';
if (val === 'card') return 'Card';
if (val === 'cash') return 'Cash';
return 'Other';
};
const notificationSound = $('#notification-sound');
const colNotTaken = $('#orders-col-not-taken');
const colPaymentComplete = $('#orders-col-payment-complete');
const colSuppPending = $('#supp-orders-pending');
const loadingOrders = $('#loading-orders');
// payment modal elements
const paymentModal = document.getElementById('payment-modal');
const paymentForm = document.getElementById('payment-form');
const paymentOrderIdEl = document.getElementById('payment-order-id');
const paymentOrderCustomerEl = document.getElementById('payment-order-customer');
const paymentOrderTotalEl = document.getElementById('payment-order-total');
const paymentMethodSelect = document.getElementById('payment-method');
const paymentReferenceInput = document.getElementById('payment-reference');
const paymentCancelBtn = document.getElementById('payment-cancel-btn');
const paymentCloseBtn = document.getElementById('payment-close-btn');
// keep the uuid as a STRING
// { id: string, customer: string, total: number, type: 'cafe' | 'supplement' }
let currentPaymentOrder = null;
// ==========================================
// ROLE-BASED ACCESS CONTROL
// ==========================================
function getUserRole() {
return localStorage.getItem('userRole') || 'staff';
}
function setUserRole(role) {
localStorage.setItem('userRole', role);
}
function isAdmin() {
return getUserRole() === 'admin';
}
function checkAccess(requiredRole = 'admin') {
const userRole = getUserRole();
if (requiredRole === 'admin' && userRole !== 'admin') {
return false;
}
return true;
}
function slugifyName(filename) {
const dot = filename.lastIndexOf('.');
const base = (dot >= 0 ? filename.slice(0, dot) : filename)
.toLowerCase()
.replace(/[^a-z0-9-_]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 40);
const ext = (dot >= 0 ? filename.slice(dot + 1) : 'jpg').toLowerCase();
return { base, ext };
}
function parseStoragePath(publicUrl) {
try {
const u = new URL(publicUrl);
const ix = u.pathname.indexOf('/object/public/');
if (ix === -1) return null;
const after = u.pathname.slice(ix + '/object/public/'.length);
const [bucket, ...rest] = after.split('/');
return { bucket, path: rest.join('/') };
} catch {
return null;
}
}
// ==========================================
// 2. TABS & NAVIGATION
// ==========================================
function initTabs() {
const mainTabs = $('.main-tabs');
const tabContents = $$('.tab-content');
if (!mainTabs) return;
mainTabs.addEventListener('click', (e) => {
const btn = e.target.closest('button');
if (!btn) return;
mainTabs.querySelector('.active')?.classList.remove('active');
btn.classList.add('active');
tabContents.forEach((c) => c.classList.remove('active'));
const toShow = document.getElementById(`${btn.dataset.tab}-section`);
toShow?.classList.add('active');
const tab = btn.dataset.tab;
if (tab === 'dashboard') loadDashboard();
if (tab === 'orders') fetchAndRenderOrders();
if (tab === 'transactions') fetchAndRenderTransactions();
if (tab === 'menu') loadMenuItems();
if (tab === 'supplements') loadSupplements();
if (tab === 'supplement-requests') loadSupplementRequests();
});
}
function startAutoRefresh() {
setInterval(async () => {
const activeTab = document.querySelector('.main-tab-btn.active')?.dataset.tab;
if (activeTab === 'dashboard') await loadDashboard();
if (activeTab === 'orders') await fetchAndRenderOrders();
if (activeTab === 'transactions') await fetchAndRenderTransactions();
}, 10000);
}
function initThemeToggle() {
const themeToggleBtn = $('#theme-toggle-btn');
const themeIcon = $('#theme-icon');
const themeText = $('#theme-text');
const savedTheme = localStorage.getItem('theme') || 'light';
if (savedTheme === 'dark') {
document.body.classList.add('dark-mode');
themeIcon?.setAttribute('data-lucide', 'sun');
if (themeText) themeText.textContent = 'Light Mode';
}
themeToggleBtn?.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
const isDark = document.body.classList.contains('dark-mode');
localStorage.setItem('theme', isDark ? 'dark' : 'light');
themeIcon?.setAttribute('data-lucide', isDark ? 'sun' : 'moon');
if (themeText) themeText.textContent = isDark ? 'Light Mode' : 'Dark Mode';
window.lucide?.createIcons();
});
}
// ==========================================
// 3. ORDERS (CAFE + SUPPLEMENTS PENDING)
// ==========================================
let currentOrderCount = 0;
let currentSuppPendingCount = 0;
async function fetchAndRenderOrders() {
if (loadingOrders) loadingOrders.classList.remove('hidden');
// 1. Fetch Cafe Orders
const { data: orders, error: errCafe } = await supabase
.from('orders')
.select(`*, order_items ( * )`)
.neq('status', 'Delivery Complete')
.order('created_at', { ascending: true });
// 2. Fetch Pending Supplement Orders
const { data: suppOrders, error: errSupp } = await supabase
.from('supplement_orders')
.select(`*, supplement_order_items ( * )`)
.eq('status', 'Pending')
.order('created_at', { ascending: true });
if (errCafe) console.error('Error fetching cafe orders:', errCafe);
if (errSupp) console.error('Error fetching supplement orders:', errSupp);
// Notification Sound Logic
const totalNewCount = (orders?.length || 0) + (suppOrders?.length || 0);
const previousCount = currentOrderCount + currentSuppPendingCount;
if (totalNewCount > previousCount && previousCount > 0) {
notificationSound?.play().catch((e) => console.log('Audio play blocked'));
}
currentOrderCount = orders?.length || 0;
currentSuppPendingCount = suppOrders?.length || 0;
renderCafeKanban(orders || []);
renderSuppPending(suppOrders || []);
if (loadingOrders) loadingOrders.classList.add('hidden');
}
// ===============================
// PAYMENT MODAL HELPERS
// ===============================
function openPaymentModal({ id, customer, total, type = 'cafe' }) {
currentPaymentOrder = {
id: String(id),
customer: customer || 'Walk-in',
total: Number(total) || 0,
type, // 'cafe' or 'supplement'
};
if (paymentOrderIdEl)
paymentOrderIdEl.textContent = `#${String(id).slice(0, 6).toUpperCase()}`;
if (paymentOrderCustomerEl)
paymentOrderCustomerEl.textContent = currentPaymentOrder.customer;
if (paymentOrderTotalEl)
paymentOrderTotalEl.textContent = fmtBDT(currentPaymentOrder.total);
if (paymentMethodSelect) paymentMethodSelect.value = '';
if (paymentReferenceInput) paymentReferenceInput.value = '';
paymentModal?.classList.remove('hidden');
window.lucide?.createIcons();
}
function closePaymentModal() {
paymentModal?.classList.add('hidden');
currentPaymentOrder = null;
}
async function handlePaymentSubmit(e) {
e.preventDefault();
if (!currentPaymentOrder) return;
const submitBtn = paymentForm.querySelector('button[type="submit"]');
const originalText = submitBtn?.textContent;
const method = paymentMethodSelect?.value;
const reference = paymentReferenceInput?.value.trim() || null;
if (!method) {
alert('Please select a payment method.');
return;
}
if (submitBtn) {
submitBtn.disabled = true;
submitBtn.textContent = 'Saving...';
}
try {
// build payment payload
const payload = {
method,
status: 'completed',
amount: currentPaymentOrder.total,
transaction_reference: reference,
source: currentPaymentOrder.type || 'cafe',
};
if (currentPaymentOrder.type === 'supplement') {
payload.supplement_order_id = currentPaymentOrder.id;
} else {
payload.order_id = currentPaymentOrder.id;
}
// 1) Insert payment
const { error: paymentError } = await supabase
.from('payments')
.insert([payload]);
if (paymentError) {
console.error('Payment insert error:', paymentError);
alert('Could not save payment. Please try again.');
return;
}
// 2) Update order status
if (currentPaymentOrder.type === 'supplement') {
// supplements: mark as Completed
const { error: suppErr } = await supabase
.from('supplement_orders')
.update({
status: 'Completed',
updated_at: new Date().toISOString(),
})
.eq('id', currentPaymentOrder.id);
if (suppErr) {
console.error('Supp order status update error:', suppErr);
alert('Payment saved, but supplement order status could not be updated.');
return;
}
} else {
// cafe
const { error: orderError } = await supabase
.from('orders')
.update({
status: 'Payment Complete',
updated_at: new Date().toISOString(),
})
.eq('id', currentPaymentOrder.id);
if (orderError) {
console.error('Order status update error:', orderError);
alert('Payment saved, but order status could not be updated.');
return;
}
}
closePaymentModal();
await fetchAndRenderOrders();
} finally {
if (submitBtn) {
submitBtn.disabled = false;
submitBtn.textContent = originalText || 'Confirm Payment';
}
}
}
// --- Cafe Rendering ---
function renderCafeKanban(orders) {
if (colNotTaken) colNotTaken.innerHTML = '';
if (colPaymentComplete) colPaymentComplete.innerHTML = '';
const ordersNotTaken = orders.filter((o) => o.status === 'Not Taken');
const ordersPaymentComplete = orders.filter(
(o) => o.status === 'Payment Complete'
);
if (colNotTaken) {
colNotTaken.innerHTML = ordersNotTaken.length
? ''
: '<p class="empty-message">No new orders.</p>';
ordersNotTaken.forEach((o) =>
colNotTaken.appendChild(createCafeOrderCard(o))
);
}
if (colPaymentComplete) {
colPaymentComplete.innerHTML = ordersPaymentComplete.length
? ''
: '<p class="empty-message">No orders awaiting pickup.</p>';
ordersPaymentComplete.forEach((o) =>
colPaymentComplete.appendChild(createCafeOrderCard(o))
);
}
}
function createCafeOrderCard(order) {
const orderCard = document.createElement('div');
const statusClass = (order.status || '').toLowerCase().replace(' ', '-');
const statusColor = order.status === 'Not Taken' ? 'var(--blue)' : '#ffc107';
orderCard.className = `order-card status-${statusClass}`;
orderCard.style.cssText = `--status-color: ${statusColor}`;
const itemsHtml = (order.order_items || [])
.map(
(item) => `
<div class="order-item">
<span><span class="quantity">${item.quantity}x</span> ${
item.item_name
}</span>
<span>৳${(item.price_at_order * item.quantity).toFixed(2)}</span>
</div>
`
)
.join('');
orderCard.innerHTML = `
<div class="order-header">
<div>
<h3>Order #${String(order.id).slice(0, 6).toUpperCase()}</h3>
<p class="order-customer">${order.customer_name}</p>
<p class="order-time">${new Date(
order.created_at
).toLocaleTimeString()}</p>
</div>
<p class="total">৳${Number(order.total_amount).toFixed(2)}</p>
</div>
<div class="order-items-list">${itemsHtml}</div>
<div class="order-actions">
${
order.status === 'Not Taken'
? `
<button
class="btn btn-primary"
data-id="${order.id}"
data-next-status="Payment Complete"
data-order-total="${Number(order.total_amount).toFixed(2)}"
data-order-customer="${order.customer_name || 'Walk-in'}"
>
Mark Payment
</button>`
: ''
}
${
order.status === 'Payment Complete'
? `
<button
class="btn btn-primary"
data-id="${order.id}"
data-next-status="Delivery Complete"
>
Mark Delivery Complete
</button>`
: ''
}
</div>
`;
return orderCard;
}
// --- Supplements Pending Rendering ---
function renderSuppPending(rows) {
if (!colSuppPending) return;
colSuppPending.innerHTML = rows.length
? ''
: '<p class="empty-message">No supplement orders pending.</p>';
rows.forEach((o) => colSuppPending.appendChild(createSuppPendingCard(o)));
}
function createSuppPendingCard(order) {
const card = document.createElement('div');
card.className = 'order-card status-pending';
card.style.cssText = `--status-color: var(--teal, #0fb);`;
const itemsHtml = (order.supplement_order_items || [])
.map(
(item) => `
<div class="order-item">
<span><span class="quantity">${item.quantity}x</span> ${
item.item_name
}</span>
<span>৳${(item.price_at_order * item.quantity).toFixed(2)}</span>
</div>
`
)
.join('');
card.innerHTML = `
<div class="order-header">
<div>
<h3>Supp #${String(order.id).slice(0, 6).toUpperCase()}</h3>
<p class="order-customer">${order.customer_name || 'Walk-in'}</p>
<p class="order-time">${new Date(
order.created_at
).toLocaleTimeString()}</p>
</div>
<p class="total">৳${Number(order.total_amount).toFixed(2)}</p>
</div>
<div class="order-items-list">${itemsHtml}</div>
<div class="order-actions">
<button class="btn btn-danger" data-supp-delete="${order.id}">Delete</button>
<button
class="btn btn-primary"
data-supp-pay="${order.id}"
data-supp-total="${Number(order.total_amount).toFixed(2)}"
data-supp-customer="${order.customer_name || 'Walk-in'}"
>
Mark Payment
</button>
</div>
`;
return card;
}
// --- Event Listeners (Orders) ---
function bindOrderStatusEvents() {
const ordersSection = document.getElementById('orders-section');
if (!ordersSection) return;
ordersSection.addEventListener('click', async (e) => {
const btn = e.target.closest('button');
if (!btn) return;
// 1. CAFE: Payment & Status
if (btn.dataset.id && btn.dataset.nextStatus) {
const orderId = btn.dataset.id;
const nextStatus = btn.dataset.nextStatus;
// If we're marking payment, open modal instead of direct update
if (nextStatus === 'Payment Complete') {
openPaymentModal({
id: orderId,
customer: btn.dataset.orderCustomer || 'Walk-in',
total: parseFloat(btn.dataset.orderTotal || '0') || 0,
type: 'cafe',
});
return;
}
// Delivery Complete still updates directly
if (nextStatus === 'Delivery Complete') {
const original = btn.textContent;
btn.disabled = true;
btn.textContent = 'Updating…';
const { error } = await supabase
.from('orders')
.update({
status: nextStatus,
updated_at: new Date().toISOString(),
})
.eq('id', orderId);
if (error) {
console.error('Error updating status:', error);
alert('Could not update order status.');
btn.disabled = false;
btn.textContent = original;
} else {
await fetchAndRenderOrders();
}
}
}
// 2. SUPP: Mark Payment (open modal)
if (btn.dataset.suppPay) {
const suppId = btn.dataset.suppPay;
openPaymentModal({
id: suppId,
customer: btn.dataset.suppCustomer || 'Walk-in',
total: parseFloat(btn.dataset.suppTotal || '0') || 0,
type: 'supplement',
});
return;
}
// 3. SUPP: Delete
if (btn.dataset.suppDelete) {
const orderId = btn.dataset.suppDelete;
if (!confirm('Delete this supplement order? Items will be restocked.'))
return;
const { data: items } = await supabase
.from('supplement_order_items')
.select('*')
.eq('order_id', orderId);
// Restock items
for (const it of items || []) {
const pid = it.supplement_product_id;
const qty = Number(it.quantity || 0);
if (!pid || !qty) continue;
const { data: prod } = await supabase
.from('supplement_products')
.select('stock')
.eq('id', pid)
.single();
const newStock = Number(prod?.stock || 0) + qty;
await supabase
.from('supplement_products')
.update({ stock: newStock, updated_at: new Date().toISOString() })
.eq('id', pid);
}
await supabase
.from('supplement_order_items')
.delete()
.eq('order_id', orderId);
await supabase.from('supplement_orders').delete().eq('id', orderId);
alert('Supplement order deleted.');
await fetchAndRenderOrders();
}
});
}
// ==========================================
// 4. CAFE MENU MANAGEMENT
// ==========================================
const menuTableBody = $('#menu-table-body');
const loadingMenu = $('#loading-menu');
const menuTable = $('#menu-table');
const addItemBtn = $('#add-item-btn');
const itemModal = $('#item-modal');
const closeModalBtn = $('#close-modal-btn');
const cancelBtn = $('#cancel-btn');
const itemForm = $('#item-form');
const modalTitle = $('#modal-title');
let editingItemId = null;
async function loadMenuItems() {
if (loadingMenu) loadingMenu.classList.remove('hidden');
if (menuTable) menuTable.classList.add('hidden');
const { data, error } = await supabase
.from('menu_items')
.select('*')
.order('created_at', { ascending: false });
if (error) {
console.error('Error fetching menu items:', error);
alert('Could not fetch menu items.');
return;
}
if (menuTableBody) {
menuTableBody.innerHTML = '';
(data || []).forEach((item) => {
const row = document.createElement('tr');
const priceRegular = item.price_regular || item.price || 0;
const priceLarge = item.price_large || item.price || 0;
row.innerHTML = `
<td>
<div class="item-info">
<img src="${
item.image_url || 'https://via.placeholder.com/50'
}" alt="${item.name}" class="item-image">
<div class="item-name-desc">
<div class="item-name">${item.name} ${
item.is_popular ? '⭐' : ''
}</div>
</div>
</div>
</td>
<td><span class="item-category">${item.category}</span></td>
<td>
<div class="price-display">
<span class="price-regular">Reg: ${fmtBDT(priceRegular)}</span>
<span class="price-large">Lg: ${fmtBDT(priceLarge)}</span>
</div>
</td>
<td>
<button class="status-toggle ${
item.available ? 'available' : 'unavailable'
}" data-id="${item.id}" data-current-status="${
item.available
}">${item.available ? 'Available' : 'Unavailable'}</button>
</td>
<td>
<div class="action-buttons">
<button class="action-btn edit" data-id="${
item.id
}"><i data-lucide="edit"></i></button>
<button class="action-btn delete" data-id="${
item.id
}"><i data-lucide="trash-2"></i></button>
</div>
</td>
`;
menuTableBody.appendChild(row);
});
}
window.lucide?.createIcons();
if (loadingMenu) loadingMenu.classList.add('hidden');
if (menuTable) menuTable.classList.remove('hidden');
}
async function toggleMenuAvailability(id, current) {
const { error } = await supabase
.from('menu_items')
.update({ available: !current })
.eq('id', id);
if (error) alert('Failed to update status.');
else loadMenuItems();
}
async function openEditModal(id) {
const { data, error } = await supabase
.from('menu_items')
.select('*')
.eq('id', id)
.single();
if (error) {
console.error('Error fetching item:', error);
alert('Could not load item data.');
return;
}
editingItemId = id;
modalTitle.textContent = 'Edit Menu Item';
$('#item-id').value = data.id;
$('#name').value = data.name;
$('#description').value = data.description;
$('#category').value = data.category;
$('#price-regular').value = data.price_regular || data.price || 0;
$('#price-large').value = data.price_large || data.price || 0;
$('#is_popular').checked = !!data.is_popular;
// Nutrition fields
const setVal = (idSel, v) => ($(idSel).value = v ?? '');
setVal('#calories', data.calories);
setVal('#protein', data.protein);
setVal('#carbohydrates', data.carbohydrates);
setVal('#fats', data.fats);
setVal('#fiber', data.fiber);
setVal('#sugar', data.sugar);
setVal('#sodium', data.sodium);
setVal('#vitamins', data.vitamins);
setVal('#allergens', data.allergens);
setVal('#dietary_tags', data.dietary_tags);
$('#current-image').textContent = data.image_url
? `Current: ${data.image_url.split('/').pop()}`
: 'No image uploaded.';
itemModal.classList.remove('hidden');
window.lucide?.createIcons();
}
function openAddModal() {
editingItemId = null;
modalTitle.textContent = 'Add Menu Item';
itemForm.reset();
$('#is_popular').checked = false;
$('#current-image').textContent = '';
itemModal.classList.remove('hidden');
window.lucide?.createIcons();
}
async function handleMenuFormSubmit(e) {
e.preventDefault();
const submitButton = e.target.querySelector('button[type="submit"]');
submitButton.disabled = true;
submitButton.textContent = 'Saving…';
let imageUrl = null;
const imageFile = $('#image')?.files?.[0];
if (imageFile) {
const filePath = `public/${Date.now()}-${imageFile.name}`;
const { data: uploadData, error: uploadError } = await supabase.storage
.from('menu-images')
.upload(filePath, imageFile);
if (uploadError) {
console.error('Image upload error:', uploadError);
alert('Failed to upload image.');
submitButton.disabled = false;
submitButton.textContent = 'Save Item';
return;
}
const { data: urlData } = supabase.storage
.from('menu-images')
.getPublicUrl(uploadData.path);
imageUrl = urlData.publicUrl;
}
const priceRegular = parseFloat($('#price-regular').value);
const priceLarge = parseFloat($('#price-large').value);
if (
isNaN(priceRegular) ||
isNaN(priceLarge) ||
priceRegular <= 0 ||
priceLarge <= 0
) {
alert('Please enter valid prices for both regular and large sizes.');
submitButton.disabled = false;
submitButton.textContent = 'Save Item';
return;
}
const formData = {
name: $('#name').value,
description: $('#description').value,
category: $('#category').value,
price: priceRegular,
price_regular: priceRegular,
price_large: priceLarge,
is_popular: $('#is_popular').checked,
calories: parseInt($('#calories').value) || null,
};
if (imageUrl) formData.image_url = imageUrl;
let dbErr;
if (editingItemId) {
({ error: dbErr } = await supabase
.from('menu_items')
.update(formData)
.eq('id', editingItemId));
} else {
formData.available = true;
({ error: dbErr } = await supabase.from('menu_items').insert([formData]));
}
if (dbErr) {
console.error('Database error:', dbErr);
alert('Failed to save the item.');
} else {
itemModal.classList.add('hidden');
await loadMenuItems();
}
submitButton.disabled = false;
submitButton.textContent = 'Save Item';
}
async function deleteMenuItem(id) {
if (!confirm('Are you sure you want to delete this menu item?')) return;
const { error } = await supabase.from('menu_items').delete().eq('id', id);
if (error) alert('Could not delete item');
else loadMenuItems();
}
function bindMenuEvents() {
addItemBtn?.addEventListener('click', openAddModal);
closeModalBtn?.addEventListener('click', () =>
itemModal.classList.add('hidden')
);
cancelBtn?.addEventListener('click', () =>
itemModal.classList.add('hidden')
);
itemForm?.addEventListener('submit', handleMenuFormSubmit);
menuTableBody?.addEventListener('click', (e) => {
const target = e.target.closest('button');
if (!target) return;
const id = target.dataset.id;
if (target.classList.contains('status-toggle'))
toggleMenuAvailability(id, target.dataset.currentStatus === 'true');
if (target.classList.contains('edit')) openEditModal(id);
if (target.classList.contains('delete')) deleteMenuItem(id);
});
}
// ==========================================
// 5. SUPPLEMENTS INVENTORY MANAGEMENT
// ==========================================
const supplementsSection = $('#supplements-section');
const supplementsTable = $('#supplements-table');
const supplementsTableBody = $('#supplements-table-body');
const loadingSupplements = $('#loading-supplements');
const addSuppBtn = $('#add-supplement-btn');
const suppModal = $('#supplement-modal');
const suppModalTitle = $('#supplement-modal-title');
const suppForm = $('#supplement-form');
const suppCloseBtn = $('#supplement-close-btn');
const suppCancelBtn = $('#supp-cancel-btn');
let currentEditingSuppId = null;
async function hasOrderHistory(productId) {
const { count, error } = await supabase
.from('supplement_order_items')
.select('id', { count: 'exact', head: true })
.eq('supplement_product_id', productId);
if (error) {
console.error('check history error:', error);
return true;
}
return (count ?? 0) > 0;
}
async function loadSupplements() {
if (loadingSupplements) loadingSupplements.classList.remove('hidden');
if (supplementsTable) supplementsTable.classList.add('hidden');
const { data, error } = await supabase
.from('supplement_products')
.select('*')
.order('created_at', { ascending: false });
if (error) {
console.error('Error fetching supplements:', error);
alert('Could not fetch supplements.');
loadingSupplements?.classList.add('hidden');
return;
}
if (supplementsTableBody) {
supplementsTableBody.innerHTML = '';
(data || []).forEach((p) => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>
<div class="item-info">
<img src="${
p.image_url || 'https://via.placeholder.com/50'
}" class="item-image" alt="${p.name}">
<div class="item-name-desc">
<div class="item-name">${p.name} ${
p.is_featured ? '⭐' : ''
}</div>
<div class="item-desc">${p.tags || ''}</div>
</div>
</div>
</td>
<td>${p.brand || '-'}</td>
<td>${p.category}</td>
<td>${fmtBDT(p.price)}</td>
<td>${
p.stock > 0
? p.stock
: '<span class="status-badge danger">Out of stock</span>'
}</td>
<td>
<button class="status-toggle ${
p.available ? 'available' : 'unavailable'
}" data-supp-id="${p.id}" data-current-status="${
p.available
}">${p.available ? 'Available' : 'Unavailable'}</button>
</td>
<td>
<div class="action-buttons">
<button class="action-btn edit-supp" data-supp-id="${
p.id
}"><i data-lucide="edit"></i></button>
<button class="action-btn delete-supp" data-supp-id="${
p.id
}"><i data-lucide="trash-2"></i></button>
</div>
</td>
`;
supplementsTableBody.appendChild(tr);
});
}
window.lucide?.createIcons();
if (loadingSupplements) loadingSupplements.classList.add('hidden');
if (supplementsTable) supplementsTable.classList.remove('hidden');
}
function openAddSupplementModal() {
currentEditingSuppId = null;
suppModalTitle.textContent = 'Add Product';
suppForm.reset();
$('#supp-current-image').textContent = '';
suppModal.classList.remove('hidden');
window.lucide?.createIcons();
}
async function openEditSupplementModal(id) {
const { data, error } = await supabase
.from('supplement_products')
.select('*')
.eq('id', id)
.single();
if (error) {
console.error(error);
alert('Could not load product.');
return;
}
currentEditingSuppId = id;
suppModalTitle.textContent = 'Edit Product';
const setVal = (elId, val = '') => {
const el = document.getElementById(elId);
if (el) el.value = val ?? '';
};
setVal('supplement-id', data.id);
setVal('supp-name', data.name);
setVal('supp-brand', data.brand || '');
setVal('supp-category', data.category);
setVal('supp-price', data.price);
setVal('supp-buying', data.buying_price ?? 0);
setVal('supp-stock', data.stock);
setVal('supp-description', data.description || '');
setVal('supp-tags', data.tags || '');
setVal('supp-rating', data.rating || '');
const feat = $('#supp-featured');
if (feat) feat.checked = !!data.is_featured;
const currentImg = $('#supp-current-image');
if (currentImg) {
currentImg.textContent = data.image_url
? `Current: ${data.image_url.split('/').pop()}`
: 'No image uploaded.';
}
suppModal.classList.remove('hidden');
window.lucide?.createIcons();
}
async function handleSupplementSubmit(e) {
e.preventDefault();
const btn = e.target.querySelector('button[type="submit"]');
btn.disabled = true;
btn.textContent = 'Saving…';
const gv = (id) => document.getElementById(id)?.value ?? '';
const required = {
name: gv('supp-name').trim(),
category: gv('supp-category'),
price: Number(gv('supp-price')),
buying_price: Number(gv('supp-buying')),
stock: Number(gv('supp-stock')),
};
if (
!required.name ||
!required.category ||
isNaN(required.price) ||
isNaN(required.buying_price) ||
isNaN(required.stock)
) {
alert('Please fill in Name, Category, Price, Buying Price, and Stock.');
btn.disabled = false;
btn.textContent = 'Save Product';
return;
}
let imageUrl = null;
const imageFile = document.getElementById('supp-image')?.files?.[0];