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
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WASTE-LESS - Admin Dashboard</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>
    <style>
        .tab-btn.active {
            color: #2563eb;
            border-bottom: 2px solid #2563eb;
        }
        .rfid-card {
            transition: all 0.3s ease;
        }
        .rfid-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- Header with back button -->
        <header class="bg-blue-600 text-white rounded-lg shadow-lg p-6 mb-8">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <a href="index.html" class="text-blue-100 hover:text-white mr-4 text-xl"><i class="fas fa-home"></i></a>
                    <div>
                        <h1 class="text-3xl font-bold">Admin Dashboard</h1>
                        <p class="text-blue-100">Manage food waste and attendance data</p>
                    </div>
                </div>
                <button id="logout-btn" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg">
                    <i class="fas fa-sign-out-alt mr-2"></i> Logout
                </button>
            </div>
        </header>

        <!-- Admin Controls -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <!-- Quick Actions -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-semibold mb-4 text-gray-800">Quick Actions</h2>
                <div class="grid grid-cols-2 gap-4">
                    <a href="attendance.html" class="bg-blue-50 hover:bg-blue-100 text-blue-700 p-4 rounded-lg flex flex-col items-center justify-center transition-colors">
                        <i class="fas fa-utensils text-2xl mb-2"></i>
                        <span>Attendance Form A</span>
                    </a>
                    <a href="students-ate.html" class="bg-green-50 hover:bg-green-100 text-green-700 p-4 rounded-lg flex flex-col items-center justify-center transition-colors">
                        <i class="fas fa-check-circle text-2xl mb-2"></i>
                        <span>Attendance Form B</span>
                    </a>
                    <a href="reports.html" class="bg-purple-50 hover:bg-purple-100 text-purple-700 p-4 rounded-lg flex flex-col items-center justify-center transition-colors">
                        <i class="fas fa-chart-bar text-2xl mb-2"></i>
                        <span>View Reports</span>
                    </a>
                    <a href="student-management.html" class="bg-yellow-50 hover:bg-yellow-100 text-yellow-700 p-4 rounded-lg flex flex-col items-center justify-center transition-colors">
                        <i class="fas fa-users-cog text-2xl mb-2"></i>
                        <span>Student Management</span>
                    </a>
                    <a href="#" onclick="showRFIDSection(); return false;" class="bg-indigo-50 hover:bg-indigo-100 text-indigo-700 p-4 rounded-lg flex flex-col items-center justify-center transition-colors">
                        <i class="fas fa-wifi text-2xl mb-2"></i>
                        <span>RFID Management</span>
                    </a>
                    <a href="#" class="bg-gray-100 hover:bg-gray-200 text-gray-700 p-4 rounded-lg flex flex-col items-center justify-center transition-colors">
                        <i class="fas fa-cog text-2xl mb-2"></i>
                        <span>Settings</span>
                    </a>
                </div>
            </div>

            <!-- System Overview -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-semibold mb-4 text-gray-800">System Overview</h2>
                <div class="space-y-4">
                    <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                        <span>Total Students</span>
                        <span class="font-bold">1200</span>
                    </div>
                    <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                        <span>Today's Attendance</span>
                        <span class="font-bold">78%</span>
                    </div>
                    <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                        <span>Food Waste Today</span>
                        <span class="font-bold">15 kg</span>
                    </div>
                    <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                        <span>Meals Served Today</span>
                        <span class="font-bold">850</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- RFID Management Section -->
        <div id="rfid-section" class="bg-white rounded-lg shadow-md p-6 mb-8 hidden">
            <div class="flex justify-between items-center mb-6">
                <div class="flex items-center">
                    <div class="bg-indigo-100 p-3 rounded-full mr-4">
                        <i class="fas fa-wifi text-indigo-600 text-xl"></i>
                    </div>
                    <div>
                        <h2 class="text-2xl font-bold text-gray-800">RFID Card Management</h2>
                        <p class="text-gray-600">Add, remove, or update student RFID card mappings</p>
                    </div>
                </div>
                <button onclick="hideRFIDSection()" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>

            <!-- Tabs -->
            <div class="flex border-b border-gray-200 mb-6 overflow-x-auto">
                <button class="tab-btn active px-4 py-2 font-medium whitespace-nowrap" onclick="switchTab('view')">
                    <i class="fas fa-list mr-2"></i>View All Cards
                </button>
                <button class="tab-btn px-4 py-2 font-medium text-gray-500 hover:text-gray-700 whitespace-nowrap" onclick="switchTab('add')">
                    <i class="fas fa-plus mr-2"></i>Add Card
                </button>
                <button class="tab-btn px-4 py-2 font-medium text-gray-500 hover:text-gray-700 whitespace-nowrap" onclick="switchTab('update')">
                    <i class="fas fa-edit mr-2"></i>Update Card
                </button>
                <button class="tab-btn px-4 py-2 font-medium text-gray-500 hover:text-gray-700 whitespace-nowrap" onclick="switchTab('remove')">
                    <i class="fas fa-trash mr-2"></i>Remove Card
                </button>
            </div>

            <!-- View Tab -->
            <div id="tab-view" class="tab-content">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-700">Registered RFID Cards</h3>
                    <div class="flex items-center gap-2">
                        <input type="text" id="rfid-search" placeholder="Search cards..." 
                            class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm"
                            oninput="filterRFIDCards()">
                        <button onclick="loadRFIDData()" class="bg-indigo-50 hover:bg-indigo-100 text-indigo-600 px-3 py-2 rounded-lg transition-colors">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                    </div>
                </div>
                <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 tracking-wider">RFID ID</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student Name</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Class</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Form</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="rfid-table-body">
                            <tr>
                                <td colspan="5" class="px-4 py-8 text-center text-gray-500">
                                    <i class="fas fa-spinner fa-spin mr-2"></i> Loading RFID data...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    Total cards: <span id="rfid-count" class="font-bold">0</span>
                </div>
            </div>

            <!-- Add Tab -->
            <div id="tab-add" class="tab-content hidden">
                <div class="max-w-lg">
                    <h3 class="text-lg font-semibold text-gray-700 mb-4">Register New RFID Card</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">RFID Card ID</label>
                            <input type="text" id="add-rfid-id" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 font-mono" placeholder="e.g. 1234567890">
                            <p class="text-xs text-gray-500 mt-1">Enter the unique ID printed on the RFID card</p>
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-gray-700 font-medium mb-2">Class</label>
                                <select id="add-rfid-class" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" onchange="updateRFIDStudentDropdown()">
                                    <option value="">Select Class</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-gray-700 font-medium mb-2">Form</label>
                                <select id="add-rfid-form" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" onchange="updateRFIDStudentDropdown()">
                                    <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>
                            <label class="block text-gray-700 font-medium mb-2">Student Name</label>
                            <select id="add-rfid-student" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" disabled>
                                <option value="">Select Class and Form first</option>
                            </select>
                        </div>
                        <button onclick="addRFIDCard()" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-lg transition duration-200">
                            <i class="fas fa-plus mr-2"></i> Register Card
                        </button>
                    </div>
                    <div id="add-rfid-success" class="hidden mt-4 bg-green-50 border border-green-200 text-green-700 p-4 rounded-lg">
                        <div class="flex items-center">
                            <i class="fas fa-check-circle text-green-500 text-xl mr-3"></i>
                            <div>
                                <h4 class="font-bold">Card Registered!</h4>
                                <p class="text-sm">RFID mapping saved to GitHub.</p>
                            </div>
                        </div>
                    </div>
                    <div id="add-rfid-error" class="hidden mt-4 bg-red-50 border border-red-200 text-red-700 p-4 rounded-lg">
                        <div class="flex items-center">
                            <i class="fas fa-exclamation-circle text-red-500 text-xl mr-3"></i>
                            <span id="add-rfid-error-msg">Error message</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Update Tab -->
            <div id="tab-update" class="tab-content hidden">
                <div class="max-w-lg">
                    <h3 class="text-lg font-semibold text-gray-700 mb-4">Update RFID Card</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Select Existing Card</label>
                            <select id="update-rfid-select" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" onchange="loadRFIDUpdateForm()">
                                <option value="">Select RFID Card</option>
                            </select>
                        </div>
                        <div id="update-rfid-form" class="hidden space-y-4">
                            <div>
                                <label class="block text-gray-700 font-medium mb-2">New RFID ID (optional)</label>
                                <input type="text" id="update-rfid-new-id" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 font-mono" placeholder="Leave empty to keep current ID">
                            </div>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-gray-700 font-medium mb-2">Class</label>
                                    <select id="update-rfid-class" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" onchange="updateRFIDStudentDropdownForUpdate()">
                                        <option value="">Select Class</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-gray-700 font-medium mb-2">Form</label>
                                    <select id="update-rfid-form" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" onchange="updateRFIDStudentDropdownForUpdate()">
                                        <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>
                                <label class="block text-gray-700 font-medium mb-2">Student Name</label>
                                <select id="update-rfid-student" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" disabled>
                                    <option value="">Select Class and Form first</option>
                                </select>
                            </div>
                            <button onclick="updateRFIDCard()" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-4 rounded-lg transition duration-200">
                                <i class="fas fa-save mr-2"></i> Update Card
                            </button>
                        </div>
                    </div>
                    <div id="update-rfid-success" class="hidden mt-4 bg-green-50 border border-green-200 text-green-700 p-4 rounded-lg">
                        <div class="flex items-center">
                            <i class="fas fa-check-circle text-green-500 text-xl mr-3"></i>
                            <div>
                                <h4 class="font-bold">Card Updated!</h4>
                                <p class="text-sm">RFID mapping updated in GitHub.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Remove Tab -->
            <div id="tab-remove" class="tab-content hidden">
                <div class="max-w-lg">
                    <h3 class="text-lg font-semibold text-gray-700 mb-4">Remove RFID Card</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Select Card to Remove</label>
                            <select id="remove-rfid-select" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500">
                                <option value="">Select RFID Card</option>
                            </select>
                        </div>
                        <div class="bg-red-50 border border-red-200 text-red-700 p-4 rounded-lg">
                            <div class="flex items-center">
                                <i class="fas fa-exclamation-triangle text-red-500 text-xl mr-3"></i>
                                <div>
                                    <h4 class="font-bold">Warning</h4>
                                    <p class="text-sm">This will permanently remove the RFID mapping. The student will need to use manual form until a new card is registered.</p>
                                </div>
                            </div>
                        </div>
                        <button onclick="removeRFIDCard()" class="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-3 px-4 rounded-lg transition duration-200">
                            <i class="fas fa-trash-alt mr-2"></i> Remove Card
                        </button>
                    </div>
                    <div id="remove-rfid-success" class="hidden mt-4 bg-green-50 border border-green-200 text-green-700 p-4 rounded-lg">
                        <div class="flex items-center">
                            <i class="fas fa-check-circle text-green-500 text-xl mr-3"></i>
                            <div>
                                <h4 class="font-bold">Card Removed!</h4>
                                <p class="text-sm">RFID mapping deleted from GitHub.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Attendance Data Tables -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <!-- Form A Data -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-semibold text-gray-800">Students Who Want To Eat (Form A)</h2>
                    <button id="refresh-formA" class="text-blue-600 hover:text-blue-800">
                        <i class="fas fa-sync-alt mr-1"></i> Refresh
                    </button>
                </div>
                <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-2 text-left text-xs font-medium text-gray-500 uppercase">Student</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Class</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Form</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Attendance</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Meal</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Time</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="formAData">
                            <tr>
                                <td colspan="6" class="px-4 py-4 text-center text-gray-500">Loading data...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <a href="https://github.com/SMSS-Waste-Less/Waste-LessV5/blob/main/Data%20Students%20who%20want%20to%20eat" target="_blank" class="text-blue-600 hover:underline">
                        View full data on GitHub
                    </a>
                </div>
            </div>

            <!-- Form B Data -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-semibold text-gray-800">Students Who Have Eaten (Form B)</h2>
                    <button id="refresh-formB" class="text-blue-600 hover:text-blue-800">
                        <i class="fas fa-sync-alt mr-1"></i> Refresh
                    </button>
                </div>
                <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-2 text-left text-xs font-medium text-gray-500 uppercase">Student</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Class</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Form</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Meal</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Time</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="formBData">
                            <tr>
                                <td colspan="5" class="px-4 py-4 text-center text-gray-500">Loading data...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <a href="https://github.com/WaffleExecutors/Waste-LessV5/blob/main/data%20who%20has%20ate%20at%20dm" target="_blank" class="text-blue-600 hover:underline">
                        View full data on GitHub
                    </a>
                </div>
            </div>
        </div>

        <!-- Charts -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-semibold mb-4 text-gray-800">Attendance Trend</h2>
                <canvas id="attendanceChart" height="250"></canvas>
            </div>
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-xl font-semibold mb-4 text-gray-800">Food Waste Breakdown</h2>
                <canvas id="wasteChart" height="250"></canvas>
            </div>
        </div>
    </div>

    <script src="config.js"></script>
    <script>
        // Your GitHub token (filled in)
        const GITHUB_TOKEN = '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';

        // Login check
        if (localStorage.getItem('isAdminLoggedIn') !== 'true') {
            alert('Please login first');
            window.location.href = 'admin-login.html';
        }

        // ========== RFID MANAGEMENT ==========
        let rfidMapping = {};
        let students = {};
        let availableClasses = [];
        let rfidSha = '';

        function showRFIDSection() {
            document.getElementById('rfid-section').classList.remove('hidden');
            document.getElementById('rfid-section').scrollIntoView({ behavior: 'smooth' });
            loadRFIDData();
            loadStudentListForRFID();
        }

        function hideRFIDSection() {
            document.getElementById('rfid-section').classList.add('hidden');
        }

        function switchTab(tab) {
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active', 'text-blue-600', 'border-b-2', 'border-blue-600'));
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.add('text-gray-500'));
            event.target.classList.add('active', 'text-blue-600', 'border-b-2', 'border-blue-600');
            event.target.classList.remove('text-gray-500');

            document.querySelectorAll('.tab-content').forEach(content => content.classList.add('hidden'));
            document.getElementById(`tab-${tab}`).classList.remove('hidden');

            if (tab === 'view') loadRFIDData();
            if (tab === 'add') loadStudentListForRFID();
            if (tab === 'update') loadRFIDUpdateSelect();
            if (tab === 'remove') loadRFIDRemoveSelect();
        }

        async function loadRFIDData() {
            try {
                const response = await fetch(`https://api.github.com/repos/${GITHUB_CONFIG.REPOS.STUDENT_LIST}/contents/${GITHUB_CONFIG.PATHS.RFID_MAP}`, {
                    headers: {
                        'Authorization': `token ${GITHUB_CONFIG.TOKEN}`,
                        'Accept': 'application/vnd.github.v3+json'
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    rfidSha = data.sha;
                    rfidMapping = JSON.parse(atob(data.content));
                } else if (response.status === 404) {
                    rfidMapping = {};
                    rfidSha = '';
                } else {
                    throw new Error('Failed to load RFID data');
                }

                renderRFIDTable();
            } catch (error) {
                console.error('Error loading RFID data:', error);
                document.getElementById('rfid-table-body').innerHTML = `
                    <tr><td colspan="5" class="px-4 py-8 text-center text-red-500">
                        <i class="fas fa-exclamation-circle mr-2"></i> Failed to load RFID data
                    </td></tr>`;
            }
        }

        function renderRFIDTable() {
            const tbody = document.getElementById('rfid-table-body');
            const searchTerm = document.getElementById('rfid-search').value.toLowerCase();
            const entries = Object.entries(rfidMapping);

            const filtered = entries.filter(([id, data]) => {
                return !searchTerm || 
                    id.toLowerCase().includes(searchTerm) ||
                    data.studentName.toLowerCase().includes(searchTerm) ||
                    data.class.toLowerCase().includes(searchTerm);
            });

            document.getElementById('rfid-count').textContent = filtered.length;

            if (filtered.length === 0) {
                tbody.innerHTML = `<tr><td colspan="5" class="px-4 py-8 text-center text-gray-500">No RFID cards registered</td></tr>`;
                return;
            }

            tbody.innerHTML = filtered.map(([id, data]) => `
                <tr class="hover:bg-gray-50 transition-colors">
                    <td class="px-4 py-3 text-sm font-mono text-indigo-600">${id}</td>
                    <td class="px-4 py-3 text-sm font-medium">${data.studentName}</td>
                    <td class="px-4 py-3 text-sm">${data.class}</td>
                    <td class="px-4 py-3 text-sm">${data.form}</td>
                    <td class="px-4 py-3 text-sm">
                        <button onclick="quickEditRFID('${id}')" class="text-indigo-600 hover:text-indigo-800 mr-3" title="Edit">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button onclick="quickDeleteRFID('${id}')" class="text-red-600 hover:text-red-800" title="Delete">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        function filterRFIDCards() {
            renderRFIDTable();
        }

        async function loadStudentListForRFID() {
            try {
                const response = await fetch(`https://api.github.com/repos/${GITHUB_CONFIG.REPOS.STUDENT_LIST}/contents/student-list.json`, {
                    headers: {
                        'Authorization': `token ${GITHUB_CONFIG.TOKEN}`,
                        'Accept': 'application/vnd.github.v3+json'
                    }
                });
                if (response.ok) {
                    const data = await response.json();
                    students = JSON.parse(atob(data.content));
                    availableClasses = [...new Set(Object.keys(students).map(key => key.split('-')[0]))].sort();

                    // Update all class dropdowns
                    ['add-rfid-class', 'update-rfid-class'].forEach(id => {
                        const select = document.getElementById(id);
                        select.innerHTML = '<option value="">Select Class</option>';
                        availableClasses.forEach(cls => {
                            const opt = document.createElement('option');
                            opt.value = cls;
                            opt.textContent = cls;
                            select.appendChild(opt);
                        });
                    });
                }
            } catch (error) {
                console.error('Error loading student list:', error);
            }
        }

        function updateRFIDStudentDropdown() {
            const classVal = document.getElementById('add-rfid-class').value;
            const formVal = document.getElementById('add-rfid-form').value;
            const studentSelect = document.getElementById('add-rfid-student');

            studentSelect.innerHTML = '<option value="">Select Student</option>';
            studentSelect.disabled = true;

            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;
                } else {
                    studentSelect.innerHTML = '<option value="">No students found</option>';
                }
            }
        }

        function updateRFIDStudentDropdownForUpdate() {
            const classVal = document.getElementById('update-rfid-class').value;
            const formVal = document.getElementById('update-rfid-form').value;
            const studentSelect = document.getElementById('update-rfid-student');

            studentSelect.innerHTML = '<option value="">Select Student</option>';
            studentSelect.disabled = true;

            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;
                } else {
                    studentSelect.innerHTML = '<option value="">No students found</option>';
                }
            }
        }

        async function saveRFIDToGitHub() {
            try {
                const putRes = await fetch(`https://api.github.com/repos/${GITHUB_CONFIG.REPOS.STUDENT_LIST}/contents/${GITHUB_CONFIG.PATHS.RFID_MAP}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `token ${GITHUB_CONFIG.TOKEN}`,
                        'Content-Type': 'application/json',
                        'Accept': 'application/vnd.github.v3+json'
                    },
                    body: JSON.stringify({
                        message: `Update RFID mapping - ${new Date().toISOString()}`,
                        content: btoa(JSON.stringify(rfidMapping, null, 2)),
                        sha: rfidSha || undefined,
                        branch: 'main'
                    })
                });

                if (!putRes.ok) {
                    const err = await putRes.json();
                    throw new Error(err.message || 'Save failed');
                }

                const resData = await putRes.json();
                rfidSha = resData.content.sha;
                return true;
            } catch (err) {
                alert('Failed to save to GitHub: ' + err.message);
                return false;
            }
        }

        async function addRFIDCard() {
            const rfidId = document.getElementById('add-rfid-id').value.trim();
            const classVal = document.getElementById('add-rfid-class').value;
            const formVal = document.getElementById('add-rfid-form').value;
            const studentName = document.getElementById('add-rfid-student').value;

            if (!rfidId) return alert('Enter RFID Card ID');
            if (!classVal || !formVal || !studentName) return alert('Select class, form, and student');
            if (rfidMapping[rfidId]) return alert('This RFID ID is already registered');

            rfidMapping[rfidId] = {
                studentName,
                class: classVal,
                form: formVal
            };

            const saved = await saveRFIDToGitHub();
            if (saved) {
                document.getElementById('add-rfid-success').classList.remove('hidden');
                document.getElementById('add-rfid-id').value = '';
                document.getElementById('add-rfid-class').value = '';
                document.getElementById('add-rfid-form').value = '';
                document.getElementById('add-rfid-student').innerHTML = '<option value="">Select Class and Form first</option>';
                document.getElementById('add-rfid-student').disabled = true;
                setTimeout(() => document.getElementById('add-rfid-success').classList.add('hidden'), 3000);
                loadRFIDData();
            }
        }

        function loadRFIDUpdateSelect() {
            const select = document.getElementById('update-rfid-select');
            select.innerHTML = '<option value="">Select RFID Card</option>';
            Object.entries(rfidMapping).forEach(([id, data]) => {
                const opt = document.createElement('option');
                opt.value = id;
                opt.textContent = `${id} - ${data.studentName}`;
                select.appendChild(opt);
            });
        }

        function loadRFIDUpdateForm() {
            const id = document.getElementById('update-rfid-select').value;
            const form = document.getElementById('update-rfid-form');

            if (!id) {
                form.classList.add('hidden');
                return;
            }

            const data = rfidMapping[id];
            document.getElementById('update-rfid-new-id').value = id;

            // Set class dropdown
            const classSelect = document.getElementById('update-rfid-class');
            if (classSelect.querySelector(`option[value="${data.class}"]`)) {
                classSelect.value = data.class;
            }

            document.getElementById('update-rfid-form').value = data.form;
            updateRFIDStudentDropdownForUpdate();

            setTimeout(() => {
                const studentSelect = document.getElementById('update-rfid-student');
                if (studentSelect.querySelector(`option[value="${data.studentName}"]`)) {
                    studentSelect.value = data.studentName;
                }
            }, 100);

            form.classList.remove('hidden');
        }

        async function updateRFIDCard() {
            const oldId = document.getElementById('update-rfid-select').value;
            const newId = document.getElementById('update-rfid-new-id').value.trim();
            const classVal = document.getElementById('update-rfid-class').value;
            const formVal = document.getElementById('update-rfid-form').value;
            const studentName = document.getElementById('update-rfid-student').value;

            if (!oldId) return alert('Select a card to update');
            if (!newId) return alert('RFID ID cannot be empty');
            if (!classVal || !formVal || !studentName) return alert('Select class, form, and student');

            // If ID changed, delete old and create new
            if (oldId !== newId) {
                if (rfidMapping[newId] && newId !== oldId) return alert('New RFID ID already exists');
                delete rfidMapping[oldId];
            }

            rfidMapping[newId] = {
                studentName,
                class: classVal,
                form: formVal
            };

            const saved = await saveRFIDToGitHub();
            if (saved) {
                document.getElementById('update-rfid-success').classList.remove('hidden');
                document.getElementById('update-rfid-select').value = '';
                document.getElementById('update-rfid-form').classList.add('hidden');
                setTimeout(() => document.getElementById('update-rfid-success').classList.add('hidden'), 3000);
                loadRFIDData();
            }
        }

        function loadRFIDRemoveSelect() {
            const select = document.getElementById('remove-rfid-select');
            select.innerHTML = '<option value="">Select RFID Card</option>';
            Object.entries(rfidMapping).forEach(([id, data]) => {
                const opt = document.createElement('option');
                opt.value = id;
                opt.textContent = `${id} - ${data.studentName}`;
                select.appendChild(opt);
            });
        }

        async function removeRFIDCard() {
            const id = document.getElementById('remove-rfid-select').value;
            if (!id) return alert('Select a card to remove');
            if (!confirm(`Are you sure you want to remove RFID card ${id} for ${rfidMapping[id].studentName}?`)) return;

            delete rfidMapping[id];

            const saved = await saveRFIDToGitHub();
            if (saved) {
                document.getElementById('remove-rfid-success').classList.remove('hidden');
                document.getElementById('remove-rfid-select').value = '';
                setTimeout(() => document.getElementById('remove-rfid-success').classList.add('hidden'), 3000);
                loadRFIDData();
            }
        }

        function quickEditRFID(id) {
            switchTab('update');
            document.getElementById('update-rfid-select').value = id;
            loadRFIDUpdateForm();
        }

        async function quickDeleteRFID(id) {
            if (!confirm(`Delete RFID card ${id} for ${rfidMapping[id]?.studentName}?`)) return;
            delete rfidMapping[id];
            const saved = await saveRFIDToGitHub();
            if (saved) {
                loadRFIDData();
            }
        }

        // ========== EXISTING ATTENDANCE DATA FUNCTIONS ==========
        async function fetchAttendanceData() {
            try {
                document.getElementById('formAData').innerHTML = '<tr><td colspan="6" class="text-center py-4"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>';
                document.getElementById('formBData').innerHTML = '<tr><td colspan="5" class="text-center py-4"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>';

                // Form A
                const aResp = await fetch('https://api.github.com/repos/SMSS-Waste-Less/Waste-LessV5/contents/Data%20Students%20who%20want%20to%20eat', {
                    headers: { 'Authorization': `token ${GITHUB_TOKEN}`, 'Accept': 'application/vnd.github.v3+json' }
                });
                let aRows = '<tr><td colspan="6" class="text-center py-4 text-gray-500">No data</td></tr>';
                if (aResp.ok) {
                    const aFile = await aResp.json();
                    const aContent = atob(aFile.content);
                    aRows = aContent.split('\n').filter(l => l.trim()).reverse().map(l => {
                        try {
                            const r = JSON.parse(l);
                            const t = new Date(r.timestamp).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
                            const att = r.attendance === 'yes' ? 'Will Eat' : 'Will Not Eat';
                            const source = r.source === 'rfid-scan' ? '<span class="ml-1 text-xs bg-indigo-100 text-indigo-600 px-1 rounded">RFID</span>' : '';
                            return `<tr class="hover:bg-gray-50">
                                <td class="px-4 py-2 text-sm">${r.studentName}${source}</td>
                                <td class="px-4 py-2 text-sm">${r.class}</td>
                                <td class="px-4 py-2 text-sm">${r.form}</td>
                                <td class="px-4 py-2 text-sm">${att}</td>
                                <td class="px-4 py-2 text-sm">${r.mealTime || '-'}</td>
                                <td class="px-4 py-2 text-sm text-gray-500">${t}</td>
                            </tr>`;
                        } catch { return ''; }
                    }).join('');
                }
                document.getElementById('formAData').innerHTML = aRows;

                // Form B
                const bResp = await fetch('https://api.github.com/repos/WaffleExecutors/Waste-LessV5/contents/data%20who%20has%20ate%20at%20dm', {
                    headers: { 'Authorization': `token ${GITHUB_TOKEN}`, 'Accept': 'application/vnd.github.v3+json' }
                });
                let bRows = '<tr><td colspan="5" class="text-center py-4 text-gray-500">No data</td></tr>';
                if (bResp.ok) {
                    const bFile = await bResp.json();
                    const bContent = atob(bFile.content);
                    bRows = bContent.split('\n').filter(l => l.trim()).reverse().map(l => {
                        try {
                            const r = JSON.parse(l);
                            const t = new Date(r.timestamp).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
                            const source = r.source === 'rfid-scan' ? '<span class="ml-1 text-xs bg-indigo-100 text-indigo-600 px-1 rounded">RFID</span>' : '';
                            return `<tr class="hover:bg-gray-50">
                                <td class="px-4 py-2 text-sm">${r.studentName}${source}</td>
                                <td class="px-4 py-2 text-sm">${r.class}</td>
                                <td class="px-4 py-2 text-sm">${r.form}</td>
                                <td class="px-4 py-2 text-sm">${r.mealTime || '-'}</td>
                                <td class="px-4 py-2 text-sm text-gray-500">${t}</td>
                            </tr>`;
                        } catch { return ''; }
                    }).join('');
                }
                document.getElementById('formBData').innerHTML = bRows;

            } catch (err) {
                console.error(err);
                alert('Failed to load data. Check token or connection.');
            }
        }

        fetchAttendanceData();
        setInterval(fetchAttendanceData, 30000);

        document.getElementById('refresh-formA').onclick = fetchAttendanceData;
        document.getElementById('refresh-formB').onclick = fetchAttendanceData;

        // Initialize charts with empty data
        const attendanceChart = new Chart(document.getElementById('attendanceChart'), { 
            type: 'line', 
            data: { 
                labels: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'], 
                datasets: [{ 
                    label: 'Attendance Rate (%)', 
                    data: [],
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: true
                }] 
            },
            options: {
                responsive: true,
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `${context.dataset.label}: ${context.raw}%`;
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        min: 0,
                        max: 100,
                        ticks: {
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    }
                }
            } 
        });

        const wasteChart = new Chart(document.getElementById('wasteChart'), { 
            type: 'bar', 
            data: { 
                labels: ['Breakfast','Lunch','Dinner','Supper'], 
                datasets: [{ 
                    label: 'Food Waste (kg)', 
                    data: [],
                    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)'
                    ],
                    borderColor: [
                        'rgba(234, 179, 8, 1)',
                        'rgba(22, 163, 74, 1)',
                        'rgba(99, 102, 241, 1)',
                        'rgba(168, 85, 247, 1)'
                    ],
                    borderWidth: 1
                }] 
            },
            options: {
                responsive: true,
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return `${context.dataset.label}: ${context.raw}kg`;
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Kilograms'
                        }
                    }
                }
            } 
        });

        // Logout
        document.getElementById('logout-btn').onclick = () => {
            localStorage.clear();
            window.location.href = 'admin-login.html';
        };
    </script>
</body>
</html>