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

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : null;
    $topic_id = isset($_GET['topic_id']) && $_GET['topic_id'] !== '' ? (int)$_GET['topic_id'] : null;

    if (!$user_id) {
        echo json_encode([
            'status' => 'error',
            'message' => 'User ID is required.'
        ]);
        exit;
    }

    try {
        $retake_status = false; // Initialize retake_status

        // If topic_id is provided, use it; otherwise, fetch based on user's category
        if ($topic_id) {
            // Check if the user has already attempted this topic
            $stmt = $pdo->prepare("
                SELECT score, total_questions 
                FROM user_quizzes 
                WHERE user_id = :user_id AND topic_id = :topic_id
            ");
            $stmt->execute([':user_id' => $user_id, ':topic_id' => $topic_id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($result) {
                $score_percentage = ($result['score'] / $result['total_questions'] * 100);
                if ($score_percentage >= 80) {
                    // Topic attempted with score >= 80%, block access
                    echo json_encode([
                        'status' => 'exists',
                        'score' => (int)$result['score'],
                        'total_questions' => (int)$result['total_questions']
                    ]);
                    exit;
                }
                // Mark as retake if score < 80% and allow_retakes = 1 (checked below)
                $retake_status = true;
            }

            // Fetch topic details including allow_retakes
            $stmt = $pdo->prepare("
                SELECT id, name, allow_retakes 
                FROM topics 
                WHERE id = :topic_id AND status = 1
            ");
            $stmt->execute([':topic_id' => $topic_id]);
            $topic = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$topic) {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Topic not found or inactive.'
                ]);
                exit;
            }

            // Verify retake eligibility if attempted
            if ($retake_status && $topic['allow_retakes'] != 1) {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Retakes are not allowed for this topic.'
                ]);
                exit;
            }

            $topic_id = $topic['id'];
            $topic_name = $topic['name'];
        } else {
            // Fallback: Fetch category for the user
            $stmt = $pdo->prepare("SELECT category_id FROM users WHERE id = :user_id");
            $stmt->execute([':user_id' => $user_id]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user || !$user['category_id']) {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'User not found or no category assigned.'
                ]);
                exit;
            }

            $category_id = $user['category_id'];

            // Fetch the latest active topic for the category that is unattempted or retakeable
            $stmt = $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 = :user_id
                WHERE t.category_id = :category_id 
                AND t.status = 1
                AND (
                    uq.topic_id IS NULL 
                    OR (uq.score / uq.total_questions * 100 < 80 AND t.allow_retakes = 1)
                )
                ORDER BY t.created_at DESC 
                LIMIT 1
            ");
            $stmt->execute([':category_id' => $category_id, ':user_id' => $user_id]);
            $topic = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$topic) {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'No active topics found for this category.'
                ]);
                exit;
            }

            $topic_id = $topic['id'];
            $topic_name = $topic['name'];
            $retake_status = !is_null($topic['score']) && $topic['allow_retakes'] == 1;
        }

        // Fetch questions for the topic
        $stmt = $pdo->prepare("SELECT id, question_text FROM questions WHERE topic_id = :topic_id");
        $stmt->execute([':topic_id' => $topic_id]);
        $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (empty($questions)) {
            echo json_encode([
                'status' => 'error',
                'message' => 'No questions found for this topic.'
            ]);
            exit;
        }

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

            // Fetch options for each question
            $stmt = $pdo->prepare("SELECT id, option_text, is_correct FROM options WHERE question_id = :question_id");
            $stmt->execute([':question_id' => $question_id]);
            $options = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

        echo json_encode([
            'status' => 'success',
            'topic_id' => $topic_id,
            'topic_name' => $topic_name,
            'retake_status' => $retake_status,
            'questions' => $data
        ]);

    } catch (PDOException $e) {
        echo json_encode([
            'status' => 'error',
            'message' => 'Database error: ' . $e->getMessage()
        ]);
    }
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request method.'
    ]);
}
?>