<?php
include 'db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $user_id = $_POST['user_id'];
    $topic_id = $_POST['topic_id'];
    $answers = json_decode($_POST['answers'], true); // Expecting answers in JSON format

    // Check if the user has already attempted this quiz
    $stmt = $pdo->prepare("SELECT score FROM user_quizzes WHERE user_id = ? AND topic_id = ?");
    $stmt->execute([$user_id, $topic_id]);
    $existingAttempt = $stmt->fetch();

    if ($existingAttempt) {
        // If attempt exists, return the previous score
        echo json_encode([
            'status' => 'exists',
            'score' => $existingAttempt['score'],
            'message' => 'Quiz already attempted. Here is your score.'
        ]);
    } else {
        $score = 0;
        $total_questions = count($answers);

        // Start a transaction to ensure atomicity
        $pdo->beginTransaction();

        try {
            foreach ($answers as $answer) {
                $question_id = $answer['question_id'];
                $selected_option_id = $answer['selected_option_id'];

                // Check if the selected option is correct
                $stmt = $pdo->prepare("SELECT is_correct FROM options WHERE id = ?");
                $stmt->execute([$selected_option_id]);
                $option = $stmt->fetch();

                if ($option && $option['is_correct']) {
                    $score++;
                }
            }

            // Save user's quiz attempt
            $stmt = $pdo->prepare("INSERT INTO user_quizzes (user_id, topic_id, score) VALUES (?, ?, ?)");
            $stmt->execute([$user_id, $topic_id, $score]);

            // Get the last inserted user_quiz_id
            $user_quiz_id = $pdo->lastInsertId();

            // Insert each answer into user_answers
            foreach ($answers as $answer) {
                $question_id = $answer['question_id'];
                $selected_option_id = $answer['selected_option_id'];

                $stmt = $pdo->prepare("INSERT INTO user_answers (user_quiz_id, question_id, selected_option_id) VALUES (?, ?, ?)");
                $stmt->execute([$user_quiz_id, $question_id, $selected_option_id]);
            }

            // Commit the transaction
            $pdo->commit();

            echo json_encode([
                'status' => 'success',
                'score' => $score,
                'total_questions' => $total_questions,
                'message' => 'Quiz submitted successfully!'
            ]);
        } catch (Exception $e) {
            // Rollback the transaction if an error occurs
            $pdo->rollBack();
            echo json_encode([
                'status' => 'error',
                'message' => 'Failed to submit quiz. Please try again.'
            ]);
        }
    }
}
?>
