-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrade2_1.html
More file actions
1498 lines (1299 loc) · 61.4 KB
/
grade2_1.html
File metadata and controls
1498 lines (1299 loc) · 61.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html><!DOCTYPE html>
<html><html lang="ar" dir="rtl">
<head><head>
<meta charset="UTF-8"> <meta charset="UTF-8" />
<meta http-equiv="refresh" content="0; url=project%2012/pages/grade2_1.html"> <meta name="viewport" content="width=device-width, initial-scale=1" />
<script> <title>الصف الثاني الثانوي علمي - منصتي التعليمية</title>
window.location.href = "project%2012/pages/grade2_1.html"; <script src="https://cdn.tailwindcss.com"></script>
</script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
<title>Redirecting...</title> <style>
</head> body {
<body> background: linear-gradient(to bottom right, #dbeafe, #e0e7ff, #e0f2fe);
<p>Redirecting to Grade 2 Science...</p> transition: background 0.5s ease;
</body> }
</html> html.dark body {
background: linear-gradient(to bottom right, #0f172a, #1e1b4b, #1e3a8a);
}
.card { transition: all 0.3s ease; }
.card:hover {
transform: translateY(-3px);
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}
.nav-tab.active {
background: linear-gradient(135deg, #3b82f6 0%, #6366f1 100%);
color: #fff;
}
.schedule-time {
background: linear-gradient(135deg, #3b82f6 0%, #6366f1 100%);
}
.teacher-mode-indicator {
position: absolute;
top: -8px;
right: -8px;
background: linear-gradient(135deg, #8b5cf6, #a855f7);
color: white;
padding: 4px 8px;
border-radius: 12px;
font-size: 10px;
font-weight: 600;
box-shadow: 0 2px 8px rgba(139, 92, 246, 0.4);
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.8; }
}
.teacher-tools {
border-top: 2px dashed #8b5cf6;
background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
margin-top: 1rem;
padding-top: 1rem;
}
html.dark .teacher-tools {
background: linear-gradient(135deg, #374151, #4b5563);
}
html.dark .text-gray-800 { color: #e2e8f0; }
html.dark .text-gray-600 { color: #94a3b8; }
html.dark .bg-white { background-color: #1e293b; }
html.dark .bg-gray-50 { background-color: #334155; }
html.dark .text-gray-700 { color: #cbd5e1; }
#themeToggle {
position: fixed; top: 20px; left: 20px;
background: rgba(255, 255, 255, 0.8);
border: none; border-radius: 9999px;
width: 50px; height: 50px; cursor: pointer;
font-size: 1.5rem; display: flex; align-items: center; justify-content: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
transition: background 0.3s ease; z-index: 1000;
}
#themeToggle:hover { background: rgba(255, 255, 255, 1); }
html.dark #themeToggle { background: rgba(30, 41, 59, 0.8); color: #e2e8f0; }
html.dark #themeToggle:hover { background: rgba(30, 41, 59, 1); }
</style>
</head>
<body class="min-h-screen">
<!-- زر الوضع الليلي -->
<button id="themeToggle" aria-label="تبديل الوضع بين داكن وفاتح">🌙</button>
<!-- بانر ترحيب -->
<section id="welcomeBox" class="container mx-auto mt-6 hidden">
<div class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white p-4 rounded-lg shadow-lg flex justify-between items-center">
<span id="welcomeText" class="font-semibold text-lg"></span>
<button id="logoutBtn" class="bg-white text-blue-600 px-4 py-2 rounded-lg shadow hover:bg-gray-100">تسجيل الخروج</button>
</div>
</section>
<!-- Header -->
<header class="bg-white shadow-lg">
<div class="container mx-auto px-4 py-4 flex flex-col md:flex-row justify-between items-center gap-4">
<div class="flex items-center gap-4">
<div class="w-12 h-12 bg-gradient-to-r from-blue-500 to-indigo-600 rounded-full flex items-center justify-center">
<i class="fas fa-graduation-cap text-white text-xl"></i>
</div>
<div>
<h1 class="text-2xl font-bold text-gray-800">الصف الثاني الثانوي علمي</h1>
<p class="text-gray-600">منصتي التعليمية</p>
</div>
</div>
<div class="flex items-center gap-6">
<!-- منيو الطالب -->
<div class="relative inline-block text-left">
<button id="userMenuBtn" class="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-full shadow hover:bg-blue-700">
<span id="studentName">👤 الطالب</span>
<i class="fas fa-caret-down"></i>
</button>
<div id="userMenu" class="hidden absolute right-0 mt-2 w-48 bg-white border rounded-lg shadow-lg z-50">
<a href="profile.html" class="block px-4 py-2 text-gray-700 hover:bg-gray-100">الملف الشخصي</a>
<a href="grades.html" class="block px-4 py-2 text-gray-700 hover:bg-gray-100">الدرجات</a>
<a href="calendar.html" class="block px-4 py-2 text-gray-700 hover:bg-gray-100">التقويم</a>
<a href="settings.html" class="block px-4 py-2 text-gray-700 hover:bg-gray-100">الإعدادات</a>
<hr>
<button id="logoutBtn2" class="w-full text-right px-4 py-2 text-red-600 hover:bg-red-100">تسجيل الخروج</button>
</div>
</div>
<!-- بيانات الأستاذ + زر التبديل -->
<div class="flex items-center gap-3">
<!-- زر إضافة حصة للمعلمين فقط -->
<div id="addLessonHeaderBtn" class="hidden">
<a href="add-lesson.html" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 transition-colors">
<i class="fas fa-plus"></i>
<span>إضافة حصة</span>
</a>
</div>
<!-- زر إضافة جدول دراسي للمعلمين فقط -->
<div id="addScheduleHeaderBtn" class="hidden">
<a href="add-schedule-simple.html" class="bg-purple-500 hover:bg-purple-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 transition-colors">
<i class="fas fa-calendar-plus"></i>
<span>إضافة جدول</span>
</a>
</div>
<!-- زر إضافة واجب للمعلمين فقط -->
<div id="addHomeworkHeaderBtn" class="hidden">
<a href="add-homework.html" class="bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 transition-colors">
<i class="fas fa-tasks"></i>
<span>إضافة واجب</span>
</a>
</div>
<!-- زر إضافة كويز للمعلمين فقط -->
<div id="addQuizHeaderBtn" class="hidden">
<a href="add-quiz.html" class="bg-pink-500 hover:bg-pink-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 transition-colors">
<i class="fas fa-question-circle"></i>
<span>إضافة كويز</span>
</a>
</div>
<div class="relative">
<img src="../images/photo_2025-09-03_00-20-27.jpg" class="w-12 h-12 rounded-full border-2 border-blue-400" alt="أ/ مجدي جمال" />
<div id="teacherModeIndicator" class="teacher-mode-indicator hidden">مدرس</div>
</div>
<div class="text-right">
<p class="font-semibold text-gray-800">أ/ مجدي جمال</p>
<p class="text-sm text-gray-600">مدرس الرياضيات</p>
</div>
</div>
</div>
</div>
</header>
<!-- Navigation -->
<nav class="bg-white shadow-md mt-4 overflow-x-auto">
<div class="container mx-auto px-4 py-3 flex justify-center md:justify-between gap-3 min-w-max">
<button class="nav-tab active px-6 py-2 rounded-lg font-semibold" data-tab="lessons">🎓 الحصص</button>
<button class="nav-tab px-6 py-2 rounded-lg font-semibold" data-tab="schedule">📅 الجدول</button>
<button class="nav-tab px-6 py-2 rounded-lg font-semibold" data-tab="homework">📝 الواجبات</button>
<button class="nav-tab px-6 py-2 rounded-lg font-semibold" data-tab="materials">📚 المواد</button>
<button class="nav-tab px-6 py-2 rounded-lg font-semibold" data-tab="quizzes">🎯 الكويزات</button>
</div>
</nav>
<!-- Main -->
<main class="container mx-auto px-4 py-8">
<!-- Lessons -->
<div id="lessons-tab" class="tab-content">
<h2 class="text-3xl font-bold text-center text-gray-800 mb-8">الحصص</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="lessonsGrid"></div>
<!-- الإضافة الآن من خلال صفحة add-lesson.html -->
</div>
<!-- Schedule -->
<div id="schedule-tab" class="tab-content hidden">
<h2 class="text-3xl font-bold text-center text-gray-800 mb-8">الجدول الدراسي</h2>
<!-- Teacher Tools for Schedule -->
<div id="scheduleTeacherTools" class="teacher-tools rounded-lg p-4 mb-6 hidden">
<h3 class="text-lg font-bold text-purple-800 mb-4">🛠️ أدوات المدرس - إدارة الجدول</h3>
<div class="flex flex-col md:flex-row gap-4">
<input type="text" id="scheduleDay" placeholder="اليوم (مثال: الأحد)" class="flex-1 px-3 py-2 border border-gray-300 rounded-md" />
<input type="text" id="scheduleSubject" placeholder="المادة" class="flex-1 px-3 py-2 border border-gray-300 rounded-md" />
<input type="time" id="scheduleTimeStart" class="px-3 py-2 border border-gray-300 rounded-md" />
<input type="time" id="scheduleTimeEnd" class="px-3 py-2 border border-gray-300 rounded-md" />
<button onclick="addScheduleItem()" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">➕ إضافة</button>
</div>
</div>
<div id="scheduleGrid" class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Schedule items will be generated by JavaScript -->
</div>
</div>
<!-- Homework -->
<div id="homework-tab" class="tab-content hidden">
<h2 class="text-3xl font-bold text-center text-gray-800 mb-8">الواجبات</h2>
<!-- Teacher Tools for Homework -->
<div id="homeworkTeacherTools" class="teacher-tools rounded-lg p-4 mb-6 hidden">
<h3 class="text-lg font-bold text-purple-800 mb-4">🛠️ أدوات المدرس - إدارة الواجبات</h3>
<div class="flex flex-col md:flex-row gap-4">
<input type="text" id="homeworkSubject" placeholder="المادة" class="flex-1 px-3 py-2 border border-gray-300 rounded-md" />
<textarea id="homeworkDescription" placeholder="وصف الواجب" class="flex-1 px-3 py-2 border border-gray-300 rounded-md" rows="2"></textarea>
<input type="date" id="homeworkDueDate" class="px-3 py-2 border border-gray-300 rounded-md" />
<button onclick="addHomework()" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">➕ إضافة</button>
</div>
</div>
<div id="homeworkGrid" class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Homework items will be generated by JavaScript -->
</div>
</div>
<!-- Materials -->
<div id="materials-tab" class="tab-content hidden">
<h2 class="text-3xl font-bold text-center text-gray-800 mb-8">المواد التعليمية</h2>
<!-- Teacher Tools for Materials -->
<div id="materialsTeacherTools" class="teacher-tools rounded-lg p-4 mb-6 hidden">
<h3 class="text-lg font-bold text-purple-800 mb-4">🛠️ أدوات المدرس - إدارة المواد</h3>
<div class="flex flex-col md:flex-row gap-4">
<input type="text" id="materialTitle" placeholder="عنوان المادة" class="flex-1 px-3 py-2 border border-gray-300 rounded-md" />
<input type="text" id="materialDescription" placeholder="وصف المادة" class="flex-1 px-3 py-2 border border-gray-300 rounded-md" />
<input type="url" id="materialLink" placeholder="رابط الملف أو PDF" class="flex-1 px-3 py-2 border border-gray-300 rounded-md" />
<button onclick="addMaterial()" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">➕ إضافة</button>
</div>
</div>
<div id="materialsGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<!-- Material items will be generated by JavaScript -->
</div>
</div>
<!-- Quizzes -->
<div id="quizzes-tab" class="tab-content hidden">
<h2 class="text-3xl font-bold text-center text-gray-800 mb-8">الكويزات</h2>
<!-- Teacher Tools for Quizzes -->
<div id="quizzesTeacherTools" class="teacher-tools rounded-lg p-4 mb-6 hidden">
<h3 class="text-lg font-bold text-purple-800 mb-4">🛠️ أدوات المدرس - إدارة الكويزات</h3>
<div class="flex flex-col md:flex-row gap-4">
<input type="text" id="quizTitle" placeholder="عنوان الكويز" class="flex-1 px-3 py-2 border border-gray-300 rounded-md" />
<textarea id="quizDescription" placeholder="وصف الكويز" class="flex-1 px-3 py-2 border border-gray-300 rounded-md" rows="2"></textarea>
<select id="quizStatus" class="px-3 py-2 border border-gray-300 rounded-md">
<option value="متاح">متاح</option>
<option value="قريباً">قريباً</option>
<option value="مغلق">مغلق</option>
</select>
<button onclick="addQuiz()" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">➕ إضافة</button>
</div>
</div>
<div id="quizzesGrid" class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Quiz items will be generated by JavaScript -->
</div>
</div>
</main>
<!-- JS -->
<script src="../js/auth.js"></script>
<script src="../js/lessons.js"></script>
<script>
/* =============================
حماية الوصول للصف
============================= */
(function guardAccess(){
const attempt=()=>{
if(!(window.AUTH && AUTH.getCurrentUser)) return setTimeout(attempt,50);
const user = AUTH.getCurrentUser();
if(!user){
localStorage.setItem('postLoginRedirect','grade2_1.html');
return window.location.href='index_updated.html';
}
const wanted='الصف الثاني الثانوي علمي';
const norm=g=>g?g.trim():g;
const role=(user.role||'').toLowerCase();
const isInstructor=['instructor','admin','teacher','مدرس','معلم'].includes(role);
if(!isInstructor && norm(user.grade)!==wanted){
return window.location.href='index_updated.html';
}
};
attempt();
})();
// ================== المتغيرات الخاصة بالحصة ==================
let isTeacherMode = false; // سيُحدَّث بناءً على الصلاحيات
let lessons = [];
let lessonsLoading=false, lessonsError=null;
let currentLessonSearch='', currentLessonUnit='', currentLessonPage=1; const LESSONS_PAGE_SIZE=30;
let editingLessonId=null;
// Schedule state
let schedules = [];
// Homework/Tasks state
let homework = [];
let homeworkLoading = false;
let homeworkError = null;
document.addEventListener('DOMContentLoaded', () => {
initTabs();
initStudentBanner();
setupLessonsToolbar();
loadLessons();
loadSchedules();
loadHomework();
// Try to show header buttons immediately and also after a delay
setTimeout(showHeaderButtons, 100);
setTimeout(showHeaderButtons, 500);
setTimeout(showHeaderButtons, 1000);
// Also check periodically in case auth system loads later
const checkInterval = setInterval(() => {
showHeaderButtons();
// Stop checking after 10 seconds
setTimeout(() => clearInterval(checkInterval), 10000);
}, 2000);
});
document.addEventListener('auth:user-ready',()=>{
isTeacherMode = LessonsAPI.canManage();
updateTeacherToolsVisibility();
setupLessonsToolbar(); // لإظهار زر الإضافة عند توفر الصلاحية
showHeaderButtons();
});
// Function to show header buttons for authorized users
function showHeaderButtons() {
// Check if user is authorized using multiple methods
let canManage = false;
// Method 1: Check LessonsAPI
if (window.LessonsAPI && LessonsAPI.canManage) {
try {
canManage = LessonsAPI.canManage();
} catch(e) {
console.log('LessonsAPI check failed, trying other methods');
}
}
// Method 2: Check global teacher mode
if (!canManage) {
canManage = localStorage.getItem('globalTeacherMode') === 'true';
}
// Method 3: Check user data directly
if (!canManage) {
try {
const userData = localStorage.getItem('user') || localStorage.getItem('userData');
if (userData) {
const user = JSON.parse(userData);
const role = (user.role || '').toLowerCase();
canManage = ['instructor', 'admin', 'teacher', 'مدرس', 'معلم'].includes(role);
}
} catch(e) {}
}
// Method 4: Check if isTeacherMode is true
if (!canManage) {
canManage = isTeacherMode === true;
}
console.log('Header buttons check - canManage:', canManage);
if (canManage) {
const addLessonHeaderBtn = document.getElementById('addLessonHeaderBtn');
if (addLessonHeaderBtn) {
addLessonHeaderBtn.classList.remove('hidden');
console.log('Shown add lesson button');
}
const addScheduleHeaderBtn = document.getElementById('addScheduleHeaderBtn');
if (addScheduleHeaderBtn) {
addScheduleHeaderBtn.classList.remove('hidden');
console.log('Shown add schedule button');
}
const addHomeworkHeaderBtn = document.getElementById('addHomeworkHeaderBtn');
if (addHomeworkHeaderBtn) {
addHomeworkHeaderBtn.classList.remove('hidden');
console.log('Shown add homework button');
}
// Show add quiz header button
const addQuizHeaderBtn = document.getElementById('addQuizHeaderBtn');
if (addQuizHeaderBtn) {
addQuizHeaderBtn.classList.remove('hidden');
console.log('Shown add quiz button');
}
}
}
function initStudentBanner(){
const studentName = localStorage.getItem('studentName') || '👤 الطالب';
document.getElementById('studentName').textContent = studentName;
if(studentName && studentName !== '👤 الطالب'){
document.getElementById('welcomeBox').classList.remove('hidden');
document.getElementById('welcomeText').textContent = `👋 أهلاً، ${studentName} — الصف الثاني الثانوي علمي 🎉`;
}
}
function initTabs(){
const tabs=document.querySelectorAll('.nav-tab');
const contents=document.querySelectorAll('.tab-content');
tabs.forEach(tab=>tab.addEventListener('click',function(){
tabs.forEach(t=>t.classList.remove('active'));
this.classList.add('active');
contents.forEach(c=>c.classList.add('hidden'));
document.getElementById(this.dataset.tab+'-tab').classList.remove('hidden');
}));
}
// ================== الدروس الديناميكية ==================
async function loadLessons(){
if(lessonsLoading) return; lessonsLoading=true; lessonsError=null;
const grid=document.getElementById('lessonsGrid');
grid.innerHTML = `<div class='col-span-full text-center py-10 text-gray-600'>جارٍ تحميل الحصص...</div>`;
try {
// Use grade-specific endpoint for 2nd secondary science
const resp = await fetch('https://courses-nine-eta.vercel.app/api/lessons/grade/2nd-secondary-science');
const data = await resp.json();
lessons = (data.data || data.lessons || []).map(l=>{ if(!l.id && l._id) l.id=l._id; return l; });
renderLessons();
refreshUnitFilter();
} catch(e){
lessonsError=e; console.error(e);
grid.innerHTML = `<div class='col-span-full text-center py-10 text-red-600'>فشل تحميل الحصص <button class='underline' onclick='loadLessons()'>إعادة المحاولة</button></div>`;
} finally { lessonsLoading=false; }
}
function renderLessons(){
const grid=document.getElementById('lessonsGrid');
if(!lessons.length){ grid.innerHTML = `<div class='col-span-full text-center py-10 text-gray-500'>لا توجد حصص بعد</div>`; return; }
grid.innerHTML='';
lessons.forEach(l=> grid.appendChild(createLessonCard(l)) );
}
// Load schedules from API
async function loadSchedules() {
try {
const token = localStorage.getItem('authToken') || '';
const response = await fetch('https://courses-nine-eta.vercel.app/api/schedule/grade/2nd-secondary-science', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
schedules = (data.data || data.schedules || []).map(s => {
if (!s.id && s._id) s.id = s._id;
return s;
});
renderSchedule();
} else {
console.error('Failed to load schedules');
renderSchedule(); // Render empty state
}
} catch (error) {
console.error('Schedule load error:', error);
renderSchedule(); // Render empty state
}
}
// Load homework from API
async function loadHomework() {
if (homeworkLoading) return;
homeworkLoading = true;
homeworkError = null;
renderHomework(); // عرض حالة التحميل
try {
const token = localStorage.getItem('authToken') || '';
const response = await fetch('https://courses-nine-eta.vercel.app/api/tasks/grade/second-secondary-science', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
homework = data.data || [];
} else {
console.error('Failed to load homework:', response.statusText);
homeworkError = new Error('Failed to load homework');
}
} catch (error) {
console.error('Load homework error:', error);
homeworkError = error;
} finally {
homeworkLoading = false;
renderHomework(); // إعادة عرض النتائج النهائية
}
}
function createLessonCard(lesson){
const card=document.createElement('div');
card.className='card bg-white rounded-xl shadow-lg p-6 border-l-4 border-indigo-500 relative flex flex-col';
const canManage=isTeacherMode;
const title=lesson.lessonTitle || lesson.title || 'بدون عنوان';
const unit=lesson.unitTitle || lesson.unit || '';
const video=lesson.videoUrl || lesson.video || lesson.video_link;
card.innerHTML=`
${canManage?'<div class="teacher-mode-indicator">مدرس</div>':''}
<div class='flex justify-between items-start mb-2'>
<div>
<h3 class='text-lg font-bold text-indigo-800 mb-1 line-clamp-2'>${title}</h3>
${unit?`<span class='inline-block text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded-full'>${unit}</span>`:''}
</div>
${canManage?`<div class='relative'>
<button class='text-gray-500 hover:text-gray-700' onclick='this.nextElementSibling.classList.toggle("hidden")'>⋮</button>
<div class='hidden absolute left-0 mt-1 w-32 bg-white border rounded shadow z-10'>
<button class='block w-full text-right px-3 py-1 text-sm hover:bg-gray-100' onclick='openLessonModal("${lesson.id}")'>✏️ تعديل</button>
<button class='block w-full text-right px-3 py-1 text-sm text-red-600 hover:bg-red-100' onclick='deleteLessonConfirm("${lesson.id}")'>🗑️ حذف</button>
</div>
</div>`:''}
</div>
<div class='mt-auto pt-2'>
${video?`<button onclick='openLessonDetail("${lesson.id}")' class='w-full bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition flex items-center justify-center gap-2'>▶️ مشاهدة الدرس</button>`:`<div class='w-full bg-gray-300 text-gray-600 px-4 py-2 rounded-lg text-center text-sm'>لا يوجد فيديو</div>`}
</div>`;
return card;
}
function openLessonDetail(id){ window.location.href = `lesson.html?id=${encodeURIComponent(id)}`; }
function setupLessonsToolbar(){
const container = document.querySelector('#lessons-tab');
if(!container) return;
let bar=document.getElementById('lessonsToolbar');
if(!bar){
bar=document.createElement('div');
bar.id='lessonsToolbar';
bar.className='mb-6';
container.insertBefore(bar, container.querySelector('#lessonsGrid'));
}
const canManage=isTeacherMode;
bar.innerHTML = `
<div class='flex flex-col md:flex-row gap-3'>
<div class='flex-1 flex items-stretch gap-2'>
<input id='lessonSearch' type='text' placeholder='🔍 بحث...' class='flex-1 px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500'/>
<select id='lessonUnitFilter' class='px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-purple-500'>
<option value=''>كل الوحدات</option>
</select>
</div>
${canManage?`<a href='add-lesson.html' class='px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 text-sm flex items-center gap-2 self-start'>➕ إضافة حصة</a>`:''}
</div>`;
if(canManage && document.getElementById('addLessonBtn')) document.getElementById('addLessonBtn').addEventListener('click',()=>openLessonModal());
const search=document.getElementById('lessonSearch');
if(search){ let deb; search.addEventListener('input',e=>{ clearTimeout(deb); deb=setTimeout(()=>{ currentLessonSearch=e.target.value.trim(); currentLessonPage=1; loadLessons(); },350); }); }
const unitSel=document.getElementById('lessonUnitFilter');
if(unitSel){ unitSel.addEventListener('change',e=>{ currentLessonUnit=e.target.value; currentLessonPage=1; loadLessons(); }); }
}
function refreshUnitFilter(){
const select=document.getElementById('lessonUnitFilter');
if(!select) return;
const current=select.value;
const units=[...new Set(lessons.map(l=>l.unitTitle||l.unit).filter(Boolean))];
select.innerHTML = `<option value=''>كل الوحدات</option>` + units.map(u=>`<option value='${u}' ${u===current?'selected':''}>${u}</option>`).join('');
}
// تم نقل الإضافة والتعديل إلى صفحة مستقلة add-lesson.html
async function deleteLessonConfirm(id){ if(!confirm('حذف الحصة؟')) return; try { await LessonsAPI.deleteLesson(id); showNotification('تم الحذف','success'); loadLessons(); } catch(_){ showNotification('فشل الحذف','error'); } }
function updateTeacherToolsVisibility(){
if(isTeacherMode){
showTeacherTools();
showHeaderButtons(); // إظهار أزرار الheader أيضاً
} else {
hideTeacherTools();
}
}
// ================== وظائف الجدول / الواجبات / المواد / الكويزات (قديمة) ==================
function renderAllContent(){
renderLessons();
renderSchedule();
renderHomework();
renderMaterials();
renderQuizzes();
}
// Toggle between teacher and student mode
function toggleMode() {
isTeacherMode = !isTeacherMode;
localStorage.setItem('globalTeacherMode', isTeacherMode.toString());
updateModeDisplay();
renderAllContent();
showHeaderButtons(); // إظهار الأزرار عند التبديل
showNotification(
isTeacherMode ? 'تم التبديل إلى وضع المدرس 👨🏫' : 'تم التبديل إلى وضع الطالب 👨🎓',
'success'
);
}
// Update mode display
function updateModeDisplay() {
const modeToggle = document.getElementById('modeToggle');
const modeText = document.getElementById('modeText');
const indicator = document.getElementById('teacherModeIndicator');
if (isTeacherMode) {
modeToggle.className = 'px-4 py-2 bg-green-600 text-white rounded-lg shadow hover:bg-green-700 transition-colors';
modeText.textContent = '👨🎓 وضع الطالب';
indicator.classList.remove('hidden');
showTeacherTools();
showHeaderButtons(); // إظهار أزرار الheader
} else {
modeToggle.className = 'px-4 py-2 bg-purple-600 text-white rounded-lg shadow hover:bg-purple-700 transition-colors';
modeText.textContent = '🎓 وضع المدرس';
indicator.classList.add('hidden');
hideTeacherTools();
}
}
// Show/Hide teacher tools
function showTeacherTools() {
document.getElementById('scheduleTeacherTools').classList.remove('hidden');
document.getElementById('homeworkTeacherTools').classList.remove('hidden');
document.getElementById('materialsTeacherTools').classList.remove('hidden');
document.getElementById('quizzesTeacherTools').classList.remove('hidden');
}
function hideTeacherTools() {
document.getElementById('scheduleTeacherTools').classList.add('hidden');
document.getElementById('homeworkTeacherTools').classList.add('hidden');
document.getElementById('materialsTeacherTools').classList.add('hidden');
document.getElementById('quizzesTeacherTools').classList.add('hidden');
}
// Render all content
function renderAllContent() {
renderLessons();
renderSchedule();
renderHomework();
renderMaterials();
renderQuizzes();
}
// (تم استبدال نظام الحصص القديم بنظام ديناميكي)
// Render schedule
function renderSchedule() {
const scheduleGrid = document.getElementById('scheduleGrid');
// Use API data or show empty state
if (!schedules || schedules.length === 0) {
scheduleGrid.innerHTML = `<div class="col-span-full text-center py-10 text-gray-500">لا توجد جداول دراسية متاحة حالياً</div>`;
return;
}
scheduleGrid.innerHTML = '';
// Group by day
const groupedByDay = schedules.reduce((acc, item) => {
if (!acc[item.day]) acc[item.day] = [];
acc[item.day].push(item);
return acc;
}, {});
Object.keys(groupedByDay).forEach(day => {
const dayCard = document.createElement('div');
dayCard.className = 'bg-white rounded-xl shadow-lg overflow-hidden';
let dayContent = `
<div class="schedule-time px-4 py-3 text-white text-center">
<h3 class="font-bold text-lg">${day}</h3>
</div>
<div class="p-4 space-y-3">
`;
groupedByDay[day].forEach(item => {
const canManage = window.LessonsAPI && LessonsAPI.canManage();
const timeFrom = item.timeFrom || item.startTime || '';
const timeTo = item.timeTo || item.endTime || '';
const scheduleId = item.id || item._id;
dayContent += `
<div class="schedule-card bg-blue-50 border-l-4 border-blue-400 p-3 rounded-lg relative">
${canManage ? '<div class="teacher-mode-indicator">قابل للتعديل</div>' : ''}
<div class="flex justify-between items-start">
<div class="flex-1">
<span class="font-semibold text-blue-800">${item.subject}</span>
<div class="text-sm text-blue-600 mt-1">${timeFrom} - ${timeTo}</div>
${item.date ? `<div class="text-xs text-gray-500 mt-1">${new Date(item.date).toLocaleDateString('ar-EG')}</div>` : ''}
</div>
${canManage ? `
<div class="relative">
<button class="text-gray-500 hover:text-gray-700" onclick="this.nextElementSibling.classList.toggle('hidden')">⋮</button>
<div class="hidden absolute left-0 mt-1 w-32 bg-white border rounded shadow z-10">
<button class="block w-full text-right px-3 py-1 text-sm hover:bg-gray-100" onclick="editScheduleItem('${scheduleId}')">✏️ تعديل</button>
<button class="block w-full text-right px-3 py-1 text-sm text-red-600 hover:bg-red-100" onclick="deleteScheduleItem('${scheduleId}')">🗑️ حذف</button>
</div>
</div>
` : ''}
</div>
</div>
`;
});
dayContent += '</div>';
dayCard.innerHTML = dayContent;
scheduleGrid.appendChild(dayCard);
});
}
// Render homework
function renderHomework() {
const homeworkGrid = document.getElementById('homeworkGrid');
if (homeworkLoading) {
homeworkGrid.innerHTML = '<div class="col-span-full text-center py-10 text-gray-600">جارٍ تحميل الواجبات...</div>';
return;
}
if (homeworkError) {
homeworkGrid.innerHTML = '<div class="col-span-full text-center py-10 text-red-600">فشل تحميل الواجبات <button class="underline" onclick="loadHomework()">إعادة المحاولة</button></div>';
return;
}
if (homework.length === 0) {
homeworkGrid.innerHTML = '<div class="col-span-full text-center py-10 text-gray-600">لا توجد واجبات متاحة</div>';
return;
}
homeworkGrid.innerHTML = '';
homework.forEach((item) => {
const homeworkCard = document.createElement('div');
homeworkCard.className = 'card bg-white rounded-xl shadow-lg p-6 border-blue-400 relative';
// Calculate days until due
const dueDate = new Date(item.dueDate);
const today = new Date();
const diffTime = dueDate - today;
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
let statusText = 'منتهي';
let statusColor = 'bg-red-100 text-red-800';
if (diffDays > 7) {
statusText = 'الأسبوع القادم';
statusColor = 'bg-blue-100 text-blue-800';
} else if (diffDays > 1) {
statusText = `بعد ${diffDays} أيام`;
statusColor = 'bg-yellow-100 text-yellow-800';
} else if (diffDays === 1) {
statusText = 'غداً';
statusColor = 'bg-orange-100 text-orange-800';
} else if (diffDays === 0) {
statusText = 'اليوم';
statusColor = 'bg-red-100 text-red-800';
}
// Priority colors
let priorityColor = 'border-blue-400';
if (item.priority === 'عاجل') priorityColor = 'border-red-400';
else if (item.priority === 'عالي') priorityColor = 'border-orange-400';
else if (item.priority === 'متوسط') priorityColor = 'border-yellow-400';
homeworkCard.className = `card bg-white rounded-xl shadow-lg p-6 ${priorityColor} relative`;
homeworkCard.innerHTML = `
${isTeacherMode ? '<div class="teacher-mode-indicator">قابل للتعديل</div>' : ''}
<div class="flex items-center justify-between mb-4">
<h3 class="text-xl font-bold text-blue-800">${item.subject}</h3>
<span class="px-3 py-1 ${statusColor} rounded-full text-sm">${statusText}</span>
</div>
<h4 class="text-md font-semibold text-gray-800 mb-2">${item.title}</h4>
<p class="text-gray-700 mb-4">${item.description}</p>
<div class="flex justify-between items-center text-sm text-gray-600 mb-4">
<span>تاريخ التسليم: ${new Date(item.dueDate).toLocaleDateString('ar-EG')}</span>
<span class="px-2 py-1 bg-gray-100 rounded">${item.priority}</span>
</div>
${item.attachments && item.attachments.length > 0 ? `
<div class="mb-4">
<h5 class="text-sm font-medium text-gray-700 mb-2">المرفقات:</h5>
${item.attachments.map(att => `
<a href="${att.url}" target="_blank" class="text-blue-600 hover:text-blue-800 text-sm block">
<i class="fas fa-paperclip ml-1"></i> ${att.filename}
</a>
`).join('')}
</div>
` : ''}
${isTeacherMode ? `
<div class="teacher-tools rounded-lg p-3">
<button
onclick="editHomework('${item._id || item.id}')"
class="px-3 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm ml-2"
>
✏️ تعديل
</button>
<button
onclick="deleteHomework('${item._id || item.id}')"
class="px-3 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors text-sm"
>
🗑️ حذف
</button>
</div>
` : ''}
`;
homeworkGrid.appendChild(homeworkCard);
});
}
// Render materials
function renderMaterials() {
const materialsGrid = document.getElementById('materialsGrid');
const materials = JSON.parse(localStorage.getItem('materials_grade2sci') || '[]');
// Default materials if empty
if (materials.length === 0) {
materials.push({
title: 'ملخص الرياضيات',
description: 'جبر وهندسة',
files: [
{ name: 'تمارين الجبر.pdf', link: '#' },
{ name: 'مسائل الهندسة.pdf', link: '#' }
]
});
}
materialsGrid.innerHTML = '';
materials.forEach((material, index) => {
const materialCard = document.createElement('div');
materialCard.className = 'card bg-white rounded-xl shadow-lg p-6 relative';
let filesHtml = '';
material.files.forEach((file, fileIndex) => {
filesHtml += `
<div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<span class="text-sm">${file.name}</span>
<div class="flex gap-2">
<button onclick="downloadFile('${file.link}')" class="text-blue-600 hover:text-indigo-600"><i class="fas fa-download"></i></button>
${isTeacherMode ? `
<button onclick="removeMaterialFile(${index}, ${fileIndex})" class="text-red-600 hover:text-red-800"><i class="fas fa-trash"></i></button>
` : ''}
</div>
</div>
`;
});
materialCard.innerHTML = `
${isTeacherMode ? '<div class="teacher-mode-indicator">قابل للتعديل</div>' : ''}
<div class="text-center mb-4">
<i class="fas fa-file-pdf text-blue-500 text-4xl mb-2"></i>
<h3 class="font-bold text-gray-800">${material.title}</h3>
<p class="text-sm text-gray-600">${material.description}</p>
</div>
<div class="space-y-2">
${filesHtml}
</div>
${isTeacherMode ? `
<div class="teacher-tools rounded-lg p-3 mt-4">
<button
onclick="removeMaterial(${index})"
class="px-3 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors text-sm"
>
🗑️ حذف المجموعة
</button>
</div>
` : ''}
`;
materialsGrid.appendChild(materialCard);
});
}
// Render quizzes
function renderQuizzes() {
const quizzesGrid = document.getElementById('quizzesGrid');
const quizzes = JSON.parse(localStorage.getItem('quizzes_grade2sci') || '[]');
// Default quizzes if empty
if (quizzes.length === 0) {
quizzes.push({
title: 'كويز جبر',
description: '10 أسئلة اختيار من متعدد',
status: 'متاح'
});
}
quizzesGrid.innerHTML = '';
quizzes.forEach((quiz, index) => {
const quizCard = document.createElement('div');
quizCard.className = 'card bg-white rounded-xl shadow-lg p-6 border-yellow-400 relative';
const statusColors = {
'متاح': 'bg-yellow-100 text-yellow-800',
'قريباً': 'bg-blue-100 text-blue-800',
'مغلق': 'bg-red-100 text-red-800'
};
quizCard.innerHTML = `
${isTeacherMode ? '<div class="teacher-mode-indicator">قابل للتعديل</div>' : ''}
<div class="flex items-center justify-between mb-4">
<h3 class="text-xl font-bold text-yellow-800">${quiz.title}</h3>
<span class="px-3 py-1 ${statusColors[quiz.status]} rounded-full text-sm">${quiz.status}</span>
${isTeacherMode ? `
<div class='relative'>
<button class='text-gray-500 hover:text-gray-700 px-2' onclick="this.nextElementSibling.classList.toggle('hidden')">⋮</button>
<div class='hidden absolute left-0 mt-1 w-32 bg-white border rounded shadow z-10'>
<button class='block w-full text-right px-3 py-1 text-sm hover:bg-gray-100' onclick='editQuiz(${index})'>✏️ تعديل</button>
<button class='block w-full text-right px-3 py-1 text-sm text-red-600 hover:bg-red-100' onclick='removeQuiz(${index})'>🗑️ حذف</button>
</div>
</div>
` : ''}
</div>
<p class="text-gray-700 mb-4">${quiz.description}</p>
<div class="flex justify-between items-center">
${quiz.status === 'متاح' ? `
<button class="bg-yellow-500 text-white px-4 py-2 rounded-lg shadow hover:bg-yellow-600 flex-1">ابدأ الآن</button>
` : `
<button disabled class="bg-gray-400 text-white px-4 py-2 rounded-lg shadow cursor-not-allowed flex-1">${quiz.status}</button>
`}
</div>
`;
quizzesGrid.appendChild(quizCard);
});
}
// Teacher tools functions
function editQuiz(index) {
// مثال: توجيه لصفحة التعديل مع معرف الكويز
// يمكن لاحقاً استخدام id حقيقي من API
window.location.href = `add-quiz.html?edit=${index}`;
}
function addScheduleItem() {
const day = document.getElementById('scheduleDay').value.trim();
const subject = document.getElementById('scheduleSubject').value.trim();
const startTime = document.getElementById('scheduleTimeStart').value;
const endTime = document.getElementById('scheduleTimeEnd').value;
if (!day || !subject || !startTime || !endTime) {
showNotification('يرجى ملء جميع الحقول', 'error');
return;
}
const scheduleItems = JSON.parse(localStorage.getItem('scheduleItems_grade2sci') || '[]');
scheduleItems.push({ day, subject, startTime, endTime });
localStorage.setItem('scheduleItems_grade2sci', JSON.stringify(scheduleItems));
// Clear inputs
document.getElementById('scheduleDay').value = '';
document.getElementById('scheduleSubject').value = '';
document.getElementById('scheduleTimeStart').value = '';
document.getElementById('scheduleTimeEnd').value = '';
renderSchedule();
showNotification('تمت إضافة الجلسة بنجاح', 'success');
}
function addHomework() {
const subject = document.getElementById('homeworkSubject').value.trim();
const description = document.getElementById('homeworkDescription').value.trim();
const dueDate = document.getElementById('homeworkDueDate').value;
if (!subject || !description || !dueDate) {
showNotification('يرجى ملء جميع الحقول', 'error');
return;
}
const homeworkItems = JSON.parse(localStorage.getItem('homeworkItems_grade2sci') || '[]');
const today = new Date();
const due = new Date(dueDate);
const diffDays = Math.ceil((due - today) / (1000 * 60 * 60 * 24));
let status = 'متأخر';
if (diffDays === 1) status = 'غداً';
else if (diffDays <= 7 && diffDays > 1) status = 'هذا الأسبوع';
else if (diffDays > 7) status = 'الأسبوع القادم';
homeworkItems.push({ subject, description, dueDate, status });