100 lines
2.2 KiB
PHP
100 lines
2.2 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/../includes/config.php';
|
|
require_once __DIR__ . '/../includes/functions.php';
|
|
require_once __DIR__ . '/../includes/jsondb.php';
|
|
require_once __DIR__ . '/../includes/srs.php';
|
|
require_once __DIR__ . '/../includes/auth.php';
|
|
|
|
requireLogin();
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
$user = $_SESSION['user'];
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (!is_array($input)) {
|
|
echo json_encode(['error' => 'invalid_json']);
|
|
exit;
|
|
}
|
|
|
|
$lang = $input['lang'] ?? '';
|
|
$list = $input['list'] ?? '';
|
|
$wordId = (int)($input['wordId'] ?? 0);
|
|
$userAnswer = trim($input['answer'] ?? '');
|
|
|
|
$file = listPath($user, $lang, $list);
|
|
$data = JsonDB::read($file);
|
|
|
|
if (!isset($data['words']) || !is_array($data['words'])) {
|
|
echo json_encode(['error' => 'list_not_found']);
|
|
exit;
|
|
}
|
|
|
|
$correct = false;
|
|
$updatedWord = null;
|
|
|
|
foreach ($data['words'] as $i => $word) {
|
|
|
|
if ((int)$word['id'] === $wordId) {
|
|
|
|
// init stats
|
|
if (!isset($data['words'][$i]['correct'])) {
|
|
$data['words'][$i]['correct'] = 0;
|
|
}
|
|
|
|
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) {
|
|
$data['words'][$i]['correct']++;
|
|
} else {
|
|
$data['words'][$i]['wrong']++;
|
|
}
|
|
|
|
// SRS update (nextReview etc.)
|
|
updateWordStats($data['words'][$i], $correct);
|
|
|
|
$updatedWord = $data['words'][$i];
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
if ($updatedWord === null) {
|
|
echo json_encode([
|
|
'error' => 'word_not_found',
|
|
'wordId' => $wordId
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
// save JSON
|
|
$ok = JsonDB::write($file, $data);
|
|
|
|
if (!$ok) {
|
|
echo json_encode(['error' => 'write_failed']);
|
|
exit;
|
|
}
|
|
|
|
echo json_encode([
|
|
'correct' => $correct,
|
|
'debug' => [
|
|
'wordId' => $wordId,
|
|
'updatedCorrect' => $updatedWord['correct'] ?? null,
|
|
'updatedWrong' => $updatedWord['wrong'] ?? null
|
|
],
|
|
'stats' => [
|
|
'wordId' => $wordId,
|
|
'correct' => $correct ? 1 : 0
|
|
],
|
|
]); |