<?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 total quizzes in the category
    $stmtTotal = $pdo->prepare("
        SELECT COUNT(*) AS total_quizzes 
        FROM topics 
        WHERE category_id = :categoryId AND status = 1
    ");
    $stmtTotal->execute([':categoryId' => $categoryId]);
    $totalQuizzes = $stmtTotal->fetchColumn() ?: 0;

    // Count attempted quizzes
    $stmtAttempted = $pdo->prepare("
        SELECT COUNT(DISTINCT topic_id) AS attempted_quizzes 
        FROM user_quizzes uq
        JOIN topics t ON uq.topic_id = t.id
        WHERE uq.user_id = :userId AND t.category_id = :categoryId
    ");
    $stmtAttempted->execute([':userId' => $userId, ':categoryId' => $categoryId]);
    $attemptedQuizzes = $stmtAttempted->fetchColumn() ?: 0;

    // Fetch available quizzes, including retakeable ones (score < 80% and allow_retakes = 1)
    $stmtAvailable = $pdo->prepare("
        SELECT 
            t.id, 
            t.name,
            t.allow_retakes,
            uq.score,
            uq.total_questions
        FROM topics t
        LEFT JOIN user_quizzes uq ON t.id = uq.topic_id AND uq.user_id = :userId
        WHERE t.category_id = :categoryId 
        AND t.status = 1
        AND (
            uq.topic_id IS NULL 
            OR (uq.score / uq.total_questions * 100 < 80 AND t.allow_retakes = 1)
        )
    ");
    $stmtAvailable->execute([':categoryId' => $categoryId, ':userId' => $userId]);
    $availableQuizzes = $stmtAvailable->fetchAll(PDO::FETCH_ASSOC);

    // Process available quizzes to add 'rt' prefix for retakeable ones
    $processedQuizzes = array_map(function ($quiz) {
        $isRetake = !is_null($quiz['score']) && $quiz['allow_retakes'] == 1;
        return [
            'id' => $quiz['id'],
            'name' => $isRetake ? "rt{$quiz['name']}" : $quiz['name']
        ];
    }, $availableQuizzes);

    // Count available quizzes
    $availableQuizzesCount = count($availableQuizzes);

    // Return JSON response
    echo json_encode([
        'attempted_quizzes' => (int) $attemptedQuizzes,
        'total_quizzes' => (int) $totalQuizzes,
        'available_quizzes_count' => (int) $availableQuizzesCount,
        'available_quizzes' => $processedQuizzes
    ]);

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