File size: 25,630 Bytes
6b3c4b4
 
 
 
 
f8816c9
6b3c4b4
 
 
 
 
 
f8816c9
 
 
 
 
 
 
 
 
 
6b3c4b4
f8816c9
 
 
6b3c4b4
 
f8816c9
 
 
 
 
 
 
 
 
 
 
 
 
 
6b3c4b4
f8816c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b3c4b4
 
 
f8816c9
 
 
 
 
 
 
 
 
 
6b3c4b4
f8816c9
 
 
 
 
 
 
 
 
 
6b3c4b4
 
f8816c9
df74b9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8816c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b3c4b4
f8816c9
 
 
 
6b3c4b4
f8816c9
 
 
 
6b3c4b4
 
 
f8816c9
 
 
 
 
 
 
6b3c4b4
f8816c9
6b3c4b4
 
f8816c9
 
6b3c4b4
f8816c9
 
 
 
 
 
 
 
 
 
 
 
 
6b3c4b4
 
 
f8816c9
 
 
 
 
 
 
6b3c4b4
f8816c9
 
 
 
 
6b3c4b4
f8816c9
 
6b3c4b4
 
f8816c9
 
 
 
6b3c4b4
f8816c9
 
 
 
 
6b3c4b4
 
f8816c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b3c4b4
f8816c9
 
 
 
 
6b3c4b4
 
 
f8816c9
 
6b3c4b4
 
f8816c9
 
 
 
 
 
 
 
6b3c4b4
f8816c9
6b3c4b4
 
f8816c9
6b3c4b4
f8816c9
 
6b3c4b4
f8816c9
 
 
 
6b3c4b4
f8816c9
 
6b3c4b4
 
 
 
f8816c9
6b3c4b4
 
 
 
f8816c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b3c4b4
 
f8816c9
 
 
6b3c4b4
 
