From 4d21fadd7324f9adb0a1757b6c1f9ced36e40697 Mon Sep 17 00:00:00 2001 From: Thomas de Roo <2+thomas@noreply.localhost> Date: Mon, 15 Jun 2026 12:36:33 +0200 Subject: [PATCH] Update api/answer.php --- api/answer.php | 59 +++++++++++++++++++++++--------------------------- 1 file changed, 27 insertions(+), 32 deletions(-) diff --git a/api/answer.php b/api/answer.php index b5698a1..c937716 100644 --- a/api/answer.php +++ b/api/answer.php @@ -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 ] ]); \ No newline at end of file