<?php
require_once '../config.php';

// Parse query params
$userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$quizId = isset($_GET['quiz_id']) ? intval($_GET['quiz_id']) : 0;

if ($userId <= 0 || $quizId <= 0) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Valid user_id and quiz_id are required parameters."]);
    exit();
}

try {
    $db = getDBConnection();

    // 1. Verify user exists and is verified
    $stmt = $db->prepare("SELECT id FROM users WHERE id = ? AND is_verified = 1");
    $stmt->execute([$userId]);
    if (!$stmt->fetch()) {
        http_response_code(404);
        echo json_encode(["status" => "error", "message" => "User account not found or unverified."]);
        exit();
    }

    // 2. Verify quiz exists and is active
    $stmt = $db->prepare("SELECT id FROM quizzes WHERE id = ? AND is_active = 1");
    $stmt->execute([$quizId]);
    if (!$stmt->fetch()) {
        http_response_code(404);
        echo json_encode(["status" => "error", "message" => "Requested quiz is not active or does not exist."]);
        exit();
    }

    // 3. Fetch unseen question IDs for this user by difficulty
    // Easy:
    $stmt = $db->prepare("SELECT id FROM quiz_questions WHERE quiz_id = ? AND difficulty = 'easy' AND id NOT IN (SELECT question_id FROM user_question_history WHERE user_id = ?)");
    $stmt->execute([$quizId, $userId]);
    $easyIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

    // Medium:
    $stmt = $db->prepare("SELECT id FROM quiz_questions WHERE quiz_id = ? AND difficulty = 'medium' AND id NOT IN (SELECT question_id FROM user_question_history WHERE user_id = ?)");
    $stmt->execute([$quizId, $userId]);
    $mediumIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

    // Hard:
    $stmt = $db->prepare("SELECT id FROM quiz_questions WHERE quiz_id = ? AND difficulty = 'hard' AND id NOT IN (SELECT question_id FROM user_question_history WHERE user_id = ?)");
    $stmt->execute([$quizId, $userId]);
    $hardIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

    // 4. Self-healing history: reset history if any difficulty doesn't have enough questions remaining
    if (count($easyIds) < 5 || count($mediumIds) < 5 || count($hardIds) < 5) {
        $stmt = $db->prepare("DELETE FROM user_question_history WHERE user_id = ? AND question_id IN (SELECT id FROM quiz_questions WHERE quiz_id = ?)");
        $stmt->execute([$userId, $quizId]);

        // Re-fetch all IDs
        $stmt = $db->prepare("SELECT id FROM quiz_questions WHERE quiz_id = ? AND difficulty = 'easy'");
        $stmt->execute([$quizId]);
        $easyIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

        $stmt = $db->prepare("SELECT id FROM quiz_questions WHERE quiz_id = ? AND difficulty = 'medium'");
        $stmt->execute([$quizId]);
        $mediumIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

        $stmt = $db->prepare("SELECT id FROM quiz_questions WHERE quiz_id = ? AND difficulty = 'hard'");
        $stmt->execute([$quizId]);
        $hardIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
    }

    if (count($easyIds) < 5 || count($mediumIds) < 5 || count($hardIds) < 5) {
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Insufficient questions in database for this category."]);
        exit();
    }

    // Shuffle each pool in memory
    shuffle($easyIds);
    shuffle($mediumIds);
    shuffle($hardIds);

    // Slice 5 from each
    $selectedEasy = array_slice($easyIds, 0, 5);
    $selectedMedium = array_slice($mediumIds, 0, 5);
    $selectedHard = array_slice($hardIds, 0, 5);

    // Combine them in order: Easy (1-5), Medium (6-10), Hard (11-15)
    $selectedIds = array_merge($selectedEasy, $selectedMedium, $selectedHard);

    // 5. Fetch the details of the selected questions
    $placeholders = implode(',', array_fill(0, count($selectedIds), '?'));
    $stmt = $db->prepare("SELECT id, question_text, option_a, option_b, option_c, option_d, correct_option FROM quiz_questions WHERE id IN ($placeholders)");
    $stmt->execute($selectedIds);
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Re-index the query results so we can map them back to the exact $selectedIds order
    $questionsById = [];
    foreach ($questions as $q) {
        $questionsById[intval($q['id'])] = $q;
    }

    // Build the sorted array matching the exact $selectedIds order (Easy -> Medium -> Hard)
    $sortedQuestions = [];
    foreach ($selectedIds as $id) {
        if (isset($questionsById[$id])) {
            $sortedQuestions[] = $questionsById[$id];
        }
    }

    // Format structure for frontend
    $formattedQuestions = [];
    foreach ($sortedQuestions as $q) {
        $formattedQuestions[] = [
            "id" => intval($q['id']),
            "question" => $q['question_text'],
            "correct" => intval($q['correct_option']),
            "options" => [
                $q['option_a'],
                $q['option_b'],
                $q['option_c'],
                $q['option_d']
            ]
        ];
    }

    echo json_encode([
        "status" => "success",
        "questions" => $formattedQuestions
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to load quiz questions: " . $e->getMessage()]);
}