f8816c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df74b9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8816c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b3c4b4
f8816c9
6b3c4b4
 
 
f8816c9
 
 
 
 
 
 
 
 
 
 
 
 
6b3c4b4
 
 
f8816c9
6b3c4b4
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WASTE-LESS - Reports & Analytics</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- Header -->
        <header class="bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-2xl shadow-lg p-6 mb-8">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <a href="index.html" class="text-white/80 hover:text-white mr-4 text-xl transition"><i class="fas fa-home"></i></a>
                    <div>
                        <h1 class="text-3xl font-bold">Reports & Analytics</h1>
                        <p class="text-white/80">Real-time insights from live GitHub data</p>
                    </div>
                </div>
                <button onclick="location.reload()" class="bg-white/20 hover:bg-white/30 text-white px-4 py-2 rounded-lg transition">
                    <i class="fas fa-sync-alt mr-2"></i>Refresh
                </button>
            </div>
        </header>

        <!-- Loading State -->
        <div id="loading" class="text-center py-12">
            <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-4 border-b-4 border-green-500 mb-4"></div>
            <p class="text-gray-600 text-lg">Fetching data from GitHub...</p>
        </div>

        <!-- Error State -->
        <div id="error-msg" class="hidden bg-red-50 border border-red-200 text-red-700 p-6 rounded-xl mb-8">
            <div class="flex items-center">
                <i class="fas fa-exclamation-circle text-2xl mr-3"></i>
                <div>
                    <h3 class="font-bold text-lg">Failed to load data</h3>
                    <p id="error-detail" class="text-sm mt-1"></p>
                </div>
            </div>
        </div>

        <!-- Dashboard Content -->
        <div id="dashboard" class="hidden space-y-8">
            <!-- KPI Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-blue-500">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm font-medium uppercase">Planned Today</p>
                            <p class="text-3xl font-bold text-gray-800 mt-1" id="kpi-planned">0</p>
                        </div>
                        <div class="bg-blue-100 p-3 rounded-lg"><i class="fas fa-utensils text-blue-600"></i></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-green-500">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm font-medium uppercase">Actually Ate</p>
                            <p class="text-3xl font-bold text-gray-800 mt-1" id="kpi-ate">0</p>
                        </div>
                        <div class="bg-green-100 p-3 rounded-lg"><i class="fas fa-check-circle text-green-600"></i></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-red-500">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm font-medium uppercase">No-Shows</p>
                            <p class="text-3xl font-bold text-gray-800 mt-1" id="kpi-noshow">0</p>
                        </div>
                        <div class="bg-red-100 p-3 rounded-lg"><i class="fas fa-user-times text-red-600"></i></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-yellow-500">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm font-medium uppercase">Est. Waste</p>
                            <p class="text-3xl font-bold text-gray-800 mt-1"><span id="kpi-waste">0</span><span class="text-lg text-gray-500">kg</span></p>
                        </div>
                        <div class="bg-yellow-100 p-3 rounded-lg"><i class="fas fa-trash-alt text-yellow-600"></i></div>
                    </div>
                </div>
            </div>

            <!-- Charts Row 1 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-chart-bar mr-2 text-blue-500"></i>Attendance vs Consumption (Last 7 Days)</h3>
                    <canvas id="trendChart" height="220"></canvas>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-chart-pie mr-2 text-green-500"></i>Meal Period Breakdown</h3>
                    <canvas id="mealChart" height="220"></canvas>
                </div>
            </div>

            <!-- Charts Row 2 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-building mr-2 text-purple-500"></i>Attendance by Class</h3>
                    <canvas id="classChart" height="220"></canvas>
                </div>
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-layer-group mr-2 text-indigo-500"></i>Attendance by Form</h3>
                    <canvas id="formChart" height="220"></canvas>
                </div>
            </div>

            <!-- Who Actually Ate -->
            <div class="bg-white rounded-xl shadow-md p-6 mb-8">
                <h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-check-double mr-2 text-green-500"></i>Who Actually Ate (Form B Records)</h3>
                <div class="overflow-x-auto max-h-96 overflow-y-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50 sticky top-0">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Meal</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Student</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Class</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Form</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Time</th>
                            </tr>
                        </thead>
                        <tbody id="ate-body" class="bg-white divide-y divide-gray-200"></tbody>
                    </table>
                    <p id="ate-empty" class="text-center py-8 text-gray-500 hidden">No consumption records found.</p>
                </div>
            </div>

            <!-- No-Show Analysis -->
            <div class="bg-white rounded-xl shadow-md p-6">
                <h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-exclamation-triangle mr-2 text-red-500"></i>No-Show Analysis (Planned but Did Not Eat)</h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Meal</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Student</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Class</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Form</th>
                            </tr>
                        </thead>
                        <tbody id="noshow-body" class="bg-white divide-y divide-gray-200"></tbody>
                    </table>
                    <p id="noshow-empty" class="text-center py-8 text-gray-500 hidden">No no-shows detected — great job!</p>
                </div>
            </div>

            <!-- Raw Data Summary -->
            <div class="bg-white rounded-xl shadow-md p-6">
                <h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-database mr-2 text-gray-500"></i>Data Source Summary</h3>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <p class="font-semibold text-gray-700">Form A Records</p>
                        <p class="text-2xl font-bold text-blue-600 mt-1" id="summary-formA">0</p>
                        <p class="text-gray-500">Students who want to eat</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <p class="font-semibold text-gray-700">Form B Records</p>
                        <p class="text-2xl font-bold text-green-600 mt-1" id="summary-formB">0</p>
                        <p class="text-gray-500">Students who have eaten</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <p class="font-semibold text-gray-700">Data Freshness</p>
                        <p class="text-2xl font-bold text-purple-600 mt-1" id="summary-fresh">--</p>
                        <p class="text-gray-500">Last updated</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <footer class="text-center text-gray-500 text-sm mt-12 pt-8 border-t border-gray-200">
            <p>Data sourced live from GitHub repositories</p>
            <p class="mt-1">Form A: SMSS-Waste-Less/Waste-LessV5 &middot; Form B: WaffleExecutors/Waste-LessV5</p>
        </footer>
    </div>

    <script src="config.js"></script>
    <script>
        // Parse line-delimited JSON from GitHub file content
        function parseLineJson(base64Content) {
            try {
                const text = atob(base64Content);
                if (!text.trim()) return [];
                return text.split('\n')
                    .map(line => line.trim())
                    .filter(line => line.length > 0)
                    .map(line => {
                        try { return JSON.parse(line); }
                        catch (e) { return null; }
                    })
                    .filter(r => r !== null);
            } catch (e) {
                console.error('Parse error:', e);
                return [];
            }
        }

        async function fetchGitHubFile(repo, path) {
            const url = `https://api.github.com/repos/${repo}/contents/${path}`;
            const resp = await fetch(url, {
                headers: {
                    'Authorization': `token ${GITHUB_CONFIG.TOKEN}`,
                    'Accept': 'application/vnd.github.v3+json'
                }
            });
            if (resp.status === 404) return { records: [], sha: null, exists: false };
            if (!resp.ok) throw new Error(`HTTP ${resp.status} for ${path}`);
            const data = await resp.json();
            return { records: parseLineJson(data.content), sha: data.sha, exists: true };
        }

        function getTodayStr() {
            return new Date().toISOString().split('T')[0];
        }

        function getDateStr(ts) {
            try { return new Date(ts).toISOString().split('T')[0]; }
            catch (e) { return ''; }
        }

        function formatDate(ts) {
            try {
                const d = new Date(ts);
                return d.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });
            } catch (e) { return ts; }
        }

        function formatTime(ts) {
            try {
                const d = new Date(ts);
                return d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
            } catch (e) { return ''; }
        }

        // 0.4kg estimated per no-show student
        const WASTE_PER_NOSHOW = 0.4;

        let charts = {};

        function destroyCharts() {
            Object.values(charts).forEach(c => c && c.destroy && c.destroy());
            charts = {};
        }

        function renderTrendChart(dailyStats) {
            const ctx = document.getElementById('trendChart').getContext('2d');
            const labels = dailyStats.map(d => d.label);
            const planned = dailyStats.map(d => d.planned);
            const ate = dailyStats.map(d => d.ate);

            charts.trend = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels,
                    datasets: [
                        { label: 'Planned (Form A)', data: planned, backgroundColor: 'rgba(59,130,246,0.7)', borderRadius: 6 },
                        { label: 'Ate (Form B)', data: ate, backgroundColor: 'rgba(16,185,129,0.7)', borderRadius: 6 }
                    ]
                },
                options: {
                    responsive: true,
                    plugins: { legend: { position: 'top' } },
                    scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
                }
            });
        }

        function renderMealChart(mealStats) {
            const ctx = document.getElementById('mealChart').getContext('2d');
            const meals = ['breakfast','lunch','dinner','supper'];
            const labels = meals.map(m => m.charAt(0).toUpperCase() + m.slice(1));
            const planned = meals.map(m => mealStats[m]?.planned || 0);
            const ate = meals.map(m => mealStats[m]?.ate || 0);

            charts.meal = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels,
                    datasets: [{
                        label: 'Ate',
                        data: ate,
                        backgroundColor: [
                            'rgba(234,179,8,0.7)',
                            'rgba(22,163,74,0.7)',
                            'rgba(99,102,241,0.7)',
                            'rgba(168,85,247,0.7)'
                        ],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    plugins: { legend: { position: 'bottom' } }
                }
            });
        }

        function renderClassChart(classStats) {
            const ctx = document.getElementById('classChart').getContext('2d');
            const classes = Object.keys(classStats).sort();
            const ate = classes.map(c => classStats[c].ate);

            charts.class = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: classes,
                    datasets: [{
                        label: 'Students Ate',
                        data: ate,
                        backgroundColor: 'rgba(139,92,246,0.7)',
                        borderRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    indexAxis: 'y',
                    plugins: { legend: { display: false } },
                    scales: { x: { beginAtZero: true, ticks: { precision: 0 } } }
                }
            });
        }

        function renderFormChart(formStats) {
            const ctx = document.getElementById('formChart').getContext('2d');
            const forms = Object.keys(formStats).sort((a,b) => parseInt(a)-parseInt(b));
            const ate = forms.map(f => formStats[f].ate);
            const planned = forms.map(f => formStats[f].planned);

            charts.form = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: forms.map(f => `Form ${f}`),
                    datasets: [
                        { label: 'Planned', data: planned, backgroundColor: 'rgba(59,130,246,0.6)', borderRadius: 6 },
                        { label: 'Ate', data: ate, backgroundColor: 'rgba(16,185,129,0.6)', borderRadius: 6 }
                    ]
                },
                options: {
                    responsive: true,
                    plugins: { legend: { position: 'top' } },
                    scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
                }
            });
        }

        async function loadData() {
            const loading = document.getElementById('loading');
            const dashboard = document.getElementById('dashboard');
            const errorMsg = document.getElementById('error-msg');
            const errorDetail = document.getElementById('error-detail');

            loading.classList.remove('hidden');
            dashboard.classList.add('hidden');
            errorMsg.classList.add('hidden');
            destroyCharts();

            try {
                const [formA, formB] = await Promise.all([
                    fetchGitHubFile(GITHUB_CONFIG.REPOS.ATTENDANCE, GITHUB_CONFIG.PATHS.FORM_A),
                    fetchGitHubFile(GITHUB_CONFIG.REPOS.CONSUMED, GITHUB_CONFIG.PATHS.FORM_B)
                ]);

                const aRecords = formA.records;
                const bRecords = formB.records;
                const today = getTodayStr();

                // Filter "yes" attendance from Form A (those who planned to eat)
                const aYes = aRecords.filter(r => r.attendance === 'yes');
                // All Form B records are "have eaten"
                const bYes = bRecords;

                // Today's stats
                const aToday = aYes.filter(r => getDateStr(r.timestamp) === today);
                const bToday = bYes.filter(r => getDateStr(r.timestamp) === today);

                // No-shows: planned yes today but not in Form B today (match by name+class+form+meal)
                const bTodayKeys = new Set(bToday.map(r => `${r.studentName}|${r.class}|${r.form}|${r.mealTime}`));
                const noShows = aToday.filter(r => !bTodayKeys.has(`${r.studentName}|${r.class}|${r.form}|${r.mealTime}`));

                // KPIs
                document.getElementById('kpi-planned').textContent = aToday.length;
                document.getElementById('kpi-ate').textContent = bToday.length;
                document.getElementById('kpi-noshow').textContent = noShows.length;
                document.getElementById('kpi-waste').textContent = (noShows.length * WASTE_PER_NOSHOW).toFixed(1);

                // Daily stats for last 7 days
                const last7 = [];
                for (let i = 6; i >= 0; i--) {
                    const d = new Date(); d.setDate(d.getDate() - i);
                    const ds = d.toISOString().split('T')[0];
                    const aDay = aYes.filter(r => getDateStr(r.timestamp) === ds).length;
                    const bDay = bYes.filter(r => getDateStr(r.timestamp) === ds).length;
                    last7.push({
                        label: i === 0 ? 'Today' : d.toLocaleDateString('en-US', { weekday: 'short' }),
                        planned: aDay,
                        ate: bDay
                    });
                }
                renderTrendChart(last7);

                // Meal stats (all time)
                const mealStats = {};
                ['breakfast','lunch','dinner','supper'].forEach(m => mealStats[m] = { planned: 0, ate: 0 });
                aYes.forEach(r => { if (mealStats[r.mealTime]) mealStats[r.mealTime].planned++; });
                bYes.forEach(r => { if (mealStats[r.mealTime]) mealStats[r.mealTime].ate++; });
                renderMealChart(mealStats);

                // Class stats (all time)
                const classStats = {};
                bYes.forEach(r => {
                    if (!classStats[r.class]) classStats[r.class] = { planned: 0, ate: 0 };
                    classStats[r.class].ate++;
                });
                aYes.forEach(r => {
                    if (!classStats[r.class]) classStats[r.class] = { planned: 0, ate: 0 };
                    classStats[r.class].planned++;
                });
                renderClassChart(classStats);

                // Form stats (all time)
                const formStats = {};
                bYes.forEach(r => {
                    if (!formStats[r.form]) formStats[r.form] = { planned: 0, ate: 0 };
                    formStats[r.form].ate++;
                });
                aYes.forEach(r => {
                    if (!formStats[r.form]) formStats[r.form] = { planned: 0, ate: 0 };
                    formStats[r.form].planned++;
                });
                renderFormChart(formStats);

                // Who Actually Ate table
                const ateTbody = document.getElementById('ate-body');
                ateTbody.innerHTML = '';
                const recentAte = bYes.slice().reverse().slice(0, 100);
                if (recentAte.length === 0) {
                    document.getElementById('ate-empty').classList.remove('hidden');
                } else {
                    document.getElementById('ate-empty').classList.add('hidden');
                    recentAte.forEach(r => {
                        const row = document.createElement('tr');
                        row.className = 'hover:bg-gray-50';
                        const d = r.date || getDateStr(r.timestamp);
                        row.innerHTML = `
                            <td class="px-4 py-2 text-sm text-gray-500">${d}</td>
                            <td class="px-4 py-2 text-sm"><span class="capitalize px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-medium">${r.mealTime || '-'}</span></td>
                            <td class="px-4 py-2 text-sm font-medium text-gray-800">${r.studentName || 'Unknown'}</td>
                            <td class="px-4 py-2 text-sm text-gray-600">${r.class || '-'}</td>
                            <td class="px-4 py-2 text-sm text-gray-600">${r.form || '-'}</td>
                            <td class="px-4 py-2 text-sm text-gray-500">${formatTime(r.timestamp)}</td>
                        `;
                        ateTbody.appendChild(row);
                    });
                }

                // No-show table
                const tbody = document.getElementById('noshow-body');
                tbody.innerHTML = '';
                if (noShows.length === 0) {
                    document.getElementById('noshow-empty').classList.remove('hidden');
                } else {
                    document.getElementById('noshow-empty').classList.add('hidden');
                    noShows.slice(0, 50).forEach(r => {
                        const row = document.createElement('tr');
                        row.className = 'hover:bg-gray-50';
                        row.innerHTML = `
                            <td class="px-4 py-2 text-sm text-gray-700">${formatDate(r.timestamp)}</td>
                            <td class="px-4 py-2 text-sm"><span class="capitalize px-2 py-1 rounded bg-gray-100 text-gray-700 text-xs font-medium">${r.mealTime || '-'}</span></td>
                            <td class="px-4 py-2 text-sm font-medium text-gray-800">${r.studentName || 'Unknown'}</td>
                            <td class="px-4 py-2 text-sm text-gray-600">${r.class || '-'}</td>
                            <td class="px-4 py-2 text-sm text-gray-600">${r.form || '-'}</td>
                        `;
                        tbody.appendChild(row);
                    });
                }

                // Summary
                document.getElementById('summary-formA').textContent = aRecords.length;
                document.getElementById('summary-formB').textContent = bRecords.length;
                document.getElementById('summary-fresh').textContent = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });

                loading.classList.add('hidden');
                dashboard.classList.remove('hidden');

            } catch (err) {
                console.error(err);
                loading.classList.add('hidden');
                errorMsg.classList.remove('hidden');
                errorDetail.textContent = err.message;
            }
        }

        document.addEventListener('DOMContentLoaded', loadData);
    </script>
</body>
</html>