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

### API Blueprint: /user/task_questions
# POST /user/task_questions
# Description: Fetches a specified number of questions for a specific task type.
# Headers:
#   - Device-ID: <device_id> (required)
#   - Session-Token: <session_token> (required)
# Request Body:
#   - user_id: integer (required)
#   - task_type: string (required, one of: quiz, correct_spelling, image_puzzle, find_faster, math_check)
#   - limit: integer (optional, default to 10, max 50) - Number of questions to fetch
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Questions fetched",
#       "data": {
#         "questions": [
#           {
#             "id": 1,
#             "task_type": "correct_spelling",
#             "question": "Which is correct?",
#             "options": ["Aplep", "Apple", "Paple", "Leppa"],
#             "correct_answer": "Apple"
#           },
#             // ... other question types
#         ]
#       },
#       "new_session_token": "new_strong_session_token_64_chars"
#     }
#   - 400: Invalid user_id, Invalid task_type, Invalid limit, No questions found for this task type
#   - 401: Unauthorized
#   - 429: Too many requests
#   - 500: Database connection failed

header('Content-Type: application/json');

$device_id = $_SERVER['HTTP_DEVICE_ID'] ?? '';
$session_token = $_SERVER['HTTP_SESSION_TOKEN'] ?? '';

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'POST') {
    sendResponse(405, 'Method not allowed');
}

// Get the encrypted payload
$encrypted_payload = file_get_contents('php://input');
if (empty($encrypted_payload)) {
    sendResponse(400, 'Empty request body');
}

// Decrypt the payload
$data = decryptRequestPayload($encrypted_payload);
if (!$data) {
    sendResponse(400, 'Invalid request body');
}

$task_type = $data['task_type'] ?? '';
$limit = $data['limit'] ?? 10; // Default limit to 10

// Validate and sanitize limit
$limit = (int)$limit;
if ($limit <= 0 || $limit > 50) { // Set a reasonable max limit to prevent abuse
    sendResponse(400, 'Invalid limit. Must be between 1 and 50.');
}

// Define valid task types based on your new `tasks` table ENUM
$valid_task_types = ['math_fact', 'alphabet_guess', 'colour_guess', 'vehicle_guess'];
if (!in_array($task_type, $valid_task_types)) {
    sendResponse(400, 'Invalid task_type');
}

// Establish database connection
$conn = getDbConnection();

// First, get the task_id for the given task_type
$stmt_task = $conn->prepare("SELECT id, reward_coins FROM tasks WHERE task_type = ? AND is_enabled = 1");
if (!$stmt_task) {
    sendResponse(500, 'Database query preparation failed for tasks: ' . $conn->error);
}
$stmt_task->bind_param("s", $task_type);
$stmt_task->execute();
$result_task = $stmt_task->get_result();
$task_row = $result_task->fetch_assoc();
$stmt_task->close();

if (!$task_row) {
    sendResponse(400, 'No active task found for this type.');
}

$task_id = $task_row['id'];
$reward_coins = $task_row['reward_coins'];

// Fetch questions for the specific task_id with random order and limit
$stmt_questions = $conn->prepare("
    SELECT
        id,
        question,
        option_1,
        option_2,
        option_3,
        option_4,
        correct_option,
        correctness_answer
    FROM
        task_questions
    WHERE
        task_id = ?
    ORDER BY RAND()
    LIMIT ?
");

if (!$stmt_questions) {
    sendResponse(500, 'Database query preparation failed for task_questions: ' . $conn->error);
}

// Bind task_id as integer (i) and limit as integer (i)
$stmt_questions->bind_param("ii", $task_id, $limit);
$stmt_questions->execute();
$result_questions = $stmt_questions->get_result();

$questions = [];
while ($row = $result_questions->fetch_assoc()) {
    $formatted_question = [
        "id" => $row['id'],
        "task_type" => $task_type, // Add task_type to each question for clarity on the client side
    ];

    // Format options and correct answer based on task type
    switch ($task_type) {
        case 'math_fact':
        case 'alphabet_guess':
        case 'colour_guess':
        case 'vehicle_guess':
            $formatted_question["question"] = $row['question'] ?? '';
            $options = [];
            if (!empty($row['option_1'])) $options[] = $row['option_1'];
            if (!empty($row['option_2'])) $options[] = $row['option_2'];
            if (!empty($row['option_3'])) $options[] = $row['option_3'];
            if (!empty($row['option_4'])) $options[] = $row['option_4'];
            $formatted_question["options"] = $options;
            $formatted_question["correct_answer"] = $row['correct_option'] ?? null;
            break;
        default:
            sendResponse(400, 'Unsupported task type');
    }
    $questions[] = $formatted_question;
}

$stmt_questions->close();
$conn->close();

// Shuffle questions
shuffle($questions);

// Shuffle options for each question (except math_check)
foreach ($questions as &$q) {
    if (isset($q['options']) && is_array($q['options']) && $q['task_type'] !== 'math_check') {
        shuffle($q['options']);
    }
}
unset($q);

if (empty($questions)) {
    sendResponse(400, 'No questions found for this task type or the specified limit.');
}

sendResponse(200, 'Questions fetched', ['questions' => $questions, 'reward_coins' => $reward_coins]);
?>