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

// Check if userId and categoryId are set
if (!isset($_GET['userId']) || !isset($_GET['categoryId'])) {
    echo json_encode(['error' => 'Missing parameters']);
    exit;
}

$userId = (int) $_GET['userId'];
$categoryId = (int) $_GET['categoryId'];

try {
    // Count attempted quizzes
    $stmtAttempted = $pdo->prepare("
        SELECT COUNT(DISTINCT topic_id) AS attempted_quizzes 
        FROM user_quizzes 
        WHERE user_id = :userId
    ");
    $stmtAttempted->execute([':userId' => $userId]);
    $attemptedQuizzes = $stmtAttempted->fetchColumn() ?: 0;

    // Fetch available quizzes (topics) for the category
    $stmtAvailable = $pdo->prepare("
        SELECT id, name 
        FROM topics 
        WHERE category_id = :categoryId 
        AND status = 1
        AND id NOT IN (SELECT topic_id FROM user_quizzes WHERE user_id = :userId)
    ");
    $stmtAvailable->execute([':categoryId' => $categoryId, ':userId' => $userId]);
    $availableQuizzes = $stmtAvailable->fetchAll(PDO::FETCH_ASSOC);

    // Return JSON response
    echo json_encode([
        'attempted_quizzes' => (int) $attemptedQuizzes,
        'total_quizzes' => count($availableQuizzes),
        'available_quizzes' => $availableQuizzes // List of available quizzes
    ]);

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