<?php
include 'db.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate the user ID, topic ID, and answers are present
    if (!isset($_POST['user_id'], $_POST['topic_id'], $_POST['answers'])) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Invalid input. Missing user ID, topic ID, or answers.'
        ]);
        exit;
    }

    $user_id = $_POST['user_id'];
    $topic_id = $_POST['topic_id'];
    $answers = json_decode($_POST['answers'], true);

    if (!$answers || !is_array($answers)) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Invalid answers format. Expected a valid JSON array.'
        ]);
        exit;
    }

    try {
        // Check if the user has already attempted this quiz
        $stmt = $pdo->prepare("SELECT score, total_questions 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 and total questions
            echo json_encode([
                'status' => 'exists',
                'score' => $existingAttempt['score'],
                'total_questions' => $existingAttempt['total_questions'],
                'message' => 'Quiz already attempted. Here is your score.'
            ]);
            exit;
        }

        // Initialize score and total questions
        $score = 0;
        $total_questions = count($answers);

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

        // Loop through answers and calculate the score
        foreach ($answers as $answer) {
            if (!isset($answer['question_id'], $answer['selected_option_id'])) {
                throw new Exception('Invalid answer format.');
            }

            $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 with score and total questions
        $stmt = $pdo->prepare("INSERT INTO user_quizzes (user_id, topic_id, score, total_questions) VALUES (?, ?, ?, ?)");
        $stmt->execute([$user_id, $topic_id, $score, $total_questions]);

        // 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();

        // Return success message
        echo json_encode([
            'status' => 'success',
            'score' => $score,
            'total_questions' => $total_questions,
            'message' => 'Quiz submitted successfully!'
        ]);
    } catch (Exception $e) {
        // Rollback the transaction in case of an error
        $pdo->rollBack();

        // Return error message
        echo json_encode([
            'status' => 'error',
            'message' => 'Failed to submit quiz: ' . $e->getMessage()
        ]);
    }
}
?>
