Update api/answer.php

This commit is contained in:
2026-06-15 12:36:33 +02:00
parent 64b298bce0
commit 4d21fadd73
+27 -32
View File
@@ -12,13 +12,10 @@ header('Content-Type: application/json; charset=utf-8');
$user = $_SESSION['user'];
$inputRaw = file_get_contents('php://input');
$input = json_decode($inputRaw, true);
$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input)) {
echo json_encode([
'error' => 'invalid_json'
]);
echo json_encode(['error' => 'invalid_json']);
exit;
}
@@ -31,46 +28,49 @@ $file = listPath($user, $lang, $list);
$data = JsonDB::read($file);
if (!isset($data['words']) || !is_array($data['words'])) {
echo json_encode([
'error' => 'list_not_found'
]);
echo json_encode(['error' => 'list_not_found']);
exit;
}
$correct = false;
$updated = false;
$updatedWord = null;
foreach ($data['words'] as &$word) {
foreach ($data['words'] as $i => $word) {
if ((int)$word['id'] === $wordId) {
// init stats veilig
if (!isset($word['correct'])) $word['correct'] = 0;
if (!isset($word['wrong'])) $word['wrong'] = 0;
// init stats
if (!isset($data['words'][$i]['correct'])) {
$data['words'][$i]['correct'] = 0;
}
// normalize compare
$expected = strtolower(trim($word['answer']));
if (!isset($data['words'][$i]['wrong'])) {
$data['words'][$i]['wrong'] = 0;
}
// normalize
$expected = strtolower(trim($data['words'][$i]['answer']));
$given = strtolower(trim($userAnswer));
$correct = ($expected === $given);
// update stats
if ($correct) {
$word['correct']++;
$data['words'][$i]['correct']++;
} else {
$word['wrong']++;
$data['words'][$i]['wrong']++;
}
// SRS update (nextReview + interval)
updateWordStats($word, $correct);
// SRS update (nextReview etc.)
updateWordStats($data['words'][$i], $correct);
$updatedWord = $data['words'][$i];
$updated = true;
break;
}
}
// als woord niet gevonden is
if (!$updated) {
if ($updatedWord === null) {
echo json_encode([
'error' => 'word_not_found',
'wordId' => $wordId
@@ -78,24 +78,19 @@ if (!$updated) {
exit;
}
// write back
// save JSON
$ok = JsonDB::write($file, $data);
if (!$ok) {
echo json_encode([
'error' => 'write_failed'
]);
echo json_encode(['error' => 'write_failed']);
exit;
}
echo json_encode([
'correct' => $correct,
'stats' => [
'wordId' => $wordId,
'correct' => $correct ? 1 : 0
],
'debug' => [
'updatedCorrect' => $data['words'][$i]['correct'] ?? null,
'updatedWrong' => $data['words'][$i]['wrong'] ?? null
'wordId' => $wordId,
'updatedCorrect' => $updatedWord['correct'] ?? null,
'updatedWrong' => $updatedWord['wrong'] ?? null
]
]);