-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1695 lines (1459 loc) · 77.2 KB
/
Copy pathscript.js
File metadata and controls
1695 lines (1459 loc) · 77.2 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 ---
var SUPABASE_URL = 'https://ioaqlcltvakuqqehkyor.supabase.co';
var SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImlvYXFsY2x0dmFrdXFxZWhreW9yIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjYxNTk1MzksImV4cCI6MjA4MTczNTUzOX0._7ISJbfJzryBJWmtRuN72F-JZpYdvJxsltwwhombPtE';
var supabaseClient;
var currentUser = null;
var myChart = null;
var doctorCharts = {};
var currentChartTable = 'weight_logs';
var currentChartDays = 7;
var allHistoryData = [];
var allAppointments = [];
var userRole = 'patient'; // Default role
const countriesList = [
"United States", "Canada", "United Kingdom", "Australia", "Germany", "France", "Italy", "Spain", "Brazil", "India",
"China", "Japan", "South Korea", "Mexico", "Russia", "South Africa", "Nigeria", "Egypt", "Kenya", "Ghana"
];
try {
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
console.warn("Supabase credentials missing.");
} else {
supabaseClient = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
}
} catch (err) { console.error("Init Error", err); }
// --- 2. AUTH & VIEW STATE ---
if (supabaseClient) {
supabaseClient.auth.onAuthStateChange(async (event, session) => {
const landing = document.getElementById('landing-view');
const dashboard = document.getElementById('dashboard-view');
const deco = document.getElementById('decorations');
console.log("Auth Event:", event);
// US-3: Password Recovery Handling
if (event === 'PASSWORD_RECOVERY') {
document.querySelectorAll('.modal-overlay').forEach(m => m.classList.remove('active'));
const updateModal = document.getElementById('update-password-modal');
if (updateModal) updateModal.classList.add('active');
return; // Stop further routing logic
}
if (session && session.user) {
// LOGGED IN
currentUser = session.user;
// US-1 & US-2: Role-Based Routing
// Source of Truth: user_metadata.role
const metaRole = (session.user.user_metadata && session.user.user_metadata.role) ? session.user.user_metadata.role : 'patient';
// Set Global Role
userRole = metaRole;
console.log("User Role Detected:", userRole);
landing.style.display = 'none';
dashboard.style.display = 'grid';
if(deco) deco.style.display = 'none';
closeModals();
resetDates();
populateCountries();
if (Notification.permission !== "granted") Notification.requestPermission();
// Setup Interface based on Role
setupSidebar();
if(userRole === 'doctor') {
switchView('doctor-dashboard');
loadDoctorStatus();
renderScheduleGrid();
loadDoctorDashboardData();
} else {
loadDashboardData();
loadProfileSettings();
switchView('dashboard');
}
updateWelcomeMessage();
updateAvatarUI(session.user.user_metadata?.avatar_url);
} else {
// LOGGED OUT
currentUser = null;
userRole = 'patient';
landing.style.display = 'block';
dashboard.style.display = 'none';
if(deco) deco.style.display = 'block';
}
});
}
// NEW: Dynamic Sidebar Setup
function setupSidebar() {
const list = document.getElementById('nav-list-container');
list.innerHTML = '';
if(userRole === 'patient') {
list.innerHTML = `
<li class="nav-item active">
<a href="#" class="nav-link" onclick="switchView('dashboard', this); return false;">
<i class="fa-solid fa-house"></i><span>Dashboard</span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link" onclick="switchView('metrics', this); return false;">
<i class="fa-solid fa-heart-pulse"></i><span>Health Metrics</span>
</a>
</li>
<li class="nav-item"><a href="#" class="nav-link" onclick="openModal('log-bp'); return false;"><i class="fa-solid fa-heart-pulse text-gray-500"></i><span>Log BP</span></a></li>
<li class="nav-item"><a href="#" class="nav-link" onclick="openModal('log-weight'); return false;"><i class="fa-solid fa-weight-scale text-gray-500"></i><span>Log Weight</span></a></li>
<li class="nav-item"><a href="#" class="nav-link" onclick="openModal('log-glucose'); return false;"><i class="fa-solid fa-droplet text-gray-500"></i><span>Log Glucose</span></a></li>
<li class="nav-item"><a href="#" class="nav-link" onclick="openModal('log-temp'); return false;"><i class="fa-solid fa-temperature-half text-gray-500"></i><span>Log Temp</span></a></li>
<li class="nav-item">
<a href="#" class="nav-link" onclick="switchView('appointments', this); return false;">
<i class="fa-regular fa-calendar-check"></i><span>Appointments</span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link" onclick="switchView('settings', this); return false;">
<i class="fa-solid fa-gear"></i><span>Settings</span>
</a>
</li>
`;
} else {
// DOCTOR SIDEBAR
list.innerHTML = `
<li class="nav-item active">
<a href="#" class="nav-link" onclick="switchView('doctor-dashboard', this); return false;">
<i class="fa-solid fa-house"></i><span>Dashboard</span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link" onclick="switchView('doctor-appointments', this); return false;">
<i class="fa-regular fa-calendar-check"></i><span>Appointments</span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link" onclick="switchView('doctor-settings', this); return false;">
<i class="fa-solid fa-gear"></i><span>Settings</span>
</a>
</li>
`;
}
}
function resetDates() {
const today = new Date().toISOString().split('T')[0];
['weight-date', 'bp-date', 'temp-date', 'gluc-date'].forEach(id => {
const el = document.getElementById(id);
if(el) el.value = today;
});
}
function populateCountries() {
const select = document.getElementById('settings-address-country');
if(select && select.options.length <= 1) {
countriesList.forEach(c => {
const opt = document.createElement('option');
opt.value = c;
opt.textContent = c;
select.appendChild(opt);
});
}
}
// --- 3. UI LOGIC ---
function switchView(viewName, element) {
// Hide all views first
document.querySelectorAll('.patient-view, .doctor-view').forEach(el => el.style.display = 'none');
// Handle Sidebar Active State
document.querySelectorAll('.nav-item').forEach(el => el.classList.remove('active'));
if (element && element.parentElement) {
element.parentElement.classList.add('active');
} else {
// Auto-highlight if triggered programmatically
const link = document.querySelector(`.nav-link[onclick*="'${viewName}'"]`);
if(link) link.parentElement.classList.add('active');
}
// Show requested view
const target = document.getElementById('view-' + viewName);
if(target) {
target.style.display = 'block';
if (viewName === 'metrics' && myChart) myChart.resize();
if (viewName === 'doctor-dashboard') {
setTimeout(() => {
if(doctorCharts.weekly) doctorCharts.weekly.resize();
if(doctorCharts.growth) doctorCharts.growth.resize();
}, 100);
}
if (viewName === 'doctor-appointments') {
loadDoctorAppointmentsTab();
}
}
}
// --- 4. AUTH LOGIC ---
async function logout() {
if (!supabaseClient) { window.location.reload(); return; }
try {
await supabaseClient.auth.signOut();
} catch (error) {
console.error("Error signing out:", error);
} finally {
currentUser = null;
userRole = 'patient';
const landing = document.getElementById('landing-view');
const dashboard = document.getElementById('dashboard-view');
const deco = document.getElementById('decorations');
if (landing) landing.style.display = 'block';
if (dashboard) dashboard.style.display = 'none';
if (deco) deco.style.display = 'block';
closeModals();
}
}
async function signInWithGoogle() {
const redirectUrl = window.location.href.split('#')[0];
await supabaseClient.auth.signInWithOAuth({
provider: 'google',
options: { redirectTo: redirectUrl, queryParams: { prompt: 'select_account' } }
});
}
function signInWithPhone() { alert("Phone Auth requires paid plan/setup. Use Email or Google."); }
// Toggle logic for Doctor Signup fields
function toggleDoctorSignupFields() {
const isDoc = document.getElementById('signup-as-doctor').checked;
document.getElementById('doctor-signup-fields').style.display = isDoc ? 'block' : 'none';
}
// LOGIN FORM HANDLER
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = document.getElementById('btn-login-submit');
const originalText = btn.textContent;
try {
btn.textContent = "Logging in...";
btn.disabled = true;
const { error } = await supabaseClient.auth.signInWithPassword({
email: document.getElementById('login-email').value,
password: document.getElementById('login-password').value
});
if (error) {
document.getElementById('login-error').textContent = error.message;
document.getElementById('login-error').style.display = 'block';
}
} catch (err) {
console.error(err);
} finally {
if(document.getElementById('login-error').style.display === 'block') {
btn.textContent = originalText;
btn.disabled = false;
}
}
});
// SIGNUP FORM HANDLER
document.getElementById('signup-form').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('signup-email').value;
const password = document.getElementById('signup-password').value;
const confirmPass = document.getElementById('signup-confirm-password').value;
if (password !== confirmPass) {
document.getElementById('signup-error').textContent = "Passwords do not match.";
document.getElementById('signup-error').style.display = 'block';
return;
}
// Logic to prevent Database Trigger Errors (NOT NULL constraints)
const isDoc = document.getElementById('signup-as-doctor').checked;
let metadata = {};
if (isDoc) {
// Validate Doctor Fields
const fullName = document.getElementById('signup-fullname').value;
const license = document.getElementById('signup-license').value;
if (!fullName || !license) {
document.getElementById('signup-error').textContent = "Doctors must provide Name and License Number.";
document.getElementById('signup-error').style.display = 'block';
return;
}
metadata = {
role: 'doctor',
full_name: fullName,
license_number: license,
specialty: document.getElementById('signup-specialty').value
};
} else {
const fallbackName = email.split('@')[0];
metadata = {
role: 'patient',
full_name: fallbackName
};
}
const { error } = await supabaseClient.auth.signUp({
email: email,
password: password,
options: {
data: metadata
}
});
if (error) {
document.getElementById('signup-error').textContent = error.message;
document.getElementById('signup-error').style.display = 'block';
} else {
alert("Signup successful! Please check your email for verification.");
closeModals();
}
});
// PASSWORD RESET REQUEST
document.getElementById('reset-form').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('reset-email').value;
const btn = e.target.querySelector('button');
btn.textContent = "Sending...";
const { error } = await supabaseClient.auth.resetPasswordForEmail(email, {
redirectTo: window.location.href,
});
if (error) {
document.getElementById('reset-error').textContent = error.message;
document.getElementById('reset-error').style.display = 'block';
} else {
document.getElementById('reset-success').textContent = "Check your email for the reset link.";
document.getElementById('reset-success').style.display = 'block';
e.target.reset();
}
btn.textContent = "Send Reset Link";
});
// PASSWORD UPDATE HANDLER
document.getElementById('update-pass-form').addEventListener('submit', async (e) => {
e.preventDefault();
const newPass = document.getElementById('new-password').value;
const confirmPass = document.getElementById('confirm-new-password').value;
const btn = e.target.querySelector('button');
if (newPass !== confirmPass) {
document.getElementById('update-pass-error').textContent = "Passwords do not match.";
document.getElementById('update-pass-error').style.display = 'block';
return;
}
btn.textContent = "Updating...";
const { error } = await supabaseClient.auth.updateUser({ password: newPass });
if (error) {
document.getElementById('update-pass-error').textContent = error.message;
document.getElementById('update-pass-error').style.display = 'block';
} else {
document.getElementById('update-pass-success').textContent = "Password updated successfully!";
document.getElementById('update-pass-success').style.display = 'block';
setTimeout(() => {
closeModals();
window.location.hash = '';
logout();
}, 2000);
}
btn.textContent = "Update Password";
});
// --- DOCTOR DASHBOARD DATA LOGIC ---
async function loadDoctorDashboardData() {
if(!currentUser) return;
const docId = currentUser.id;
// 1. Fetch All Appointments for this Doctor
const { data: appts, error } = await supabaseClient
.from('appointments')
.select('*')
.eq('doctor_id', docId);
if (error) { console.error("Error fetching doctor data", error); return; }
// --- Calculate Stats ---
const totalPatients = new Set(appts.map(a => a.user_id)).size;
// Fix: Robust Date matching for Today
const todayLocalStr = new Date().toLocaleDateString();
const todayAppts = appts.filter(a => new Date(a.appointment_date).toLocaleDateString() === todayLocalStr && a.status === 'Confirmed').length;
const pending = appts.filter(a => a.status === 'pending').length;
const completed = appts.filter(a => a.status === 'completed').length;
const totalCount = appts.length;
const successRate = totalCount > 0 ? Math.round((completed / totalCount) * 100) : 0;
// Update Stats UI
const docStatPatients = document.getElementById('doc-stat-patients');
if(docStatPatients) docStatPatients.textContent = totalPatients;
const docStatToday = document.getElementById('doc-stat-today');
if(docStatToday) docStatToday.textContent = todayAppts;
const docStatPending = document.getElementById('doc-stat-pending');
if(docStatPending) docStatPending.textContent = pending;
const docStatSuccess = document.getElementById('doc-stat-success');
if(docStatSuccess) docStatSuccess.textContent = successRate + '%';
// --- Populate Recent Activity ---
const recentContainer = document.getElementById('doctor-recent-activity');
if(recentContainer) {
recentContainer.innerHTML = '';
// Sort by date desc and take top 5
const recentAppts = [...appts].sort((a,b) => new Date(b.appointment_date) - new Date(a.appointment_date)).slice(0, 5);
if (recentAppts.length === 0) {
recentContainer.innerHTML = '<p class="text-xs text-gray-500 text-center">No recent activity.</p>';
} else {
recentAppts.forEach(a => {
const timeAgo = getTimeAgo(new Date(a.appointment_date));
const initials = getInitials(a.patient_name || a.user_id);
const displayName = a.patient_name || ("Patient " + a.user_id.substring(0, 4));
const item = `
<div class="flex items-center gap-4 border-b border-gray-100 pb-3">
<div class="profile-pic" style="background:#e5e7eb; color:#555;">${initials}</div>
<div class="flex-1">
<h4 class="font-bold text-sm">${displayName}</h4>
<p class="text-xs text-gray-500">${a.type || 'Appointment'}</p>
</div>
<span class="text-xs text-gray-400">${timeAgo}</span>
</div>
`;
recentContainer.innerHTML += item;
});
}
}
// --- Update Charts (Weekly) ---
updateDoctorWeeklyChart(appts);
// --- Update Charts (Growth) ---
updateDoctorGrowthChart(appts);
}
// --- UPDATED: DOCTOR APPOINTMENTS TAB LOGIC ---
async function loadDoctorAppointmentsTab() {
if(!currentUser) return;
const docId = currentUser.id;
// Fetch Appointments
const { data: appts, error } = await supabaseClient
.from('appointments')
.select('*')
.eq('doctor_id', docId)
.order('appointment_date', { ascending: true });
if(error) return;
// Time Logic
const now = new Date();
const todayLocalStr = now.toLocaleDateString();
// 1. Pending: Strictly 'pending' status
const pendingList = appts.filter(a => a.status === 'pending');
// 2. Upcoming: Strictly 'confirmed' status
const upcomingList = appts.filter(a => a.status === 'Confirmed' || a.status === 'confirmed');
// 3. Past: ONLY completed (Fix 1: hiding cancelled/declined)
const pastList = appts.filter(a => a.status === 'completed');
// Update Stats (Fix 4: accurate local date count for Today)
const todayCount = appts.filter(a => new Date(a.appointment_date).toLocaleDateString() === todayLocalStr && (a.status === 'Confirmed' || a.status === 'confirmed')).length;
document.getElementById('doc-appt-today-count').textContent = todayCount;
document.getElementById('doc-appt-pending-count').textContent = pendingList.length;
document.getElementById('doc-appt-total-count').textContent = upcomingList.length;
// Render Lists
renderDocSection('doc-pending-list', pendingList, 'pending');
renderDocSection('doc-upcoming-list', upcomingList, 'upcoming');
renderDocSection('doc-past-list', pastList, 'past');
}
function updateDoctorWeeklyChart(appts) {
if (!doctorCharts.weekly) initDoctorCharts();
const dayCounts = [0, 0, 0, 0, 0, 0, 0];
appts.forEach(a => {
const d = new Date(a.appointment_date);
const dayIndex = d.getDay();
const chartIndex = (dayIndex + 6) % 7;
dayCounts[chartIndex]++;
});
doctorCharts.weekly.data.datasets[0].data = dayCounts;
doctorCharts.weekly.update();
}
function updateDoctorGrowthChart(appts) {
if (!doctorCharts.growth) initDoctorCharts();
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const today = new Date();
const labels = [];
const dataPoints = [];
for (let i = 5; i >= 0; i--) {
const d = new Date(today.getFullYear(), today.getMonth() - i, 1);
labels.push(monthNames[d.getMonth()]);
const endOfMonth = new Date(today.getFullYear(), today.getMonth() - i + 1, 0, 23, 59, 59);
const uniquePatients = new Set(
appts
.filter(a => new Date(a.appointment_date) <= endOfMonth)
.map(a => a.user_id)
);
dataPoints.push(uniquePatients.size);
}
doctorCharts.growth.data.labels = labels;
doctorCharts.growth.data.datasets[0].data = dataPoints;
doctorCharts.growth.update();
}
function getTimeAgo(date) {
const seconds = Math.floor((new Date() - date) / 1000);
let interval = seconds / 31536000;
if (interval > 1) return Math.floor(interval) + " years ago";
interval = seconds / 2592000;
if (interval > 1) return Math.floor(interval) + " months ago";
interval = seconds / 86400;
if (interval > 1) return Math.floor(interval) + " days ago";
interval = seconds / 3600;
if (interval > 1) return Math.floor(interval) + " hours ago";
interval = seconds / 60;
if (interval > 1) return Math.floor(interval) + " mins ago";
return "Just now";
}
// --- DOCTOR DASHBOARD CHARTS ---
function initDoctorCharts() {
if(doctorCharts.weekly) return; // Already init
const ctx1 = document.getElementById('doctorWeeklyChart').getContext('2d');
doctorCharts.weekly = new Chart(ctx1, {
type: 'bar',
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [{
label: 'Appointments',
data: [0, 0, 0, 0, 0, 0, 0], // Init empty
backgroundColor: '#2ecc71',
borderRadius: 5
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
y: { grid: { borderDash: [5, 5] }, beginAtZero: true, ticks: { stepSize: 1 } },
x: { grid: { display: false } }
}
}
});
const ctx2 = document.getElementById('doctorGrowthChart').getContext('2d');
doctorCharts.growth = new Chart(ctx2, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Total Patients',
data: [],
borderColor: '#2ecc71',
tension: 0.4,
pointBackgroundColor: '#2ecc71',
pointRadius: 4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
y: { grid: { borderDash: [5, 5] }, min: 0, ticks: { stepSize: 1 } },
x: { grid: { display: false } }
}
}
});
}
// --- SHARED UI LOGIC ---
function updateWelcomeMessage() {
if (!currentUser) return;
const now = new Date();
const hour = now.getHours();
let greeting = "Good Morning";
if (hour >= 12 && hour < 18) greeting = "Good Afternoon";
else if (hour >= 18) greeting = "Good Evening";
let name = "User";
if (currentUser.user_metadata && currentUser.user_metadata.full_name) {
name = currentUser.user_metadata.full_name;
} else if (currentUser.email) {
name = currentUser.email.split('@')[0];
}
if(userRole === 'doctor' && !name.toLowerCase().includes('dr.')) {
name = "Dr. " + name.charAt(0).toUpperCase() + name.slice(1);
}
const el = document.getElementById('welcome-msg');
if (el) el.textContent = `${greeting}, ${name}`;
}
function updateAvatarUI(avatarUrl) {
const headerAvatar = document.getElementById('header-avatar');
const topProfilePic = document.querySelector('.dash-header-area .profile-pic');
const name = (currentUser.user_metadata && currentUser.user_metadata.full_name) || (currentUser.email ? currentUser.email.split('@')[0] : "User");
const initials = getInitials(name);
const content = avatarUrl ? `<img src="${avatarUrl}" alt="Profile">` : initials;
if (headerAvatar) headerAvatar.innerHTML = content;
if (topProfilePic) topProfilePic.innerHTML = content;
}
// --- 5. DATA FETCH LOGIC (PATIENT) ---
async function loadDashboardData() {
updateStatCard('weight_logs', 'weight', 'val-weight', 'kg');
updateStatCard('bp_logs', 'systolic', 'val-bp', '');
updateStatCard('glucose_logs', 'level', 'val-gluc', 'mg/dL');
updateStatCard('temp_logs', 'temperature', 'val-temp', '°C');
updateChart(currentChartTable);
loadHistory();
loadAppointments();
countMedicalRecords();
loadHealthTrends();
loadHealthAlerts();
}
// Consolidated Patient Appt Logic
async function loadAppointments() {
if(!currentUser) return;
try {
const { data, error } = await supabaseClient.from('appointments').select('*').eq('user_id', currentUser.id).order('appointment_date', { ascending: true });
if (error || !data) return;
allAppointments = data;
const now = new Date();
const futureAppts = data.filter(a => new Date(a.appointment_date) >= now && a.status !== 'cancelled' && a.status !== 'declined');
const pastAppts = data.filter(a => new Date(a.appointment_date) < now && a.status === 'completed');
const virtualCount = data.filter(a => a.type.toLowerCase().includes('video') || a.type.toLowerCase().includes('audio')).length;
const inPersonCount = data.filter(a => a.type.toLowerCase().includes('in-person')).length;
const dashCount = document.getElementById('upcoming-count');
if(dashCount) dashCount.textContent = futureAppts.length;
document.getElementById('appt-stat-total').textContent = futureAppts.length;
document.getElementById('appt-stat-virtual').textContent = virtualCount;
document.getElementById('appt-stat-inperson').textContent = inPersonCount;
document.getElementById('appt-stat-past').textContent = pastAppts.length;
const dashList = document.getElementById('dashboard-appointment-list');
if(dashList) renderAppointmentList(dashList, futureAppts.slice(0,3));
const mainList = document.getElementById('detailed-appointment-list');
if(mainList) renderDetailedList(mainList, futureAppts);
const pastList = document.getElementById('past-appointment-list');
if(pastList) renderPastList(pastList, pastAppts.slice(0, 5));
} catch (e) { console.error("Appt Load Error", e); }
}
// Patient Renderers
function renderAppointmentList(container, data) {
if (!data.length) { container.innerHTML = `<div class="loading-cell text-xs text-gray-500">No upcoming appointments.</div>`; return; }
container.innerHTML = '';
data.forEach(appt => {
const dateStr = formatAppointmentDate(new Date(appt.appointment_date));
// Audio UI handling
let typeHtml = '';
if(appt.type.toLowerCase().includes('video')) {
typeHtml = `<p class="text-xs text-blue-500"><i class="fa-solid fa-video"></i> Video</p>`;
} else if (appt.type.toLowerCase().includes('audio')) {
typeHtml = `<p class="text-xs text-purple-500"><i class="fa-solid fa-phone"></i> Audio</p>`;
} else {
typeHtml = `<p class="text-xs text-gray-500">In-person</p>`;
}
container.innerHTML += `<div class="appointment-item"><div class="doctor-avatar bg-green-500 text-white">${getInitials(appt.doctor_name)}</div><div class="flex-1"><h4 class="font-bold text-sm">${appt.doctor_name}</h4><p class="text-xs text-gray-500">${appt.specialty}</p></div><div class="text-right"><p class="text-xs font-bold">${dateStr}</p>${typeHtml}</div></div>`;
});
}
function renderDetailedList(container, data) {
if (!data.length) { container.innerHTML = `<p class="text-center-muted">No upcoming appointments.</p>`; return; }
container.innerHTML = '';
data.forEach(appt => {
const dateObj = new Date(appt.appointment_date);
const dateStr = dateObj.toLocaleDateString();
const timeStr = dateObj.toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'});
let actionBtn = '';
if(appt.status === 'Confirmed' || appt.status === 'confirmed') {
if(appt.type.toLowerCase().includes('video')) {
actionBtn = `<button class="btn-sm bg-blue-500 text-white border-none mt-2 w-full justify-center" onclick="startVideoCall('${appt.id}')"><i class="fa-solid fa-video"></i> Join Video Call</button>`;
} else if (appt.type.toLowerCase().includes('audio')) {
actionBtn = `<button class="btn-sm bg-purple-500 text-white border-none mt-2 w-full justify-center" onclick="startVideoCall('${appt.id}')"><i class="fa-solid fa-phone"></i> Join Audio Call</button>`;
}
}
container.innerHTML += `
<div class="detailed-appt-card">
<div class="doctor-avatar bg-green-500" style="width:60px;height:60px;font-size:1.2rem;">${getInitials(appt.doctor_name)}</div>
<div>
<div class="flex justify-between items-start">
<div>
<h4 class="font-bold text-md">${appt.doctor_name}</h4>
<p class="text-sm text-gray-500">${appt.specialty}</p>
</div>
<span class="appt-status-badge ${appt.status === 'Confirmed' || appt.status === 'confirmed' ? 'status-confirmed' : 'status-pending'}">${appt.status}</span>
</div>
<div class="appt-details-grid">
<div class="appt-detail-item"><i class="fa-regular fa-calendar"></i> ${dateStr}</div>
<div class="appt-detail-item"><i class="fa-regular fa-clock"></i> ${timeStr}</div>
<div class="appt-detail-item" style="grid-column: span 3; color: #666; font-size: 0.85rem;"><i class="fa-solid fa-notes-medical"></i> ${appt.type}</div>
</div>
${actionBtn}
</div>
</div>`;
});
}
function renderPastList(container, data) {
if (!data.length) { container.innerHTML = `<p class="text-center-muted">No past appointments.</p>`; return; }
container.innerHTML = '';
data.forEach(appt => {
const dateStr = new Date(appt.appointment_date).toLocaleDateString();
container.innerHTML += `<div class="card p-6 mb-4 flex justify-between items-center"><div class="flex gap-4 items-center"><div class="doctor-avatar" style="background:#e5e7eb; color:#6b7280;">${getInitials(appt.doctor_name)}</div><div><h4 class="font-bold text-sm">${appt.doctor_name}</h4><p class="text-xs text-gray-500">${appt.specialty}</p></div></div><div class="text-right"><p class="text-sm text-gray-500">${dateStr}</p><p class="text-xs text-green-600 font-bold">Completed</p></div></div>`;
});
}
// Global Helpers
function getInitials(name) { if(!name) return "DR"; return name.split(" ").map(n=>n[0]).join("").substring(0,2).toUpperCase(); }
function formatAppointmentDate(date) { return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); }
async function updateStatCard(table, col, elemId, unit) {
const { data } = await supabaseClient.from(table).select('*').eq('user_id', currentUser.id).order('date', {ascending:false}).limit(1);
const cardContainer = document.getElementById(elemId).parentElement.parentElement;
const oldTime = cardContainer.querySelector('.timestamp-label');
if(oldTime) oldTime.remove();
if(data && data.length > 0) {
let val = data[0][col];
if(table === 'bp_logs') val = `${data[0].systolic}/${data[0].diastolic}`;
document.getElementById(elemId).textContent = val;
const dbDateString = data[0].date;
const logDate = new Date(dbDateString + 'T00:00:00');
const today = new Date();
today.setHours(0,0,0,0);
const diffTime = today - logDate;
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
let timeStr = "Today";
if (diffDays === 1) timeStr = "Yesterday";
else if (diffDays > 1) timeStr = `${diffDays} days ago`;
const timeLabel = document.createElement('div');
timeLabel.className = 'timestamp-label text-xs text-gray-400 mt-1';
timeLabel.innerHTML = `<i class="fa-regular fa-clock mr-1"></i> ${timeStr}`;
document.getElementById(elemId).parentElement.appendChild(timeLabel);
} else {
document.getElementById(elemId).textContent = '--';
}
}
function setChartRange(days, btn) { currentChartDays = days; document.querySelectorAll('.time-tabs .chart-select').forEach(b => b.classList.remove('active')); btn.classList.add('active'); updateChart(currentChartTable); }
async function updateChart(tableName, btnRef) {
currentChartTable = tableName;
if (!currentUser) return;
if(btnRef) { document.querySelectorAll('.chart-tabs .chart-select').forEach(b => b.classList.remove('active')); btnRef.classList.add('active'); }
const cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - currentChartDays);
const dateStr = cutoffDate.toISOString().split('T')[0];
const { data } = await supabaseClient.from(tableName).select('*').eq('user_id', currentUser.id).gte('date', dateStr).order('date', { ascending: true });
if (!data) return;
const labels = data.map(d => new Date(d.date).toLocaleDateString(undefined, {month:'short', day:'numeric'}));
let dataset = [];
const ctx = document.getElementById('healthChart').getContext('2d');
let gradient = ctx.createLinearGradient(0, 0, 0, 400); gradient.addColorStop(0, 'rgba(46, 204, 113, 0.2)'); gradient.addColorStop(1, 'rgba(46, 204, 113, 0)');
if (tableName === 'bp_logs') { dataset = [ { label: 'Systolic', data: data.map(d => d.systolic), borderColor: '#dc2626', tension: 0.4 }, { label: 'Diastolic', data: data.map(d => d.diastolic), borderColor: '#2563eb', tension: 0.4 } ]; }
else {
let key = tableName === 'glucose_logs' ? 'level' : (tableName === 'temp_logs' ? 'temperature' : 'weight');
dataset = [{ label: key.toUpperCase(), data: data.map(d => d[key]), borderColor: '#2ecc71', backgroundColor: gradient, borderWidth: 3, tension: 0.4, fill: true }];
}
if (myChart) myChart.destroy();
myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: dataset }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { x: { grid: { display: false } }, y: { grid: { borderDash: [5, 5] } } } } });
}
async function loadHistory() {
const tables = ['weight_logs', 'bp_logs', 'glucose_logs', 'temp_logs']; let combined = [];
for (let t of tables) {
const { data } = await supabaseClient.from(t).select('*').eq('user_id', currentUser.id).order('date', {ascending:false}).limit(5);
if(data) data.forEach(d => { d.type = t; combined.push(d); });
}
combined.sort((a,b) => new Date(b.date) - new Date(a.date));
allHistoryData = combined;
const tbody = document.getElementById('history-body');
if(tbody) {
tbody.innerHTML = '';
combined.slice(0, 10).forEach(item => {
let valStr = item.type === 'bp_logs' ? `${item.systolic}/${item.diastolic}` : (item.weight || item.level || item.temperature);
tbody.innerHTML += `
<tr>
<td>${item.date}</td>
<td>${item.type.replace('_logs','').toUpperCase()}</td>
<td>${valStr}</td>
<td>
<button class="action-btn" onclick="editEntry('${item.type}', '${item.id}')" title="Edit"><i class="fa-solid fa-pen"></i></button>
<button class="action-btn delete" onclick="deleteEntry('${item.type}', '${item.id}')" title="Delete"><i class="fa-solid fa-trash"></i></button>
</td>
</tr>`;
});
}
}
async function deleteEntry(table, id) {
if(confirm("Are you sure you want to delete this record? This cannot be undone.")) {
const { error } = await supabaseClient.from(table).delete().eq('id', id);
if(error) {
alert("Error deleting: " + error.message);
} else {
loadDashboardData();
}
}
}
async function countMedicalRecords() {
if(!currentUser) return;
try {
const [w, b, g, t] = await Promise.all([
supabaseClient.from('weight_logs').select('*', { count: 'exact', head: true }).eq('user_id', currentUser.id),
supabaseClient.from('bp_logs').select('*', { count: 'exact', head: true }).eq('user_id', currentUser.id),
supabaseClient.from('glucose_logs').select('*', { count: 'exact', head: true }).eq('user_id', currentUser.id),
supabaseClient.from('temp_logs').select('*', { count: 'exact', head: true }).eq('user_id', currentUser.id)
]);
const total = (w.count || 0) + (b.count || 0) + (g.count || 0) + (t.count || 0);
const el = document.getElementById('record-count');
if(el) el.textContent = total;
} catch (e) {
const el = document.getElementById('record-count');
if(el) el.textContent = "--";
}
}
async function loadHealthTrends() {
if (!currentUser) return;
try {
const [bpData, glucoseData] = await Promise.all([
supabaseClient.from('bp_logs').select('systolic, pulse').eq('user_id', currentUser.id).order('date', {ascending:false}).limit(7),
supabaseClient.from('glucose_logs').select('level').eq('user_id', currentUser.id).order('date', {ascending:false}).limit(7)
]);
// --- Heart Rate ---
const hrData = bpData.data || [];
const hrEl = document.getElementById('trend-hr-val');
const hrStatus = document.getElementById('trend-hr-status');
const hrBars = document.getElementById('trend-hr-bars');
let latestHr = (hrData.length > 0) ? (hrData[0].pulse || '--') : '--';
if(hrEl) hrEl.innerHTML = `${latestHr} <span class="text-xs text-gray-500 font-normal">bpm</span>`;
if(hrStatus && hrData.length > 0) {
const val = hrData[0].pulse;
if(val > 100) { hrStatus.textContent = 'High'; hrStatus.className = 'text-xs text-red-500 font-bold'; }
else if(val > 0) { hrStatus.textContent = 'Normal'; hrStatus.className = 'text-xs text-green-500 font-bold'; }
else hrStatus.textContent = '--';
}
if(hrBars) {
hrBars.innerHTML = '';
for(let i=0; i<7; i++) {
let h = 10;
if (i < hrData.length) {
let val = hrData[hrData.length - 1 - i].pulse || 0;
h = Math.min(100, Math.max(10, (val / 150) * 100));
}
hrBars.innerHTML += `<div class="trend-bar" style="height: ${h}%"></div>`;
}
}
// --- BP (Systolic) ---
const bpEl = document.getElementById('trend-bp-val');
const bpStatus = document.getElementById('trend-bp-status');
const bpBars = document.getElementById('trend-bp-bars');
const { data: bpFull } = await supabaseClient.from('bp_logs').select('systolic, diastolic, pulse').eq('user_id', currentUser.id).order('date', {ascending:false}).limit(7);
const fullBP = bpFull || [];
let latestSys = (fullBP.length > 0) ? fullBP[0].systolic : '--';
let latestDia = (fullBP.length > 0) ? fullBP[0].diastolic : '--';
if(bpEl) bpEl.innerHTML = `${latestSys}/${latestDia} <span class="text-xs text-gray-500 font-normal">mmHg</span>`;
if(bpStatus && fullBP.length > 0) {
const sys = fullBP[0].systolic;
const dia = fullBP[0].diastolic;
if(sys > 130 || dia > 85) { bpStatus.textContent = 'High'; bpStatus.className = 'text-xs text-red-500 font-bold'; }
else if (sys > 0) { bpStatus.textContent = 'Normal'; bpStatus.className = 'text-xs text-green-500 font-bold'; }
else bpStatus.textContent = '--';
}
if(bpBars) {
bpBars.innerHTML = '';
for(let i=0; i<7; i++) {
let h = 10;
if(i < fullBP.length) {
let val = fullBP[fullBP.length - 1 - i].systolic || 0;
h = Math.min(100, Math.max(10, (val / 180) * 100));
}
bpBars.innerHTML += `<div class="trend-bar" style="height: ${h}%"></div>`;
}
}
// --- Glucose ---
const glData = glucoseData.data || [];
const glEl = document.getElementById('trend-gl-val');
const glStatus = document.getElementById('trend-gl-status');
const glBars = document.getElementById('trend-gl-bars');
let latestGl = (glData.length > 0) ? glData[0].level : '--';
if(glEl) glEl.innerHTML = `${latestGl} <span class="text-xs text-gray-500 font-normal">mg/dL</span>`;
if(glStatus && glData.length > 0) {
const val = glData[0].level;
if(val > 140) { glStatus.textContent = 'High'; glStatus.className = 'text-xs text-yellow-600 font-bold'; }
else if (val > 0) { glStatus.textContent = 'Normal'; glStatus.className = 'text-xs text-green-500 font-bold'; }
else glStatus.textContent = '--';
}
if(glBars) {
glBars.innerHTML = '';
for(let i=0; i<7; i++) {
let h = 10;
if(i < glData.length) {
let val = glData[glData.length - 1 - i].level || 0;
h = Math.min(100, Math.max(10, (val / 200) * 100));
}
glBars.innerHTML += `<div class="trend-bar" style="height: ${h}%"></div>`;
}
}
} catch(e) { console.error("Trend Error", e); }
}
async function loadHealthAlerts() {
if(!currentUser) return;
const banner = document.getElementById('insight-banner');
const text = document.getElementById('insight-text');
const icon = banner.querySelector('.insight-icon');
banner.style.display = 'none'; // Reset
try {
const { data: weightData } = await supabaseClient.from('weight_logs').select('weight').eq('user_id', currentUser.id).order('date', {ascending:false}).limit(1);
const meta = currentUser.user_metadata || {};
if (meta.height && weightData && weightData.length > 0) {
const h_m = meta.height / 100;
const w_kg = weightData[0].weight;
const bmi = (w_kg / (h_m * h_m)).toFixed(1);
let bmiMsg = `Your BMI is ${bmi} (Normal).`;
let bmiColor = 'linear-gradient(135deg, #11998e 0%, #38ef7d 100%)';
if (bmi >= 25 && bmi < 30) {
bmiMsg = `Your BMI is ${bmi} (Overweight). Consider a balanced diet.`;