-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate.php
More file actions
1124 lines (1019 loc) · 59.2 KB
/
create.php
File metadata and controls
1124 lines (1019 loc) · 59.2 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
<?php
// create.php
function generateId($length = 7) {
return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), 0, $length);
}
function generateProfCode($length = 10) {
return substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
}
if ($_POST['action'] == 'create_qcm') {
$qcmId = generateId();
$profCode = generateProfCode();
$qcmData = [
'id' => $qcmId,
'prof_code' => $profCode,
'title' => $_POST['title'],
'created_at' => gmdate('Y-m-d H:i:s'),
'questions' => json_decode($_POST['questions'], true)
];
// Créer le dossier du QCM
$qcmDir = "data/$qcmId";
if (!file_exists($qcmDir)) {
mkdir($qcmDir, 0777, true);
}
// Sauvegarder le QCM
file_put_contents("$qcmDir/qcm.json", json_encode($qcmData, JSON_PRETTY_PRINT));
echo json_encode([
'success' => true,
'qcm_id' => $qcmId,
'prof_code' => $profCode
]);
exit;
}
if (isset($_POST['action']) && $_POST['action'] == 'generate_print_copies') {
$qcmId = trim($_POST['qcm_id']);
$studentCount = max(1, intval($_POST['student_count']));
$qcmFile = "data/$qcmId/qcm.json";
if (!file_exists($qcmFile)) {
die('QCM introuvable');
}
$qcmData = json_decode(file_get_contents($qcmFile), true);
// Génération des copies
$copies = [];
// Génère un UID de copie unique
$genCopyUid = function($copyNumber) {
return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), 0, 12)
. '_copy' . $copyNumber . '_' . time() . '_' . rand(1000, 9999);
};
for ($copyNumber = 1; $copyNumber <= $studentCount; $copyNumber++) {
$uid = $genCopyUid($copyNumber);
$questions = $qcmData['questions'];
$questionOrder = range(0, count($questions) - 1);
shuffle($questionOrder);
$studentQcm = [
'uid' => $uid,
'qcm_id' => $qcmId,
'student_name' => '',
'student_firstname' => '',
'copy_number' => $copyNumber,
'created_at' => gmdate('Y-m-d H:i:s'),
'question_order' => $questionOrder,
'questions' => [],
'mapping' => []
];
foreach ($questionOrder as $index => $originalIndex) {
$originalQuestion = $questions[$originalIndex];
// Randomiser les choix
$choiceOrder = range(0, count($originalQuestion['choices']) - 1);
shuffle($choiceOrder);
$responseCodes = ['1','2','3','4'];
$studentQuestion = [
'question' => $originalQuestion['question'],
'choices' => [],
'response_codes' => $responseCodes,
'choice_order' => $choiceOrder
];
foreach ($choiceOrder as $i => $originalChoiceIndex) {
$studentQuestion['choices'][] = $originalQuestion['choices'][$originalChoiceIndex];
}
$studentQcm['questions'][] = $studentQuestion;
// Mapping pour correction
$correctChoiceIndex = array_search($originalQuestion['correct_answer'], $originalQuestion['choices']);
$newCorrectIndex = array_search($correctChoiceIndex, $choiceOrder);
$correctCode = $responseCodes[$newCorrectIndex];
$studentQcm['mapping'][] = [
'original_question_index' => $originalIndex,
'student_question_index' => $index,
'correct_response_code' => $correctCode,
'explanation' => $originalQuestion['explanation']
];
}
// Sauvegarde de la copie
$qcmDir = "data/$qcmId";
if (!file_exists($qcmDir)) {
mkdir($qcmDir, 0777, true);
}
file_put_contents("$qcmDir/$uid.json", json_encode($studentQcm, JSON_PRETTY_PRINT));
$copies[] = $studentQcm;
}
// Rendu de la page d'impression (UI/UX intégrée)
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$basePath = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Impression QCM - <?php echo htmlspecialchars($qcmData['title']); ?></title>
<link rel="icon" href="favicon.ico" />
<link type="image/png" sizes="16x16" rel="icon" href="./icons/icons8-mangue-clr-gls-16.png">
<link type="image/png" sizes="32x32" rel="icon" href="./icons/icons8-mangue-clr-gls-32.png">
<link type="image/png" sizes="96x96" rel="icon" href="./icons/icons8-mangue-clr-gls-96.png">
<link type="image/png" sizes="120x120" rel="icon" href="./icons/icons8-mangue-clr-gls-120.png">
<style>
:root { --bg: linear-gradient(135deg, #f59e0b 0%, #f97316 50%, #fb923c 100%); --card:#fff; --text:#0f172a; --muted:#64748b; --border:#e5e7eb; --radius:14px; --primary:#f59e0b; --primary-700:#d97706; --success:#16a34a; }
/* Écran */
body { margin:0; font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, sans-serif; background: var(--bg); color: var(--text); }
.screen-only { display: block; max-width: 1000px; margin: 0 auto; padding: clamp(16px,3vw,28px); }
.screen-only h1 { color:#fff; text-align:center; margin:0; font-size: clamp(22px,5vw,34px); font-weight:800; }
.screen-only h2 { color:#eef2ff; text-align:center; margin:8px 0 16px; font-size: clamp(16px,3.5vw,22px); font-weight:600; opacity:.95; }
.screen-card { background: var(--card); border-radius: var(--radius); border:1px solid var(--border); box-shadow: 0 10px 30px rgba(0,0,0,.12); padding: clamp(16px,2.5vw,24px); }
.btn { background: var(--primary); color: #fff; border: none; padding: 12px 20px; font-size: 15px; border-radius: 10px; cursor: pointer; margin: 10px 6px; font-weight:700; }
.btn:hover { background: var(--primary-700); }
.btn-print { background: var(--success); }
.success { background: #ecfdf5; color: #065f46; padding: 14px; border-radius: 12px; margin: 15px 0; border:1px solid #a7f3d0; }
.info-box { background: #f1f5f9; border:1px solid var(--border); padding: 14px; border-radius: 12px; margin: 16px 0; }
.rgpd-box { background: #fff7ed; border:1px solid #fed7aa; padding: 14px; border-radius: 12px; margin: 16px 0; }
.prof-box { background: #eef2ff; border:1px solid #c7d2fe; padding: 14px; border-radius: 12px; margin: 16px 0; }
.code-chip { display:inline-flex; align-items:center; gap:8px; background:#111827; color:#fff; padding:8px 12px; border-radius:10px; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', monospace; letter-spacing: 2px; }
.copy-btn { background:#111827; color:#fff; border:1px solid #374151; border-radius:8px; padding:6px 10px; cursor:pointer; font-weight:700; }
.copy-btn:hover { filter: brightness(1.1); }
/* Impression */
@media print { .screen-only { display: none !important; } }
@media print {
body { margin:0; padding:0; font-family: Arial, sans-serif; font-size: 11px; line-height: 1.2; }
.qcm-page { width: 210mm; min-height: 297mm; margin: 0; padding: 15mm; box-sizing: border-box; page-break-after: always; display: block; }
.qcm-page:last-child { page-break-after: auto; }
.qcm-header { display:flex; justify-content: space-between; align-items:flex-start; margin-bottom: 20px; border-bottom: 2px solid #000; padding-bottom: 15px; }
.student-info { flex: 1; }
.student-info h2 { margin:0 0 10px 0; font-size: 16px; font-weight: bold; }
.info-line { margin: 8px 0; font-size: 12px; }
.qr-section { text-align: right; flex-shrink: 0; margin-left: 20px; }
.qr-img { width: 80px; height: 80px; border: 1px solid #000; }
.instructions { background: #f8f9fa; padding: 10px; border: 1px solid #ddd; margin-bottom: 20px; font-size: 10px; }
.questions-container { columns: 2; column-gap: 20px; column-fill: balance; }
.question-block { break-inside: avoid; page-break-inside: avoid; margin-bottom: 15px; border: 1px solid #ddd; padding: 10px; background: #fff; }
.question-number { font-weight: bold; margin-bottom: 8px; font-size: 12px; }
.question-text { margin-bottom: 10px; line-height: 1.3; }
.choices { margin-left: 10px; }
.choice { margin: 6px 0; display: flex; align-items: flex-start; }
.choice-box { width: 12px; height: 12px; border: 2px solid #000; margin-right: 8px; flex-shrink: 0; margin-top: 2px; }
.choice-code { font-weight: bold; margin-right: 8px; min-width: 15px; }
.choice-text { flex: 1; line-height: 1.2; }
.reminder { margin-top: 20px; page-break-inside: avoid; text-align:center; font-size: 11px; }
}
.print-only { display: none; }
@media print { .print-only { display: block; } }
</style>
</head>
<body>
<div class="screen-only">
<h1>📄 Impression QCM</h1>
<h2><?php echo htmlspecialchars($qcmData['title']); ?></h2>
<div class="screen-card">
<div class="success">✅ <strong><?php echo count($copies); ?> copies générées avec succès !</strong><br> Cliquez sur « Imprimer » pour générer le PDF via votre navigateur.</div>
<div style="text-align:center; margin:12px 0 20px;">
<button onclick="window.print()" class="btn btn-print">🖨️ Imprimer toutes les copies</button>
<a href="create.php" class="btn">🔄 Retour</a>
</div>
<div class="prof-box">
<h3 style="margin:0 0 8px;">🎓 Accès Professeur</h3>
<p style="margin:0 0 10px;">Pour consulter les résultats, statistiques et exporter en CSV, rendez-vous dans l’Espace Professeur et entrez ce code :</p>
<div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
<span class="code-chip" id="prof-code-chip"><?php echo htmlspecialchars($qcmData['prof_code'] ?? ''); ?></span>
<button id="copy-prof-code-print" class="copy-btn" type="button" title="Copier">Copier</button>
<a href="prof.php" class="btn" style="padding:8px 12px;">Ouvrir l’Espace Professeur</a>
</div>
</div>
<div class="info-box">
<h3 style="margin:0 0 8px;">💡 Instructions d'impression</h3>
<ol style="margin:0 0 0 18px; padding:0; line-height:1.6;">
<li>Cliquez sur « Imprimer toutes les copies » si la pop-up d'impression ne se montre pas toute seule</li>
<li>Choisissez « Enregistrer au format PDF » comme destination</li>
<li>Vérifiez que « Paramètres supplémentaires » → « Graphisme de l'arrière-plan » est coché</li>
<li>Cliquez sur « Enregistrer »</li>
</ol>
</div>
<div class="rgpd-box">
<h3 style="margin:0 0 8px;">🔒 Conformité RGPD</h3>
<p style="margin:0;">Aucune donnée personnelle (nom, prénom) n'est stockée lors de l'impression. Les noms sont saisis au moment de la correction.</p>
</div>
</div>
</div>
<div class="print-only">
<?php foreach ($copies as $copy): ?>
<div class="qcm-page">
<div class="qcm-header">
<div class="student-info">
<h2><?php echo htmlspecialchars($qcmData['title']); ?></h2>
<div class="info-line"><strong>Merci d'écrire en CAPITALES</strong></div>
<div class="info-line">Nom : ________________________________</div>
<div class="info-line">Prénom : ________________________________</div>
<div class="info-line">Classe : ________________________________</div>
<div class="info-line" style="margin-top: 15px;"><strong>Coloriez en NOIR les bonnes réponses</strong></div>
</div>
<div class="qr-section">
<?php
$fullUrl = $scheme . '://' . $host . $basePath . '/qcm.php?id=' . urlencode($qcmId) . '&uid=' . urlencode($copy['uid']);
$qrApiUrl = "https://api.qrserver.com/v1/create-qr-code/?size=80x80&data=" . urlencode($fullUrl);
?>
<img class="qr-img" src="<?php echo $qrApiUrl; ?>" alt="QR Code">
<div style="font-size: 8px; text-align: center; word-break: break-all; max-width: 80px;">
<?php echo htmlspecialchars($fullUrl); ?>
</div>
</div>
</div>
<div class="instructions">
<strong>Instructions :</strong>
<ul>
<li>Pour chaque question, coloriez complètement la case correspondant à votre réponse.</li>
<li>Notez le <strong>chiffre</strong> (1, 2, 3 ou 4) associé à votre réponse.</li>
<li>Écrivez à la suite tous les chiffres, dans l'ordre des questions, pour former votre <strong>code unique</strong>.</li>
</ul>
<div style="text-align:center; font-size:11px; margin-top:8px;"><strong>Votre code contiendra <?php echo count($copy['questions']); ?> chiffres.</strong></div>
Rendez-vous sur le lien/QR de la copie, saisissez vos nom/prénom et ce code pour obtenir la correction.
</div>
<div class="questions-container">
<?php for ($i = 0; $i < count($copy['questions']); $i++): $q = $copy['questions'][$i]; ?>
<div class="question-block">
<div class="question-number">Question <?php echo $i + 1; ?></div>
<div class="question-text"><?php echo htmlspecialchars($q['question']); ?></div>
<div class="choices">
<?php for ($c = 0; $c < count($q['choices']); $c++): ?>
<div class="choice">
<div class="choice-box"></div>
<div class="choice-code"><?php echo $q['response_codes'][$c]; ?></div>
<div class="choice-text"><?php echo htmlspecialchars($q['choices'][$c]); ?></div>
</div>
<?php endfor; ?>
</div>
</div>
<?php endfor; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<script>
(function(){
const btn = document.getElementById('copy-prof-code-print');
const codeEl = document.getElementById('prof-code-chip');
if (btn && codeEl) {
btn.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(codeEl.textContent.trim());
const prev = btn.textContent;
btn.textContent = 'Copié !';
setTimeout(()=> btn.textContent = prev, 1200);
} catch (e) {
alert('Impossible de copier automatiquement. Code: ' + codeEl.textContent.trim());
}
});
}
})();
</script>
</body>
</html>
<?php
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Créer un QCM</title>
<link rel="icon" href="favicon.ico" />
<link type="image/png" sizes="16x16" rel="icon" href="./icons/icons8-mangue-clr-gls-16.png">
<link type="image/png" sizes="32x32" rel="icon" href="./icons/icons8-mangue-clr-gls-32.png">
<link type="image/png" sizes="96x96" rel="icon" href="./icons/icons8-mangue-clr-gls-96.png">
<link type="image/png" sizes="120x120" rel="icon" href="./icons/icons8-mangue-clr-gls-120.png">
<style>
:root {
--bg: linear-gradient(135deg, #f59e0b 0%, #f97316 50%, #fb923c 100%);
--card: #ffffff;
--text: #0f172a;
--muted: #64748b;
--primary: #f59e0b;
--primary-700: #d97706;
--success: #16a34a;
--warning: #f59e0b;
--border: #e5e7eb;
--radius: 14px;
}
html, body { height: 100%; }
body {
margin: 0;
font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, sans-serif;
color: var(--text);
background: var(--bg);
background-attachment: fixed;
}
.page {
min-height: 100%;
display: grid;
grid-template-rows: auto 1fr auto;
}
.container {
max-width: 900px;
margin: 0 auto;
padding: clamp(16px, 3vw, 28px);
}
.hero {
color: #fff;
text-align: center;
padding: clamp(12px, 2.5vw, 24px) 0;
}
.hero h1 { margin: 0; font-size: clamp(24px, 5vw, 36px); font-weight: 800; letter-spacing: -0.01em; }
.hero p { margin: 8px 0 0; opacity: .95; font-size: clamp(14px, 2.5vw, 18px); }
.grid { display: grid; gap: 24px; grid-template-columns: 1fr; align-items: start; }
@media (min-width: 800px) {
.grid { grid-template-columns: 1fr; max-width: 680px; margin: 0 auto; }
}
.card {
background: var(--card);
border-radius: var(--radius);
box-shadow: 0 10px 30px rgba(0,0,0,0.12);
overflow: hidden;
border: 1px solid var(--border);
width: 100%;
}
.card-header { padding: 20px 24px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; }
.card-header h2 { margin: 0; font-size: 20px; font-weight: 700; }
.card-body { padding: 24px; }
label { display:block; font-weight: 600; margin: 10px 0 6px; }
.input, .textarea, .number {
width: 100%;
border: 2px solid var(--border);
border-radius: 10px;
padding: 12px;
font-size: 15px;
outline: none;
transition: border-color .15s ease;
background: #fff;
box-sizing: border-box;
}
.input:focus, .textarea:focus, .number:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(37,99,235,.12); }
.textarea { resize: vertical; min-height: 320px; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', monospace; line-height: 1.5; }
.hint { color: var(--muted); font-size: 13px; margin-top: 4px; }
.toolbar { display: flex; gap: 12px; align-items: center; justify-content: space-between; margin-top: 12px; flex-wrap: wrap; }
.btn { appearance: none; border: none; cursor: pointer; border-radius: 10px; padding: 14px 20px; font-weight: 700; font-size: 15px; transition: all 0.15s ease; }
.btn-primary { background: var(--primary); color: #fff; width: 100%; }
.btn-primary:hover { background: var(--primary-700); transform: translateY(-1px); }
.btn-outline { background: #fff; color: var(--primary); border: 2px solid var(--primary); }
.btn-outline:hover { background: var(--primary); color: #fff; }
.btn-success { background: var(--success); color: #fff; width: 100%; }
.pill { display:inline-flex; align-items:center; gap:8px; background:#f1f5f9; color:#0f172a; border-radius: 999px; padding: 8px 12px; font-size: 13px; }
.success-box { background: #ecfdf5; border: 1px solid #a7f3d0; color: #065f46; border-radius: 12px; padding: 16px; }
.success-items { display:grid; gap:10px; grid-template-columns: 1fr; }
@media (min-width: 520px) { .success-items { grid-template-columns: 1fr 1fr; } }
.success-item { background:#fff; border:1px dashed #34d399; padding:12px; border-radius:10px; display:flex; flex-direction:column; gap:6px; }
.footer { color: #e5e7eb; text-align:center; font-size: 12px; padding: 20px 10px; }
.sep { height: 10px; }
.badge { font-size: 12px; color:#0f172a; background:#fde68a; padding:4px 8px; border-radius:999px; }
/* Mode Switch Styles */
.mode-switch { margin-bottom: 24px; }
.switch-buttons { display: flex; gap: 4px; background: #f1f5f9; padding: 4px; border-radius: 12px; }
.btn-switch { flex: 1; padding: 12px 16px; border: none; border-radius: 8px; font-weight: 600; font-size: 14px; cursor: pointer; transition: all 0.2s ease; background: transparent; color: var(--muted); }
.btn-switch.active { background: var(--primary); color: white; }
.btn-switch:hover:not(.active) { background: rgba(37,99,235,0.1); color: var(--primary); }
.switch-hint { text-align: center; margin-top: 8px; font-size: 13px; color: var(--muted); }
.loading { opacity: 0.7; pointer-events: none; }
/* Wizard Styles */
.wizard-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 12px; border-bottom: 1px solid var(--border); }
.wizard-header h3 { margin: 0; font-size: 18px; font-weight: 700; }
.questions-counter { background: #f1f5f9; padding: 6px 12px; border-radius: 20px; font-size: 13px; font-weight: 600; color: var(--primary); }
.questions-list { margin-bottom: 20px; }
.add-question-section { text-align: center; margin: 20px 0; }
.question-card { background: #f8fafc; border: 1px solid var(--border); border-radius: 12px; padding: 20px; margin-bottom: 16px; position: relative; }
.question-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.question-number { font-weight: 700; color: var(--primary); font-size: 16px; }
.btn-remove { background: #fee2e2; color: #dc2626; border: none; border-radius: 6px; padding: 4px 8px; cursor: pointer; font-size: 12px; }
.btn-remove:hover { background: #fecaca; }
.choices-grid { display: grid; gap: 12px; margin: 16px 0; }
.choice-item { display: grid; grid-template-columns: auto 1fr auto; gap: 12px; align-items: center; background: white; padding: 12px; border-radius: 8px; border: 1px solid var(--border); }
.choice-radio { margin: 0; }
.choice-text { margin: 0 !important; }
.correct-label { font-size: 12px; color: var(--success); font-weight: 600; opacity: 0; transition: opacity 0.2s ease; }
.choice-item:has(.choice-radio:checked) .correct-label { opacity: 1; }
.choice-item:has(.choice-radio:checked) { border-color: var(--success); background: #ecfdf5; }
@media (max-width: 640px) {
.wizard-header { flex-direction: column; gap: 8px; align-items: flex-start; }
.choice-item { grid-template-columns: auto 1fr; }
.choice-item .correct-label { grid-column: 2; justify-self: end; }
}
</style>
</head>
<body>
<div class="page">
<div class="container hero">
<span class="badge">🧪 Auto-correcteur</span>
<h1>Studio QCM pour l’éducation</h1>
<p>Créez votre QCM en collant un JSON. Imprimez des copies anonymes avec QR code, prêtes pour la correction.</p>
</div>
<div class="container grid">
<div id="create-section" class="card">
<div class="card-header">
<div>📘</div>
<h2>1. Créer le QCM</h2>
</div>
<div class="card-body">
<!-- Mode Switch -->
<div class="mode-switch">
<div class="switch-buttons">
<button type="button" id="switch-wizard" class="btn-switch active">🧙♂️ Assistant</button>
<button type="button" id="switch-json" class="btn-switch">📝 JSON</button>
<button type="button" id="switch-ai" class="btn-switch">🤖 IA</button>
</div>
<div class="switch-hint">
<span id="switch-hint-text">Créez vos questions étape par étape avec l'assistant guidé</span>
</div>
</div>
<form id="qcm-form" novalidate>
<label for="qcm-title">Titre du QCM</label>
<input type="text" id="qcm-title" class="input" placeholder="Ex: Révision – Océans et continents" required>
<!-- Vue Wizard -->
<div id="wizard-view">
<div class="wizard-header">
<h3>🎯 Créer vos questions</h3>
<div class="questions-counter">
<span id="questions-count">0</span> question(s) créée(s)
</div>
</div>
<div id="questions-list" class="questions-list"></div>
<div class="add-question-section">
<button type="button" id="add-question-btn" class="btn btn-outline">
➕ Ajouter une question
</button>
</div>
<!-- Template pour nouvelle question -->
<div id="question-template" style="display: none;">
<div class="question-card">
<div class="question-header">
<span class="question-number">Question #</span>
<button type="button" class="btn-remove" title="Supprimer cette question">✖️</button>
</div>
<div class="question-content">
<label>Énoncé de la question</label>
<textarea class="input question-text" placeholder="Ex: Quel est le plus grand océan de la Terre ?" rows="2"></textarea>
<label>Choix de réponses (4 obligatoires)</label>
<div class="choices-grid">
<div class="choice-item">
<input type="radio" name="correct-answer-{ID}" value="0" class="choice-radio">
<input type="text" class="input choice-text" placeholder="Choix A">
<label class="correct-label">✓ Bonne réponse</label>
</div>
<div class="choice-item">
<input type="radio" name="correct-answer-{ID}" value="1" class="choice-radio">
<input type="text" class="input choice-text" placeholder="Choix B">
<label class="correct-label">✓ Bonne réponse</label>
</div>
<div class="choice-item">
<input type="radio" name="correct-answer-{ID}" value="2" class="choice-radio">
<input type="text" class="input choice-text" placeholder="Choix C">
<label class="correct-label">✓ Bonne réponse</label>
</div>
<div class="choice-item">
<input type="radio" name="correct-answer-{ID}" value="3" class="choice-radio">
<input type="text" class="input choice-text" placeholder="Choix D">
<label class="correct-label">✓ Bonne réponse</label>
</div>
</div>
<label>Explication (optionnel mais conseillé)</label>
<textarea class="input explanation-text" placeholder="Ex: Le Pacifique couvre environ 165 millions de km²" rows="2"></textarea>
</div>
</div>
</div>
</div>
<!-- Vue IA (masquée par défaut) -->
<div id="ai-view" style="display: none;">
<div class="wizard-header">
<h3>🤖 Génération par IA</h3>
<div class="pill">Jusqu'à 20 questions</div>
</div>
<label for="ai-subject">Sujet ou contenu de cours</label>
<textarea id="ai-subject" class="textarea" placeholder="Ex: La tectonique des plaques et les risques sismiques..." rows="6"></textarea>
<div class="toolbar">
<div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
<label for="ai-count" style="margin:0;">Nombre de questions</label>
<input type="number" id="ai-count" class="number" min="1" max="20" value="10" style="width:110px;">
</div>
<button type="button" id="ai-generate" class="btn btn-outline">⚡ Générer avec l'IA</button>
</div>
<div id="ai-status" class="hint" style="margin-top:8px;"></div>
</div>
<!-- Vue JSON (masquée par défaut) -->
<div id="json-view" style="display: none;">
<label for="questions-json">Questions (format JSON)</label>
<textarea id="questions-json" class="textarea" placeholder='[
{
"question": "Quel est le plus grand océan de la Terre ?",
"choices": [
"Océan Atlantique",
"Océan Pacifique",
"Océan Indien",
"Océan Arctique"
],
"correct_answer": "Océan Pacifique",
"explanation": "Le Pacifique couvre environ 165 millions de km²"
}
]'></textarea>
<div class="toolbar">
<span class="hint">Attendu: tableau d’objets avec 4 choix, une bonne réponse et une explication.</span>
<button type="button" id="fill-sample" class="btn btn-outline">Remplir un exemple</button>
</div>
</div>
<div class="sep"></div>
<button type="submit" class="btn btn-primary">Créer le QCM</button>
</form>
</div>
</div>
<div class="card" id="qcm-created" style="display:none;">
<div class="card-header">
<div>🎉</div>
<h2>QCM créé avec succès</h2>
</div>
<div class="card-body">
<div class="success-box" role="status">
<div style="font-weight:700; margin-bottom:12px; text-align:center;">Vos identifiants</div>
<div class="success-items">
<div class="success-item">
<div style="font-size:12px; color:var(--muted); text-align:center;">ID du QCM</div>
<div style="display:flex; align-items:center; justify-content:center; gap:8px;">
<span id="created-qcm-id" style="font-family:monospace; font-weight:700;"></span>
</div>
</div>
<div class="success-item">
<div style="font-size:12px; color:var(--muted); text-align:center;">Code Professeur</div>
<div style="display:flex; align-items:center; justify-content:center; gap:8px; flex-wrap:wrap;">
<span id="created-prof-code" style="font-family:monospace; font-weight:700;"></span>
<button id="copy-prof-code" type="button" class="btn btn-outline" style="width:auto; padding:6px 12px; font-size:12px;" title="Copier">Copier</button>
</div>
</div>
</div>
</div>
<div style="height:20px;"></div>
<div class="card" style="border:1px dashed var(--border)">
<div class="card-header">
<div>🖨️</div>
<h2>2. Imprimer les copies</h2>
</div>
<div class="card-body" style="text-align:center;">
<form id="print-form">
<input type="hidden" id="print-qcm-id">
<label for="student-count" style="text-align:center;">Nombre d'élèves</label>
<input type="number" id="student-count" class="number" min="1" max="50" value="1" required style="max-width:200px; margin:0 auto;">
<div class="sep"></div>
<button type="submit" class="btn btn-success">🖨️ Générer et Imprimer</button>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="footer container">© <?php echo date('Y'); ?> – QCM Auto-correcteur pour l’éducation</div>
</div>
<script>
// Variables globales pour le wizard
let questionCounter = 0;
let currentMode = 'wizard'; // 'wizard' ou 'json'
// Mode Switch Logic
function switchMode(mode, autoSync = true) {
const wizardView = document.getElementById('wizard-view');
const jsonView = document.getElementById('json-view');
const aiView = document.getElementById('ai-view');
const switchWizard = document.getElementById('switch-wizard');
const switchJson = document.getElementById('switch-json');
const switchAi = document.getElementById('switch-ai');
const hintText = document.getElementById('switch-hint-text');
currentMode = mode;
if (mode === 'wizard') {
wizardView.style.display = 'block';
jsonView.style.display = 'none';
aiView.style.display = 'none';
switchWizard.classList.add('active');
switchJson.classList.remove('active');
switchAi.classList.remove('active');
hintText.textContent = 'Créez vos questions étape par étape avec l\'assistant guidé';
// Synchroniser le JSON vers le wizard si possible (sauf si on l'évite explicitement)
if (autoSync) {
syncJsonToWizard();
}
} else if (mode === 'json') {
wizardView.style.display = 'none';
jsonView.style.display = 'block';
aiView.style.display = 'none';
switchWizard.classList.remove('active');
switchJson.classList.add('active');
switchAi.classList.remove('active');
hintText.textContent = 'Éditez directement le JSON des questions';
// IMPORTANT: ne pas synchroniser automatiquement Wizard -> JSON ici
// pour éviter d'écraser le JSON avec des cartes incomplètes du wizard
} else if (mode === 'ai') {
wizardView.style.display = 'none';
jsonView.style.display = 'none';
aiView.style.display = 'block';
switchWizard.classList.remove('active');
switchJson.classList.remove('active');
switchAi.classList.add('active');
hintText.textContent = 'Décrivez votre sujet, l\'IA génère jusqu\'à 20 questions';
}
}
// Ajouter une nouvelle question dans le wizard
function addQuestion() {
questionCounter++;
const template = document.getElementById('question-template');
const questionsList = document.getElementById('questions-list');
// Cloner le template
const newQuestion = template.cloneNode(true);
newQuestion.style.display = 'block';
newQuestion.id = `question-${questionCounter}`;
// Mettre à jour le numéro de question
const questionNumber = newQuestion.querySelector('.question-number');
questionNumber.textContent = `Question ${questionCounter}`;
// Vider tous les champs après clonage pour éviter la duplication de contenu
const textInputs = newQuestion.querySelectorAll('input[type="text"], textarea');
textInputs.forEach(input => {
input.value = '';
});
// Décocher tous les radio buttons
const radios = newQuestion.querySelectorAll('input[type="radio"]');
radios.forEach(radio => {
radio.checked = false;
radio.name = `correct-answer-${questionCounter}`;
});
// Ajouter l'event listener pour supprimer
const removeBtn = newQuestion.querySelector('.btn-remove');
removeBtn.addEventListener('click', () => removeQuestion(newQuestion.id));
// Ajouter des event listeners pour la synchronisation
const inputs = newQuestion.querySelectorAll('input, textarea');
inputs.forEach(input => {
input.addEventListener('input', syncWizardToJson);
input.addEventListener('change', syncWizardToJson);
});
questionsList.appendChild(newQuestion);
updateQuestionsCount();
// Ne pas synchroniser si on est en train de remplir depuis l'IA
if (!window.syncingFromAI) {
syncWizardToJson();
}
return newQuestion;
}
// Supprimer une question
function removeQuestion(questionId) {
const questionElement = document.getElementById(questionId);
if (questionElement) {
questionElement.remove();
updateQuestionsCount();
syncWizardToJson();
}
}
// Mettre à jour le compteur de questions
function updateQuestionsCount() {
const count = document.querySelectorAll('#questions-list .question-card').length;
document.getElementById('questions-count').textContent = count;
}
// Synchroniser le wizard vers JSON
function syncWizardToJson() {
if (currentMode !== 'wizard') return;
// Ne pas synchroniser pendant qu'on remplit depuis l'IA ou qu'on reconstruit depuis JSON
if (window.syncingFromAI || window.rebuildingFromJson) return;
const questions = [];
const questionCards = document.querySelectorAll('#questions-list .question-card');
questionCards.forEach(card => {
const questionText = card.querySelector('.question-text').value.trim();
const choices = Array.from(card.querySelectorAll('.choice-text')).map(input => input.value.trim());
const explanationText = card.querySelector('.explanation-text').value.trim();
// Trouver la bonne réponse
const selectedRadio = card.querySelector('input[type="radio"]:checked');
const correctAnswer = selectedRadio ? choices[parseInt(selectedRadio.value)] : '';
// Ne sauvegarder que si la question a du contenu
if (questionText && choices.every(c => c) && correctAnswer) {
questions.push({
question: questionText,
choices: choices,
correct_answer: correctAnswer,
explanation: explanationText || ""
});
}
});
// Mettre à jour le textarea JSON
const jsonTextarea = document.getElementById('questions-json');
jsonTextarea.value = JSON.stringify(questions, null, 2);
}
// Synchroniser JSON vers wizard
function syncJsonToWizard() {
try {
const jsonText = document.getElementById('questions-json').value.trim();
if (!jsonText) return;
const questions = JSON.parse(jsonText);
if (!Array.isArray(questions)) return;
// Empêcher toute synchro inverse pendant la reconstruction
window.rebuildingFromJson = true;
// Vider le wizard
document.getElementById('questions-list').innerHTML = '';
questionCounter = 0;
// Recréer les questions dans le wizard
questions.forEach((q, index) => {
if (q.question && Array.isArray(q.choices) && q.choices.length === 4 && q.correct_answer) {
const wrapper = addQuestion();
const lastCard = wrapper.querySelector('.question-card');
// Remplir les champs
lastCard.querySelector('.question-text').value = q.question;
const choiceInputs = lastCard.querySelectorAll('.choice-text');
choiceInputs.forEach((input, i) => {
input.value = q.choices[i] || '';
});
// Sélectionner la bonne réponse
const correctIndex = q.choices.indexOf(q.correct_answer);
if (correctIndex !== -1) {
const radio = lastCard.querySelector(`input[value="${correctIndex}"]`);
if (radio) radio.checked = true;
}
// Remplir l'explication
if (q.explanation) {
lastCard.querySelector('.explanation-text').value = q.explanation;
}
}
});
updateQuestionsCount();
} catch (e) {
// Erreur JSON silencieuse - on n'affiche rien pour ne pas gêner l'utilisateur
} finally {
window.rebuildingFromJson = false;
}
}
// Initialisation
document.addEventListener('DOMContentLoaded', function() {
// Event listeners pour le switch de mode
document.getElementById('switch-wizard').addEventListener('click', () => switchMode('wizard'));
document.getElementById('switch-json').addEventListener('click', () => switchMode('json'));
document.getElementById('switch-ai').addEventListener('click', () => switchMode('ai'));
// Event listener pour ajouter une question
document.getElementById('add-question-btn').addEventListener('click', addQuestion);
// Ajouter une première question par défaut
addQuestion();
// Event listener pour synchroniser JSON vers wizard
document.getElementById('questions-json').addEventListener('input', () => {
if (currentMode === 'json') {
// Synchronisation avec delay pour éviter trop d'appels
clearTimeout(window.jsonSyncTimeout);
window.jsonSyncTimeout = setTimeout(syncJsonToWizard, 500);
}
});
});
// --- IA: Appel API et intégration ---
async function ASK(systemPrompt, userPrompt) {
try {
const response = await fetch('API.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
body: new URLSearchParams({ system: systemPrompt, prompt: userPrompt })
});
if (!response.ok) {
const text = await response.text();
throw new Error('HTTP ' + response.status + ' ' + text);
}
const raw = await response.text();
// Parser la réponse JSON
let data;
try {
data = JSON.parse(raw);
} catch (e) {
throw new Error('Réponse serveur invalide: ' + raw.substring(0, 100));
}
// Extraire la réponse
let content = '';
if (data?.response) {
// Si API renvoie {"response": "..."} avec la réponse
try {
const APIResponse = JSON.parse(data.response);
content = APIResponse?.choices?.[0]?.message?.content || '';
} catch (e) {
// Si data.response est directement du texte
content = data.response;
}
} else if (data?.choices?.[0]?.message?.content) {
// Si API renvoie directement la structure
content = data.choices[0].message.content;
} else {
throw new Error('Structure de réponse inattendue');
}
if (!content) {
throw new Error('Contenu vide dans la réponse IA');
}
// Nettoyer d’éventuelles fences ```json ... ``` et extraire proprement le tableau JSON
function stripFences(text) {
return text
.replace(/```json\s*/gi, '')
.replace(/```/g, '')
.trim();
}
function extractJsonArray(text) {
// Si le texte est déjà un JSON valide, le retourner
try {
const parsed = JSON.parse(text);
return parsed;
} catch(_){}
// Rechercher le premier '[' puis trouver le crochet fermant correspondant
const start = text.indexOf('[');
if (start === -1) return null;
let inString = false;
let escape = false;
let depth = 0;
for (let i = start; i < text.length; i++) {
const ch = text[i];
if (escape) {
escape = false;
continue;
}
if (ch === '\\') { // backslash
escape = true;
continue;
}
if (ch === '"') {
inString = !inString;
continue;
}
if (!inString) {
if (ch === '[') depth++;
else if (ch === ']') {
depth--;
if (depth === 0) {
const candidate = text.slice(start, i + 1);
try {
return JSON.parse(candidate);
} catch (e) {
// continuer pour tenter un autre bloc (peu probable)
}
}
}
}
}
return null;
}
const cleaned = stripFences(content);
const parsed = extractJsonArray(cleaned);
if (!parsed) {
throw new Error('Aucun JSON exploitable trouvé. Aperçu: ' + cleaned.substring(0, 200));
}
return parsed;
} catch (err) {
console.error('ASK error:', err);
throw err;
}
}
async function generateWithAI() {
const subject = (document.getElementById('ai-subject').value || '').trim();
const count = Math.min(20, Math.max(1, parseInt(document.getElementById('ai-count').value || '10')));
const status = document.getElementById('ai-status');
const btn = document.getElementById('ai-generate');
if (!subject) { alert('Veuillez saisir un sujet ou du contenu.'); return; }
btn.classList.add('loading'); btn.disabled = true; status.textContent = 'Génération en cours...';
const jsonExample = `[
{
"question": "Quel est le plus grand océan de la Terre ?",
"choices": ["Océan Atlantique","Océan Pacifique","Océan Indien","Océan Arctique"],
"correct_answer": "Océan Pacifique",
"explanation": "Brève explication (optionnelle)"
}
]`;
const systemPrompt = `Tu génères un QCM en JSON strict selon ce modèle ${jsonExample}. Donne entre 1 et 20 questions maximum, avec exactement 4 choix, un champ correct_answer présent dans choices, et si possible une explication courte.`;
const userPrompt = `Sujet: ${subject}. Génère ${count} questions. Réponds UNIQUEMENT par un JSON pur (un tableau), sans texte autour, sans balises ni \`\`\`.`;
try {
const result = await ASK(systemPrompt, userPrompt);
if (!Array.isArray(result) || result.length === 0) throw new Error('JSON vide');
// Tronquer à count si besoin
const trimmed = result.slice(0, count);
// Écrire dans JSON view
const jsonTextarea = document.getElementById('questions-json');
if (!jsonTextarea) throw new Error('Textarea questions-json introuvable');
jsonTextarea.value = JSON.stringify(trimmed, null, 2);
// D'abord basculer vers wizard pour que les éléments soient visibles
// On passe false pour éviter la synchronisation automatique qui viderait le JSON
switchMode('wizard', false);
// Puis synchroniser après un délai plus long pour éviter les conflits
setTimeout(() => {
// Désactiver temporairement les event listeners pendant le remplissage
window.syncingFromAI = true;
syncJsonToWizard();
// Réactiver après un petit délai
setTimeout(() => {
window.syncingFromAI = false;
}, 200);
}, 300);
status.textContent = `✅ ${trimmed.length} question(s) générée(s). Vous pouvez éditer avant de créer le QCM.`;
} catch (e) {
status.textContent = '❌ Échec de génération: ' + e.message;
alert('Erreur IA: ' + e.message);
} finally {
btn.classList.remove('loading'); btn.disabled = false;
}
}
// Wire AI button
document.addEventListener('DOMContentLoaded', function() {
const aiBtn = document.getElementById('ai-generate');
if (aiBtn) aiBtn.addEventListener('click', generateWithAI);
});