<?php
// get_attempted_quizzes.php

header('Content-Type: application/json');
require_once 'db.php'; // Database connection file

// Check if userId is provided
if (isset($_GET['userId'])) {
    $userId = $_GET['userId'];

    try {
        // Get attempted quizzes by user
        $stmt = $pdo->prepare("
            SELECT uq.topic_id, t.name AS topic_name, uq.score, uq.total_questions, uq.attempt_time
            FROM user_quizzes uq
            JOIN topics t ON uq.topic_id = t.id
            WHERE uq.user_id = :userId
             ORDER BY uq.attempt_time DESC
        ");
        $stmt->execute([':userId' => $userId]);
        $quizzes = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Return the data as JSON
        echo json_encode(['attempted_quizzes' => $quizzes]);

    } catch (PDOException $e) {
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['error' => 'Missing parameters']);
}
?>
