<?php
include 'db.php';

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $user_id = $_GET['user_id'];

    // Fetch the category for the user
    $stmt = $pdo->prepare("SELECT category_id FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();

    if ($user) {
        $category_id = $user['category_id'];

        // Fetch the latest topic for the category
        $stmt = $pdo->prepare("SELECT * FROM topics WHERE category_id = ? ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$category_id]);
        $topic = $stmt->fetch();

        if ($topic) {
            $topic_id = $topic['id'];
            $topic_name = $topic['name']; // Assuming 'name' column exists in topics

            // Fetch questions for the topic
            $stmt = $pdo->prepare("SELECT * FROM questions WHERE topic_id = ?");
            $stmt->execute([$topic_id]);
            $questions = $stmt->fetchAll();

            $data = [];

            foreach ($questions as $question) {
                $question_id = $question['id'];

                // Fetch options for each question
                $stmt = $pdo->prepare("SELECT * FROM options WHERE question_id = ?");
                $stmt->execute([$question_id]);
                $options = $stmt->fetchAll();

                $data[] = [
                    'question_id' => $question['id'],
                    'question_text' => $question['question_text'],
                    'options' => $options
                ];
            }

            echo json_encode([
                'status' => 'success',
                'topic_name' => $topic_name,
                'questions' => $data
            ]);
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => 'No topics found for this category.'
            ]);
        }
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'User not found.'
        ]);
    }
}
?>
