-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
256 lines (218 loc) · 8.6 KB
/
script.js
File metadata and controls
256 lines (218 loc) · 8.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
// ✅ Import dependencies
import { patientSignUp, loginAndRedirect } from './firebase-auth.js';
import { db, auth } from './firebase-config.js';
import { onAuthStateChanged } from "https://www.gstatic.com/firebasejs/10.7.0/firebase-auth.js";
import {
doc, getDoc, addDoc, collection,
getDocs, updateDoc
} from "https://www.gstatic.com/firebasejs/10.7.0/firebase-firestore.js";
let userId = null;
onAuthStateChanged(auth, async (user) => {
if (user) {
userId = user.uid;
try {
await loadPatientInfo();
await loadMedicationLogs();
await loadPrescriptionHistory();
} catch (error) {
console.error("Error loading data:", error);
}
} else {
window.location.href = "page1.html";
}
});
async function loadPatientInfo() {
try {
const docSnap = await getDoc(doc(db, "patients", userId));
if (docSnap.exists()) {
const data = docSnap.data();
document.getElementById("patient-name").textContent = data.name;
document.getElementById("patient-age").textContent = data.age;
document.getElementById("patient-gender").textContent = data.gender;
document.getElementById("patient-doctor").textContent = data.doctor;
document.getElementById("patient-course").textContent = data.course;
} else {
console.log("No patient data found.");
}
} catch (error) {
console.error("Error loading patient info:", error);
}
}
window.addMedicine = async function () {
try {
const name = document.getElementById("medicine-name").value;
const time = document.getElementById("medicine-time").value;
const qty = document.getElementById("medicine-qty").value;
const dayChecks = document.querySelectorAll('#day-checks input[type="checkbox"]:checked');
const days = Array.from(dayChecks).map(cb => cb.value);
if (!name || !time || !qty || days.length === 0) {
alert("Please fill in all fields and select at least one day.");
return;
}
const logData = {
medicine: name,
time: time,
quantity: parseInt(qty),
date: new Date().toISOString().split('T')[0],
day: new Date().toLocaleString('en-us', { weekday: 'long' }),
days: days,
status: "not taken"
};
await addDoc(collection(db, "patients", userId, "logs"), logData);
alert("Medicine added to log.");
await loadMedicationLogs();
} catch (error) {
console.error("Error adding medicine:", error);
}
};
async function loadMedicationLogs() {
try {
const logsRef = collection(db, "patients", userId, "logs");
const snapshot = await getDocs(logsRef);
const logs = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
const container = document.getElementById("medication-logs");
if (!container) return;
container.innerHTML = "<h2>Medication Logs</h2>";
const now = new Date();
const todayUTC = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const pastLogs = [], todayLogs = [], upcomingLogs = [];
logs.forEach(log => {
const logDateUTC = new Date(`${log.date}T00:00:00Z`);
if (logDateUTC < todayUTC) pastLogs.push(log);
else if (logDateUTC.getTime() === todayUTC.getTime()) todayLogs.push(log);
else upcomingLogs.push(log);
});
const sortedPast = [...pastLogs].sort((a, b) => a.date.localeCompare(b.date));
let streak = 0;
for (let log of sortedPast) {
if (log.status === "taken") streak++;
else streak = 0;
}
container.innerHTML += `<p><strong>Current Streak:</strong> ${streak} ${streak === 1 ? 'day' : 'days'}</p>`;
const renderGroup = (title, logsArray, disable = false) => {
if (logsArray.length === 0) return;
const section = document.createElement("div");
section.innerHTML = `<h3 style="margin-top:1rem;">${title}</h3>`;
const grouped = {};
logsArray.forEach(log => {
if (!grouped[log.date]) grouped[log.date] = [];
grouped[log.date].push(log);
});
Object.keys(grouped).sort().forEach(date => {
const dateGroup = document.createElement("div");
dateGroup.innerHTML = `<h4>${date}</h4>`;
grouped[date].forEach(log => {
const isChecked = log.status === "taken" ? "checked" : "";
const isDisabled = disable ? "disabled" : "";
const logDiv = document.createElement("div");
logDiv.innerHTML = `
<p>
<strong>${log.medicine}</strong> — ${log.time} (${log.day})<br>
<label>
<input type="checkbox" ${isChecked} ${isDisabled}
onchange="toggleTaken('${log.id}', this.checked)">
Taken
</label><br>
<button onclick="compareWithGemini('${log.medicine}')">💡 Compare Generic</button>
</p>
`;
dateGroup.appendChild(logDiv);
});
section.appendChild(dateGroup);
});
container.appendChild(section);
};
renderGroup("✅ Past Logs", pastLogs);
renderGroup("🟢 Today's Logs", todayLogs);
renderGroup("⏳ Upcoming Logs", upcomingLogs, true);
} catch (error) {
console.error("Error loading medication logs:", error);
}
}
async function loadPrescriptionHistory() {
try {
const historyRef = collection(db, "patients", userId, "prescriptions");
const snapshot = await getDocs(historyRef);
const container = document.getElementById("prescription-history");
if (!container) return;
container.innerHTML = snapshot.empty ? "<p>No prescriptions uploaded yet.</p>" : "";
snapshot.forEach(docSnap => {
const data = docSnap.data();
const div = document.createElement("div");
div.style.border = "1px solid #ccc";
div.style.margin = "10px 0";
div.style.padding = "10px";
div.style.borderRadius = "8px";
div.innerHTML = `
<img src="${data.imageURL}" alt="Prescription" style="max-width: 100%; height: auto; border: 1px solid #999;" />
<p><strong>Extracted Text:</strong><br>${data.text.replace(/\n/g, '<br>')}</p>
<p><strong>Duration:</strong> ${data.duration} days</p>
<p><strong>Uploaded At:</strong> ${new Date(data.timestamp).toLocaleString()}</p>
`;
container.appendChild(div);
});
} catch (error) {
console.error("Error loading prescription history:", error);
}
}
window.toggleTaken = async function (logId, isChecked) {
try {
const logRef = doc(db, "patients", userId, "logs", logId);
await updateDoc(logRef, { status: isChecked ? "taken" : "not taken" });
} catch (error) {
console.error("Error updating log status:", error);
}
};
// 🌙 Dark Mode
function toggleDarkMode() {
document.body.classList.toggle('dark-mode');
}
window.toggleDarkMode = toggleDarkMode;
// 👤 Signup/Login
const loginBtn = document.getElementById('login-btn');
if (loginBtn) {
loginBtn.addEventListener('click', async () => {
const email = document.querySelector('input[type="email"]').value;
const password = document.querySelector('input[type="password"]').value;
await loginAndRedirect(email, password);
});
}
const patientForm = document.getElementById('patientSignupForm');
if (patientForm) {
patientForm.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = {
name: document.getElementById('name').value,
age: document.getElementById('age').value,
gender: document.getElementById('gender').value,
email: document.getElementById('email').value,
password: document.getElementById('password').value,
doctor: document.getElementById('doctor-name').value,
course: document.getElementById('course-duration').value,
};
await patientSignUp(formData);
document.getElementById('successMsg').style.display = 'block';
});
}
// 🤖 Gemini AI Integration
const GEMINI_API_KEY = "AIzaSyBl_Hb-Z0gofykKlkT31v_qhbn-B-1zU9c";
async function getGenericAlternative(medicineName) {
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${GEMINI_API_KEY}`;
const prompt = `Suggest a cheaper or generic alternative for the medicine "${medicineName}". Include the composition and cost benefit. Respond concisely.`;
const body = {
contents: [{ parts: [{ text: prompt }] }]
};
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
const data = await res.json();
console.log("📦 Gemini API response:", data); // 👈 add this
try {
const reply = data.candidates?.[0]?.content?.parts?.[0]?.text;
return reply || "No suggestion from Gemini.";
} catch (e) {
return "❌ Failed to extract suggestion.";
}
}