File size: 12,367 Bytes
730c086
 
 
 
 
 
0946fb8
730c086
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0ab5e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
730c086
 
 
 
 
 
 
 
21990cf
 
 
 
 
 
 
730c086
 
 
 
 
e0ab5e4
 
 
 
 
 
 
 
 
 
 
730c086
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7b16c3
730c086
c7b16c3
 
730c086
 
 
 
 
c7b16c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caaee88
730c086
 
 
 
 
 
 
 
 
 
c7b16c3
 
 
 
 
 
 
 
 
 
 
 
 
730c086
 
 
0d0f773
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6f6abe
0d0f773
 
 
 
 
 
 
730c086
0d0f773
730c086
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d0f773
730c086
 
 
 
 
e0ab5e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
730c086
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Past Analyzes - CTRL + ALT + HEAL</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="script.js"></script>
</head>
<body class="bg-[#F7F8F9] min-h-screen">
  <nav class="bg-white border border-gray-200 px-6 py-4 mb-8">
    <div class="container mx-auto flex justify-between items-center">
      <a href="index.html" class="text-2xl font-bold text-[#6B9080]">CTRL + ALT + HEAL</a>
        <ul class="hidden md:flex space-x-6 font-medium text-gray-800">
          <li><a href="index.html" class="nav-link">Home</a></li>
          <li><a href="analyzer.html" class="nav-link">Analyzer</a></li>
          <li><a href="past_data.html" class="nav-link">Past Reports</a></li>
          <li><a href="profile.html" class="nav-link">Profile</a></li>
          <li id="authNavItem"><a href="login.html" class="nav-link">Login</a></li>
        </ul>
    </div>
  </nav>

  <main class="max-w-4xl mx-auto px-4">
    <h1 class="text-2xl font-bold text-green-700 mb-4">Your Past Analyzes</h1>
    <p id="auth-status" class="text-sm text-gray-500 mb-6">Checking sign-in status…</p>

    <div id="recs-container" class="space-y-4">
      <p class="text-sm text-gray-500">Sign in to view your saved analyzes.</p>
    </div>
      <div
        class="bg-[var(--latte-cream)] border border-[var(--wisteria)] rounded-lg p-6 mb-8"
      >
        <h3 class="text-lg font-semibold mb-3">Ask Chatbot</h3>
        <div
          id="chat-output"
          class="space-y-2 h-48 overflow-auto text-sm rounded p-4"
        >
          <p><strong>Chatbot:</strong> Ask me something about your report</p>
        </div>
        <div class="flex mt-4 gap-2">
          <input
            type="text"
            id="user-question"
            placeholder="Ask a question..."
            class="flex-1 rounded px-3 py-2 focus:outline-none"
          />
          <button id="ask-btn" class="btn-primary px-4 py-2 rounded">
            Ask
          </button>
        </div>
      </div>
  </main>

  <script type="module">
    import { getFirestore, collection, query, orderBy, getDocs } from 'https://www.gstatic.com/firebasejs/9.22.0/firebase-firestore.js';
    import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.22.0/firebase-app.js';
    import { getAuth, onAuthStateChanged, signOut } from 'https://www.gstatic.com/firebasejs/9.22.0/firebase-auth.js';

    const firebaseConfig = {
      apiKey: "AIzaSyAKWstCc7HqMgV8DmH2Sy6QwUP3JvZxu9g",
      authDomain: "appchallenge-c8fe3.firebaseapp.com",
      projectId: "appchallenge-c8fe3",
      storageBucket: "appchallenge-c8fe3.firebasestorage.app",
      messagingSenderId: "943791692455",
      appId: "1:943791692455:web:ae04d06bf09669b6bdd982",
      measurementId: "G-HJ7EHW8V4N"
    };

    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);
    const db = getFirestore(app);
    window.currentUser = null;
    window.chatContext = null;
    window.setChatContextFromId = function (id) {
      const pre = document.querySelector(`#content-${id} .ocr-pre`);
      window.chatContext = pre ? pre.textContent.trim() : null;
      const chatOutput = document.getElementById('chat-output');
      if (chatOutput) {
        chatOutput.innerHTML += `<p class="text-xs text-gray-500"><em>Context set from selected report.</em></p>`;
        chatOutput.scrollTop = chatOutput.scrollHeight;
      }
    };
    onAuthStateChanged(auth, (user) => {
      const authNavItem = document.getElementById('authNavItem');
      if (user) {
        authNavItem.innerHTML = '<button onclick="logout()" class="hover:text-[#6B9080] text-red-600">Logout</button>';
      } else {
        authNavItem.innerHTML = '<a href="login.html" class="hover:text-[#6B9080]">Login</a>';
      }
    });

    window.logout = async () => {
      try {
        await signOut(auth);
        localStorage.clear();
        window.location.href = 'login.html';
      } catch (error) {
        console.error("Error signing out:", error);
      }
    };

    const statusEl = document.getElementById("auth-status");
    const recsEl = document.getElementById("recs-container");
    async function sendReportToBackend(report, userId) {
      try {
        const response = await fetch('http://localhost:9000/save_report/', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            ...report,
            user_id: userId,
            sync_timestamp: new Date().toISOString()
          }),
        });
        
        if (!response.ok) {
          console.warn(`Failed to sync report to backend: ${response.status}`);
        } else {
          console.log('Report successfully synced to backend');
        }
      } catch (error) {
        console.warn('Error syncing report to backend (continuing anyway):', error);
      }
    }

    function renderAnalysisWithCustomToggle(item) {
      const d = item.createdAt && item.createdAt.toDate ? item.createdAt.toDate().toLocaleString() : "";
      const uniqueId = `ocr-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; // Generate unique ID
      
      return `
        <div class="bg-white border border-gray-200 rounded-lg p-4 shadow">
          <div class="flex justify-between mb-2">
            <div class="text-xs text-gray-500">${d}</div>
          </div>
          
          <!-- Collapsible OCR Text Section with Custom Toggle -->
          <div class="mb-4">
            <div class="font-semibold text-green-700 cursor-pointer hover:text-green-800 py-2 flex justify-between items-center" 
                 onclick="toggleOCR('${uniqueId}')">
              <span>Report ${item.reportDate || "N/A"}</span>
              <span class="arrow transition-transform duration-300" id="arrow-${uniqueId}">▶</span>
            </div>
            <div class="ocr-content overflow-hidden transition-all duration-300 max-h-0" id="content-${uniqueId}">
              <div class="mt-2 p-3 bg-gray-50 rounded border">
                <pre class="whitespace-pre-wrap text-sm text-gray-700">${item.ocr_text || ""}</pre>
              </div>
            </div>
          </div>
          
          <!-- Findings Section -->
          ${(Array.isArray(item.Detected_Anomolies) ? item.Detected_Anomolies : []).map((r,i) => `
            <div class="border-t border-gray-200 pt-2 mt-2">
              <div class="font-medium">Finding ${i+1}: ${r.findings || ""}</div>
              <div class="text-sm text-gray-600">Severity: ${r.severity || ""}</div>
              <div class="text-sm text-gray-600">Recommendations: ${(r.recommendations || []).join(", ")}</div>
            </div>
          `).join("")}
        </div>
      `;
    }

    function toggleOCR(id) {
      const content = document.getElementById(`content-${id}`);
      const arrow = document.getElementById(`arrow-${id}`);
      
      if (content.style.maxHeight && content.style.maxHeight !== '0px') {
        content.style.maxHeight = '0px';
        arrow.style.transform = 'rotate(0deg)';
      } else {
        content.style.maxHeight = content.scrollHeight + 'px';
        arrow.style.transform = 'rotate(90deg)';
      }
    }
    
    onAuthStateChanged(auth, async (user) => {
      if (user) {
        statusEl.textContent = `Signed in as ${user.email || user.uid}`;

        async function getPastReports() {
          try {
            const url = api('reports/', { user_id: user.email });
            const response = await fetch(url, {
              method: 'GET',
              headers: {
                'Content-Type': 'application/json',
              },
            });
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            console.log('Report successfully sent to backend:', data);
            recsEl.innerHTML = data.map(doc => renderAnalysisWithCustomToggle(doc)).join("");
          } catch (error) {
            console.error('Error sending report to backend:', error);
            recsEl.innerHTML = '<p class="text-sm text-gray-500">No saved analyses yet.</p>';
          }
        }
       getPastReports();
        
        
       /* try {
          const q = query(
            collection(db, "users", user.uid, "analyses"),
            orderBy("createdAt", "desc")
          );
          const snap = await getDocs(q);
          
          if (snap.empty) {
            recsEl.innerHTML = '<p class="text-sm text-gray-500">No saved analyses yet.</p>';
          } else {
            const analyses = [];

            snap.forEach(doc => {
              const data = { id: doc.id, ...doc.data() };
              analyses.push(data);

              sendReportToBackend(data, user.uid);
            });
            
            recsEl.innerHTML = analyses.map(doc => renderAnalysis(doc)).join("");
          
            const syncStatus = document.createElement('p');
            syncStatus.className = 'text-xs text-blue-500 mt-2';
            syncStatus.textContent = `Syncing ${analyses.length} reports to backend...`;
            recsEl.appendChild(syncStatus);
          
            setTimeout(() => {
              if (syncStatus.parentNode) {
                syncStatus.remove();
              }
            }, 3000);
          }
        } catch (error) {
          console.error('Error fetching analyses:', error);
          recsEl.innerHTML = '<p class="text-sm text-red-500">Error loading analyses.</p>';
        }*/
        
      } else {
        statusEl.textContent = "Not signed in.";
        recsEl.innerHTML = '<p class="text-sm text-gray-500">Please sign in to see your analyses.</p>';
      }
        document.getElementById("ask-btn").onclick = async () => {
          const q = document.getElementById("user-question").value.trim();
          if (!q) return;

          // require a selected report as context
          if (!window.chatContext) {
            alert("Please click 'Chat about this report' on a saved report first to set context.");
            return;
          }

        document.getElementById("ask-btn").onclick = async () => {
          const q = document.getElementById("user-question").value.trim();
          if (!q) return;

          // require a selected report as context
          if (!window.chatContext) {
            alert("Please click 'Chat about this report' on a saved report first to set context.");
            return;
          }
          
           const chat = document.getElementById("chat-output");
           chat.innerHTML += `<p><strong>You:</strong> ${q}</p>`;
           chat.scrollTop = chat.scrollHeight;
           
           chat.innerHTML += `<p><strong>Chatbot:</strong> <em>Thinking...</em></p>`;
           chat.scrollTop = chat.scrollHeight;
           
           try {
             const response = await fetch(api('chat/'), {
               method: "POST",
               headers: {
                 "Content-Type": "application/json",
               },
               body: JSON.stringify({
                 question: q,
                user_id: auth && auth.currentUser ? (auth.currentUser.uid || auth.currentUser.email) : "anonymous",
                context: window.chatContext
               }),
             });
             
             if (!response.ok) {
               throw new Error(`HTTP error! status: ${response.status}`);
             }
             
             const data = await response.json();
             
             //now addign acctual reposnse
             const messages = chat.querySelectorAll('p');
             const lastMessage = messages[messages.length - 1];
             lastMessage.innerHTML = `<strong>Chatbot:</strong> ${data.answer}`;
             
           } catch (error) {
             console.error("Error:", error);
             const messages = chat.querySelectorAll('p');
             const lastMessage = messages[messages.length - 1];
             lastMessage.innerHTML = `<strong>Chatbot:</strong> Sorry, I encountered an error: ${error.message}`;
           }
           
           document.getElementById("user-question").value = "";
           chat.scrollTop = chat.scrollHeight;
         };
      };
    });
  </script>
</body>
</html>