<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
include 'db.php';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : null;
$categoryId = isset($_GET['category_id']) ? (int)$_GET['category_id'] : null;

if (!$userId || !$categoryId) {
    echo json_encode(['status' => 'error', 'message' => 'Missing user_id or category_id']);
    exit;
}

$query = "
    SELECT DISTINCT s.id, s.name
    FROM sets s
    JOIN topics t ON s.id = t.set_id
    JOIN user_quizzes uq ON t.id = uq.topic_id
    WHERE uq.user_id = :user_id AND t.category_id = :category_id
    ORDER BY s.id ASC
";

try {
    $stmt = $pdo->prepare($query);
    $stmt->execute(['user_id' => $userId, 'category_id' => $categoryId]);
    $sets = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['status' => 'success', 'sets' => $sets]);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Query failed: ' . $e->getMessage()]);
}
?>