File size: 30,827 Bytes
6cfcdf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WASTE-LESS - Attendance Form B</title>
    <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">
    <style>
        .meal-card { transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
        .meal-card.active { transform: scale(1.03); box-shadow: 0 10px 25px rgba(0,0,0,0.15); }
        .meal-card:hover:not(.active) { transform: translateY(-2px); }
        .rfid-pulse { animation: rfidPulse 2s infinite; }
        @keyframes rfidPulse {
            0%, 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4); }
            50% { box-shadow: 0 0 0 10px rgba(59, 130, 246, 0); }
        }
        .menu-card { animation: slideDown 0.3s ease-out; }
        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-4xl">
        <!-- Header -->
        <header class="bg-blue-600 text-white rounded-lg shadow-lg p-6 mb-8">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <a href="index.html" class="text-blue-100 hover:text-white mr-4 text-xl"><i class="fas fa-home"></i></a>
                    <h1 class="text-3xl font-bold">Attendance Form B</h1>
                    <p class="text-blue-100">For Students Who Have Eaten At The Dining Hall</p>
                </div>
                <div class="flex items-center space-x-2">
                    <i id="meal-period-icon" class="fas fa-utensils text-2xl"></i>
                    <i class="fas fa-calendar-alt text-2xl"></i>
                    <i class="fas fa-users text-2xl"></i>
                </div>
            </div>
        </header>

        <!-- Current Time Display -->
        <div class="bg-white rounded-lg shadow-md p-4 mb-8 text-center">
            <div class="text-xl font-semibold text-gray-700" id="current-time">Loading time...</div>
            <div class="text-blue-600 font-medium" id="current-date">Loading date...</div>
        </div>

        <!-- Meal Periods -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 class="text-xl font-semibold mb-4 text-gray-800">Meal Periods</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                <div class="meal-card px-6 py-5 rounded-xl border-2 cursor-pointer transition-all duration-300" 
                     style="border-color: #fde68a; background: linear-gradient(135deg, #fef9c3, #fef3c7);" 
                     data-meal="breakfast" onclick="showMealMenu('breakfast')">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full mr-4" style="background: rgba(234, 179, 8, 0.15);">
                            <i class="fas fa-sun text-yellow-600 text-2xl"></i>
                        </div>
                        <div>
                            <div class="text-lg font-bold text-yellow-800">Breakfast</div>
                            <div class="text-yellow-700 text-sm font-medium">6:20 AM - 6:50 AM</div>
                        </div>
                    </div>
                </div>
                <div class="meal-card px-6 py-5 rounded-xl border-2 cursor-pointer transition-all duration-300" 
                     style="border-color: #bbf7d0; background: linear-gradient(135deg, #dcfce7, #d1fae5);" 
                     data-meal="lunch" onclick="showMealMenu('lunch')">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full mr-4" style="background: rgba(22, 163, 74, 0.15);">
                            <i class="fas fa-utensils text-green-600 text-2xl"></i>
                        </div>
                        <div>
                            <div class="text-lg font-bold text-green-800">Lunch</div>
                            <div class="text-green-700 text-sm font-medium">1:30 PM - 2:30 PM</div>
                        </div>
                    </div>
                </div>
                <div class="meal-card px-6 py-5 rounded-xl border-2 cursor-pointer transition-all duration-300" 
                     style="border-color: #c7d2fe; background: linear-gradient(135deg, #e0e7ff, #ddd6fe);" 
                     data-meal="dinner" onclick="showMealMenu('dinner')">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full mr-4" style="background: rgba(99, 102, 241, 0.15);">
                            <i class="fas fa-moon text-indigo-600 text-2xl"></i>
                        </div>
                        <div>
                            <div class="text-lg font-bold text-indigo-800">Dinner</div>
                            <div class="text-indigo-700 text-sm font-medium">5:50 PM - 7:00 PM</div>
                        </div>
                    </div>
                </div>
                <div class="meal-card px-6 py-5 rounded-xl border-2 cursor-pointer transition-all duration-300" 
                     style="border-color: #fbcfe8; background: linear-gradient(135deg, #fce7f3, #f5d0fe);" 
                     data-meal="supper" onclick="showMealMenu('supper')">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full mr-4" style="background: rgba(192, 38, 211, 0.15);">
                            <i class="fas fa-bed text-fuchsia-600 text-2xl"></i>
                        </div>
                        <div>
                            <div class="text-lg font-bold text-fuchsia-800">Supper</div>
                            <div class="text-fuchsia-700 text-sm font-medium">10:30 PM - 11:00 PM</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Menu Display -->
            <div id="menu-display-container" class="hidden menu-card">
                <div class="rounded-xl p-6 shadow-inner border" id="menu-display" style="background: linear-gradient(135deg, #f8fafc, #f1f5f9); border-color: #e2e8f0;">
                    <div class="font-bold mb-4 flex items-center text-lg" id="selected-meal-time-display">
                        <i class="fas fa-utensils mr-3 text-gray-600"></i>
                        <span>Select a meal period</span>
                    </div>
                    <div class="space-y-3" id="regular-menu">
                        <div class="text-gray-500 italic" id="default-menu-message">Please click on a meal period above to view its menu</div>
                    </div>
                </div>
            </div>

            <div class="text-sm text-gray-600 mt-4 bg-gray-50 p-3 rounded-lg">
                <p>Current time: <span id="current-meal-time-display" class="font-medium text-gray-800"></span></p>
                <p>Next meal: <span id="next-meal-time-display" class="font-medium text-gray-800"></span></p>
            </div>
        </div>

        <!-- RFID Scan Section -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-8 bg-gradient-to-r from-blue-50 to-indigo-50 border-2 border-blue-200">
            <h2 class="text-xl font-semibold mb-4 text-gray-800 flex items-center">
                <i class="fas fa-wifi mr-2 text-blue-600"></i> RFID Quick Scan
            </h2>
            <div class="flex flex-col md:flex-row gap-4 items-end">
                <div class="flex-1">
                    <label for="rfid-input" class="block text-gray-700 font-medium mb-2">Tap RFID Card to Confirm</label>
                    <input type="text" id="rfid-input" 
                           class="w-full px-4 py-3 border-2 border-blue-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-lg tracking-widest rfid-pulse" 
                           placeholder="Tap card or enter ID..." autocomplete="off">
                </div>
                <button id="rfid-scan-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg transition duration-200">
                    <i class="fas fa-search mr-2"></i> Lookup
                </button>
            </div>
            <div id="rfid-status" class="mt-3 hidden"></div>
            <p class="text-sm text-gray-500 mt-2"><i class="fas fa-info-circle mr-1"></i> Or use the manual form below to select student details</p>
        </div>

        <!-- Eating Confirmation Form -->
        <div id="attendance-form" class="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 class="text-xl font-semibold mb-4 text-gray-800">Dining Confirmation</h2>
            <h3 class="text-lg font-medium mb-4 text-center text-blue-600">Confirm Student Has Eaten</h3>
            <div id="eating-details" class="space-y-4 mt-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label for="class" class="block text-gray-700 font-medium mb-2">Class</label>
                        <select id="class" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" onchange="loadStudents()">
                            <option value="">Select Class</option>
                        </select>
                    </div>
                    <div>
                        <label for="form" class="block text-gray-700 font-medium mb-2">Form</label>
                        <select id="form" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" onchange="loadStudents()">
                            <option value="">Select Form</option>
                            <option value="1">Form 1</option>
                            <option value="2">Form 2</option>
                            <option value="3">Form 3</option>
                            <option value="4">Form 4</option>
                            <option value="5">Form 5</option>
                        </select>
                    </div>
                </div>
                <div id="student-container" class="mt-4 hidden">
                    <label for="student" class="block text-gray-700 font-medium mb-2">Student Name</label>
                    <select id="student" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" disabled>
                        <option value="">Please select Class and Form first</option>
                    </select>
                </div>
            </div>
            <div class="mt-6">
                <button id="submit-btn" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-4 rounded-lg transition duration-200">
                    <i class="fas fa-check-circle mr-2"></i> Confirm Meal Taken
                </button>
            </div>
        </div>

        <!-- Success Message -->
        <div id="success-message" class="hidden fade-in bg-green-50 border border-green-200 text-green-700 p-4 rounded-lg mb-8">
            <div class="flex items-center mb-3">
                <i class="fas fa-check-circle text-green-500 text-2xl mr-3"></i>
                <div>
                    <h3 class="font-bold">Attendance Submitted Successfully!</h3>
                    <p class="text-sm">Your dining hall attendance has been recorded.</p>
                </div>
            </div>
            <button id="fill-again-btn" class="w-full bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded transition duration-200">
                <i class="fas fa-redo mr-2"></i> Fill Again
            </button>
        </div>

        <!-- Footer -->
        <footer class="text-center text-gray-600 text-sm mt-12">
            <p>© 2025 WASTE-LESS Dining Hall Attendance System. All rights reserved.</p>
            <p class="mt-1">Data will be saved to <a href="https://github.com/WaffleExecutors/Waste-LessV5/blob/main/data%20who%20has%20ate%20at%20dm" class="text-blue-600 hover:underline" target="_blank">GitHub repository</a></p>
        </footer>
    </div>

    <script src="config.js"></script>
    <script>
        // ===== RFID SYSTEM =====
        let rfidMappings = {};

        async function loadRfidMappings() {
            try {
                const response = await fetch(`https://api.github.com/repos/${GITHUB_CONFIG.REPOS.ATTENDANCE}/contents/${GITHUB_CONFIG.PATHS.RFID || 'rfid-mappings.json'}`, {
                    headers: { 
                        'Authorization': `token ${GITHUB_CONFIG.TOKEN}`, 
                        'Accept': 'application/vnd.github.v3+json' 
                    }
                });
                if (response.ok) {
                    const data = await response.json();
                    rfidMappings = JSON.parse(atob(data.content));
                } else if (response.status === 404) {
                    rfidMappings = {};
                }
            } catch (e) {
                console.error('Error loading RFID mappings:', e);
                rfidMappings = {};
            }
        }

        async function handleRfidScan() {
            const rfidId = document.getElementById('rfid-input').value.trim();
            if (!rfidId) return;

            if (!rfidMappings || Object.keys(rfidMappings).length === 0) {
                await loadRfidMappings();
            }

            const mapping = rfidMappings[rfidId];
            const statusDiv = document.getElementById('rfid-status');

            if (mapping) {
                document.getElementById('class').value = mapping.class;
                document.getElementById('form').value = mapping.form;
                loadStudents();

                setTimeout(() => {
                    const studentSelect = document.getElementById('student');
                    for (let i = 0; i < studentSelect.options.length; i++) {
                        if (studentSelect.options[i].value === mapping.studentName) {
                            studentSelect.selectedIndex = i;
                            break;
                        }
                    }
                }, 600);

                statusDiv.className = 'mt-3 p-3 bg-green-100 border border-green-300 rounded-lg text-green-700 flex items-center';
                statusDiv.innerHTML = `<i class="fas fa-check-circle mr-2"></i> Card recognized: <strong>${mapping.studentName}</strong> (${mapping.class} Form ${mapping.form}). You can now submit.`;
                statusDiv.classList.remove('hidden');
            } else {
                statusDiv.className = 'mt-3 p-3 bg-red-100 border border-red-300 rounded-lg text-red-700 flex items-center';
                statusDiv.innerHTML = `<i class="fas fa-exclamation-circle mr-2"></i> RFID card not found in system. Please use manual entry below.`;
                statusDiv.classList.remove('hidden');
            }
        }

        document.getElementById('rfid-scan-btn').addEventListener('click', handleRfidScan);
        document.getElementById('rfid-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                handleRfidScan();
            }
        });

        // ===== DYNAMIC STUDENT LIST =====
        let students = {};
        let availableClasses = [];

        async function loadStudentList() {
            try {
                const response = await fetch(`https://api.github.com/repos/${GITHUB_CONFIG.REPOS.STUDENT_LIST || GITHUB_CONFIG.REPOS.CONSUMED}/contents/student-list.json`, {
                    headers: {
                        'Authorization': `token ${GITHUB_CONFIG.TOKEN}`,
                        'Accept': 'application/vnd.github.v3+json'
                    }
                });
                if (response.status === 404) {
                    students = {};
                    availableClasses = [];
                    updateClassDropdown();
                    return;
                }
                if (!response.ok) throw new Error('Failed to load student list');
                const data = await response.json();
                students = JSON.parse(atob(data.content));
                availableClasses = [...new Set(Object.keys(students).map(key => key.split('-')[0]))].sort();
                updateClassDropdown();
            } catch (error) {
                console.error('Error loading student list:', error);
                alert('Could not load student list. Using empty list.');
                students = {};
                availableClasses = [];
                updateClassDropdown();
            }
            loadStudents();
        }

        function updateClassDropdown() {
            const classSelect = document.getElementById('class');
            classSelect.innerHTML = '<option value="">Select Class</option>';
            availableClasses.forEach(cls => {
                const opt = document.createElement('option');
                opt.value = cls;
                opt.textContent = cls;
                classSelect.appendChild(opt);
            });
        }

        function loadStudents() {
            const classVal = document.getElementById('class').value;
            const formVal = document.getElementById('form').value;
            const studentContainer = document.getElementById('student-container');
            const studentSelect = document.getElementById('student');

            studentSelect.innerHTML = '<option value="">Select Student</option>';
            studentSelect.disabled = true;
            studentContainer.classList.add('hidden');

            if (classVal && formVal) {
                const key = `${classVal}-${formVal}`;
                if (students[key] && students[key].length > 0) {
                    students[key].forEach(name => {
                        const option = document.createElement('option');
                        option.value = name;
                        option.textContent = name;
                        studentSelect.appendChild(option);
                    });
                    studentSelect.disabled = false;
                    studentContainer.classList.remove('hidden');
                } else {
                    studentSelect.innerHTML = '<option value="">No students found</option>';
                }
            }
        }

        window.addEventListener('load', loadStudentList);

        // ===== TIME & MEAL FUNCTIONS =====
        function updateDateTime() {
            const now = new Date();
            document.getElementById('current-time').textContent = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
            document.getElementById('current-date').textContent = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });

            const currentMeal = getCurrentMealTime();
            document.getElementById('current-meal-time-display').textContent = currentMeal.charAt(0).toUpperCase() + currentMeal.slice(1);

            const hours = now.getHours();
            let nextMeal = '';
            if (hours < 6) nextMeal = 'Breakfast (6:20 AM)';
            else if (hours < 13) nextMeal = 'Lunch (1:30 PM)';
            else if (hours < 17) nextMeal = 'Dinner (5:50 PM)';
            else if (hours < 22) nextMeal = 'Supper (10:30 PM)';
            else nextMeal = 'Breakfast (6:20 AM)';
            document.getElementById('next-meal-time-display').textContent = nextMeal;
        }
        setInterval(updateDateTime, 1000);
        updateDateTime();

        function getCurrentMealTime() {
            const now = new Date();
            const hours = now.getHours();
            const minutes = now.getMinutes();
            if (hours === 6 && minutes >= 20 || hours === 6 && minutes <= 50) return 'breakfast';
            if (hours === 13 && minutes >= 30 || hours === 14 && minutes <= 30) return 'lunch';
            if (hours === 17 && minutes >= 50 || hours === 18 && minutes <= 30 || hours === 19 && minutes <= 0) return 'dinner';
            if (hours === 22 && minutes >= 30 || hours === 23 && minutes <= 0) return 'supper';
            if (hours < 6) return 'breakfast';
            if (hours < 13) return 'lunch';
            if (hours < 17) return 'dinner';
            if (hours < 22) return 'supper';
            return 'breakfast';
        }

        function isCurrentTimeMealPeriod() {
            const now = new Date();
            const hours = now.getHours();
            const minutes = now.getMinutes();
            return (
                (hours === 6 && minutes >= 20 && minutes <= 50) ||
                (hours === 13 && minutes >= 30 || hours === 14 && minutes <= 30) ||
                (hours === 17 && minutes >= 50 || hours === 18 || (hours === 19 && minutes <= 0)) ||
                (hours === 22 && minutes >= 30 || hours === 23)
            );
        }

        const menus = {
            breakfast: { 
                regular: ["Nasi Lemak with Fried Chicken", "Fried Noodles with Vegetables", "Fruits (Watermelon & Papaya)", "Teh Tarik / Coffee"],
                color: '#ca8a04', bg: 'linear-gradient(135deg, #fef9c3, #fef3c7)', border: '#fde68a', icon: 'fa-sun', name: 'Breakfast',
                time: '6:20 AM - 6:50 AM'
            },
            lunch: { 
                regular: ["Steamed Rice with Beef Rendang", "Stir-fried Vegetables", "Fish Ball Soup", "Fruits (Pineapple & Dragon Fruit)"],
                color: '#16a34a', bg: 'linear-gradient(135deg, #dcfce7, #d1fae5)', border: '#bbf7d0', icon: 'fa-utensils', name: 'Lunch',
                time: '1:30 PM - 2:30 PM'
            },
            dinner: { 
                regular: ["Fried Rice with Chicken Satay", "Mixed Vegetables", "Egg Drop Soup", "Fruits (Apple & Pear)"],
                color: '#4f46e5', bg: 'linear-gradient(135deg, #e0e7ff, #ddd6fe)', border: '#c7d2fe', icon: 'fa-moon', name: 'Dinner',
                time: '5:50 PM - 7:00 PM'
            },
            supper: { 
                regular: ["Sandwiches with Egg Mayo", "Milo and Biscuits", "Fruits (Banana)"],
                color: '#c026d3', bg: 'linear-gradient(135deg, #fce7f3, #f5d0fe)', border: '#fbcfe8', icon: 'fa-bed', name: 'Supper',
                time: '10:30 PM - 11:00 PM'
            }
        };

        let selectedMeal = getCurrentMealTime();

        function showMealMenu(mealTime) {
            selectedMeal = mealTime;
            const container = document.getElementById('menu-display-container');
            container.classList.remove('hidden');

            const mealData = menus[mealTime];

            // Reset all meal cards
            document.querySelectorAll('.meal-card').forEach(btn => {
                btn.classList.remove('active');
                btn.style.borderWidth = '2px';
            });

            // Highlight selected
            const selectedBtn = document.querySelector(`.meal-card[data-meal="${mealTime}"]`);
            if (selectedBtn) {
                selectedBtn.classList.add('active');
                selectedBtn.style.borderColor = mealData.color;
                selectedBtn.style.borderWidth = '3px';
            }

            // Update meal icon
            const mealIcon = document.getElementById('meal-period-icon');
            mealIcon.className = `fas ${mealData.icon} text-2xl`;
            mealIcon.style.color = mealData.color;

            updateMenuDisplay(mealTime);

            document.getElementById('selected-meal-time-display').innerHTML = 
                `<i class="fas ${mealData.icon} mr-3" style="color: ${mealData.color}"></i>` +
                `<span class="font-bold" style="color: ${mealData.color}">${mealData.name} (${mealData.time})</span>`;
            document.getElementById('default-menu-message').classList.add('hidden');
            document.getElementById('attendance-form').classList.remove('hidden');
        }

        function updateMenuDisplay(mealTime) {
            const regularMenu = document.getElementById('regular-menu');
            const mealData = menus[mealTime];
            regularMenu.innerHTML = '';

            mealData.regular.forEach((item, index) => {
                const div = document.createElement('div');
                div.className = 'flex items-center p-3 rounded-lg hover:bg-white/50 transition-colors';
                div.style.background = index % 2 === 0 ? 'rgba(255,255,255,0.4)' : 'transparent';
                div.innerHTML = `
                    <div class="w-8 h-8 rounded-full flex items-center justify-center mr-3 flex-shrink-0" style="background: ${mealData.color}15;">
                        <i class="fas fa-circle text-xs" style="color: ${mealData.color}"></i>
                    </div>
                    <span class="font-medium text-gray-700">${item}</span>
                `;
                regularMenu.appendChild(div);
            });

            const menuDisplay = document.getElementById('menu-display');
            menuDisplay.style.borderColor = mealData.border;
        }

        const initialMeal = getCurrentMealTime();
        if (isCurrentTimeMealPeriod()) {
            showMealMenu(initialMeal);
        } else {
            document.getElementById('menu-display-container').classList.add('hidden');
        }

        // ===== SUBMISSION =====
        document.getElementById('submit-btn').addEventListener('click', async function() {
            this.disabled = true;
            this.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Submitting...';

            const studentClass = document.getElementById('class').value;
            const form = document.getElementById('form').value;
            const student = document.getElementById('student').value;

            if (!student) {
                alert('Please select a student name');
                this.disabled = false;
                this.innerHTML = '<i class="fas fa-check-circle mr-2"></i> Confirm Meal Taken';
                return;
            }
            if (!studentClass || !form) {
                alert('Please select both class and form');
                this.disabled = false;
                this.innerHTML = '<i class="fas fa-check-circle mr-2"></i> Confirm Meal Taken';
                return;
            }

            const data = {
                timestamp: new Date().toISOString(),
                mealTime: getCurrentMealTime(),
                attendance: 'yes',
                class: studentClass,
                form: form,
                studentName: student
            };

            try {
                const success = await sendDataToGitHub(data);
                if (success) {
                    document.getElementById('attendance-form').classList.add('hidden');
                    document.getElementById('success-message').classList.remove('hidden');
                    document.getElementById('success-message').classList.add('fade-in');
                }
            } catch (error) {
                alert('Failed to submit: ' + error.message);
            } finally {
                this.disabled = false;
                this.innerHTML = '<i class="fas fa-check-circle mr-2"></i> Confirm Meal Taken';
            }
        });

        async function sendDataToGitHub(data) {
            try {
                let currentContent = '';
                let sha = '';
                const filePath = 'data%20who%20has%20ate%20at%20dm';
                const repoUrl = `https://api.github.com/repos/${GITHUB_CONFIG.REPOS.CONSUMED}/contents/${filePath}`;

                const getResponse = await fetch(repoUrl, {
                    headers: { 
                        'Authorization': `token ${GITHUB_CONFIG.TOKEN}`, 
                        'Accept': 'application/vnd.github.v3+json' 
                    }
                });

                if (getResponse.ok) {
                    const fileData = await getResponse.json();
                    sha = fileData.sha;
                    currentContent = atob(fileData.content);
                } else if (getResponse.status !== 404) {
                    throw new Error('Failed to fetch existing data');
                }

                const record = JSON.stringify(data);
                const newContent = currentContent + record + '\n';

                const response = await fetch(repoUrl, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `token ${GITHUB_CONFIG.TOKEN}`,
                        'Content-Type': 'application/json',
                        'Accept': 'application/vnd.github.v3+json'
                    },
                    body: JSON.stringify({
                        message: `Meal confirmation - ${new Date().toLocaleString()}`,
                        content: btoa(newContent),
                        sha: sha || undefined,
                        branch: 'main'
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || 'Submission failed');
                }
                return true;
            } catch (error) {
                console.error('Submission error:', error);
                throw new Error('Failed to confirm meal: ' + error.message);
            }
        }

        function resetForm() {
            document.getElementById('class').value = '';
            document.getElementById('form').value = '';
            document.getElementById('student').value = '';
            document.getElementById('student').disabled = true;
            document.getElementById('student-container').classList.add('hidden');
            document.getElementById('success-message').classList.add('hidden');
            document.getElementById('attendance-form').classList.remove('hidden');
            document.getElementById('rfid-input').value = '';
            document.getElementById('rfid-status').classList.add('hidden');
        }

        document.getElementById('fill-again-btn').addEventListener('click', resetForm);

        setInterval(() => {
            const currentMeal = getCurrentMealTime();
            if (currentMeal !== selectedMeal) {
                selectedMeal = currentMeal;
                if (!document.getElementById('menu-display-container').classList.contains('hidden')) {
                    updateMenuDisplay(selectedMeal);
                }
            }
        }, 60000);
    </script>
</body>
</html>