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

### API Blueprint: /admin/task_questions
# Description: Manages individual questions for specific task types.

# GET /admin/task_questions?action=list&task_id={task_id}
# Description: Lists all questions for a specific task_id.
# Headers:
#   - Authorization: Bearer <token>
# Parameters:
#   - action: string (required, value: list)
#   - task_id: integer (required)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Questions fetched",
#       "data": {
#         "questions": [
#           {
#             "id": 1,
#             "task_id": 101,
#             "question": "Which is correct?",
#             "option_1": "Aplep",
#             "option_2": "Apple",
#             "option_3": "Paple",
#             "option_4": "Leppa",
#             "correct_option": "Apple",
#             "correctness_answer": null, // For math_check
#             "created_at": "2025-06-01 10:00:00"
#           }
#         ]
#       }
#     }

# POST /admin/task_questions?action={add|edit|delete}
# Description: Adds, edits, or deletes a task question.
# Headers:
#   - Authorization: Bearer <token>
# Request Body (for add/edit - parameters vary by task_type):
#   - task_id: integer (required)
#   - question: string (required for most)
#   - option_1, option_2, option_3, option_4: string (required for quiz, spelling, puzzle, faster)
#   - correct_option: string (required for quiz, spelling, puzzle, faster)
#   - correctness_answer: string (required for math_check, 'Yes' or 'No')
# Request Body (for delete):
#   - id: integer (required, question_id to delete)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Operation successful"
#     }
#   - 400: Invalid input, Task not found, Missing required fields for task type
#   - 401: Unauthorized
#   - 500: Database connection failed

$token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
authenticateAdmin(str_replace('Bearer ', '', $token));

$action = $_GET['action'] ?? '';
$conn = getDbConnection();

switch ($action) {
    case 'list':
        validateInput($_GET, ['task_id']);
        $task_id = (int)$_GET['task_id'];

        $stmt = $conn->prepare("SELECT id, task_id, question, option_1, option_2, option_3, option_4, correct_option, correctness_answer, created_at, updated_at FROM task_questions WHERE task_id = ? ORDER BY created_at DESC");
        if (!$stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->bind_param("i", $task_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $questions = [];
        while ($row = $result->fetch_assoc()) {
            $questions[] = $row;
        }
        sendResponse(200, 'Questions fetched', ['questions' => $questions]);
        break;

    case 'add':
    case 'edit':
        // 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');
        }

        validateInput($data, ['task_id']);
        $task_id = (int)$data['task_id'];

        // Get task_type to validate question fields
        $task_type_stmt = $conn->prepare("SELECT task_type FROM tasks WHERE id = ?");
        if (!$task_type_stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $task_type_stmt->bind_param("i", $task_id);
        $task_type_stmt->execute();
        $task_type_result = $task_type_stmt->get_result();
        $task_info = $task_type_result->fetch_assoc();
        $task_type_stmt->close();

        if (!$task_info) {
            sendResponse(400, 'Task ID not found.');
        }
        $task_type = $task_info['task_type'];

        $question = $data['question'] ?? null;
        $option_1 = $data['option_1'] ?? null;
        $option_2 = $data['option_2'] ?? null;
        $option_3 = $data['option_3'] ?? null;
        $option_4 = $data['option_4'] ?? null;
        $correct_option = $data['correct_option'] ?? null;
        $correctness_answer = $data['correctness_answer'] ?? null;

        // Validation based on task_type
        if (in_array($task_type, ['word_puzzle', 'alphabet_puzzle', 'count_images', 'big_vs_small'])) {
            validateInput($data, ['question', 'option_1', 'option_2', 'option_3', 'option_4', 'correct_option']);
            if (!in_array($correct_option, [$option_1, $option_2, $option_3, $option_4])) {
                sendResponse(400, 'Correct option must be one of the provided options (1-4).');
            }
            $correctness_answer = null; // Ensure this is null for these types
        } else {
            sendResponse(400, 'Unsupported task type for adding/editing questions.');
        }

        if ($action === 'add') {
            $stmt = $conn->prepare("INSERT INTO task_questions (task_id, question, option_1, option_2, option_3, option_4, correct_option, correctness_answer) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            if (!$stmt) {
                sendResponse(500, 'Database query preparation failed: ' . $conn->error);
            }
            $stmt->bind_param("isssssss", $task_id, $question, $option_1, $option_2, $option_3, $option_4, $correct_option, $correctness_answer);
        } else { // 'edit'
            validateInput($data, ['id']);
            $question_id = (int)$data['id'];

            $stmt = $conn->prepare("UPDATE task_questions SET task_id = ?, question = ?, option_1 = ?, option_2 = ?, option_3 = ?, option_4 = ?, correct_option = ?, correctness_answer = ? WHERE id = ?");
            if (!$stmt) {
                sendResponse(500, 'Database query preparation failed: ' . $conn->error);
            }
            $stmt->bind_param("isssssssi", $task_id, $question, $option_1, $option_2, $option_3, $option_4, $correct_option, $correctness_answer, $question_id);
        }
        $stmt->execute();
        if ($stmt->affected_rows > 0) {
            sendResponse(200, ucfirst($action) . ' successful.');
        } else {
            sendResponse(404, 'Question not found or no changes made.');
        }
        break;

    case 'delete':
        // 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');
        }

        validateInput($data, ['id']);
        $question_id = (int)$data['id'];

        $stmt = $conn->prepare("DELETE FROM task_questions WHERE id = ?");
        if (!$stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->bind_param("i", $question_id);
        $stmt->execute();

        if ($stmt->affected_rows > 0) {
            sendResponse(200, 'Question deleted successfully.');
        } else {
            sendResponse(404, 'Question not found.');
        }
        break;

    default:
        sendResponse(400, 'Invalid action');
        break;
}

$conn->close();
?>