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

### API Blueprint: /admin/tasks
# Description: Manages task types (e.g., quiz, spelling).

# GET /admin/tasks?action=list
# Description: Lists all available task types.
# Headers:
#   - Authorization: Bearer <token>
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Tasks fetched",
#       "data": {
#         "tasks": [
#           {
#             "id": 1,
#             "task_type": "correct_spelling",
#             "reward_coins": 10,
#             "is_enabled": 1,
#             "created_at": "2025-06-01 10:00:00",
#             "updated_at": "2025-06-01 10:00:00"
#           }
#         ]
#       }
#     }

# POST /admin/tasks?action={add|edit|delete}
# Description: Adds, edits, or deletes a task type.
# Headers:
#   - Authorization: Bearer <token>
# Request Body (for add):
#   - task_type: string (required, one of: quiz, correct_spelling, image_puzzle, find_faster, math_check)
#   - reward_coins: integer (required)
#   - is_enabled: boolean (optional, default 1)
# Request Body (for edit):
#   - id: integer (required, task_id to edit)
#   - task_type: string (optional)
#   - reward_coins: integer (optional)
#   - is_enabled: boolean (optional)
# Request Body (for delete):
#   - id: integer (required, task_id to delete)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Operation successful"
#     }
#   - 400: Invalid input, Task type already exists, Task not found
#   - 401: Unauthorized
#   - 500: Database connection failed

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

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

$valid_task_types = ['word_puzzle', 'alphabet_puzzle', 'count_images', 'big_vs_small'];

switch ($action) {
    case 'list':
        $stmt = $conn->prepare("SELECT id, task_type, reward_coins, is_enabled, created_at, updated_at FROM tasks ORDER BY created_at DESC");
        if (!$stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        $tasks = [];
        while ($row = $result->fetch_assoc()) {
            $tasks[] = $row;
        }
        sendResponse(200, 'Tasks fetched', ['tasks' => $tasks]);
        break;

    case 'add':
        // 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_type', 'reward_coins']);

        $task_type = $data['task_type'];
        $reward_coins = (int)$data['reward_coins'];
        $is_enabled = isset($data['is_enabled']) ? (int)$data['is_enabled'] : 1;

        if (!in_array($task_type, $valid_task_types)) {
            sendResponse(400, 'Invalid task_type provided.');
        }
        if ($reward_coins <= 0) {
            sendResponse(400, 'Reward coins must be a positive integer.');
        }

        // Check if task_type already exists
        $check_stmt = $conn->prepare("SELECT id FROM tasks WHERE task_type = ?");
        $check_stmt->bind_param("s", $task_type);
        $check_stmt->execute();
        $check_stmt->store_result();
        if ($check_stmt->num_rows > 0) {
            sendResponse(400, 'Task type already exists.');
        }
        $check_stmt->close();

        $stmt = $conn->prepare("INSERT INTO tasks (task_type, reward_coins, is_enabled) VALUES (?, ?, ?)");
        if (!$stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->bind_param("sii", $task_type, $reward_coins, $is_enabled);
        $stmt->execute();
        if ($stmt->affected_rows > 0) {
            sendResponse(200, 'Task added successfully.');
        } else {
            sendResponse(500, 'Failed to add task.');
        }
        break;

    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, ['id']);
        $task_id = (int)$data['id'];

        $updates = [];
        $params = [];
        $types = '';

        if (isset($data['task_type'])) {
            if (!in_array($data['task_type'], $valid_task_types)) {
                sendResponse(400, 'Invalid task_type provided.');
            }
            $updates[] = "task_type = ?";
            $params[] = $data['task_type'];
            $types .= 's';

            // Check if updated task_type already exists for another ID
            $check_stmt = $conn->prepare("SELECT id FROM tasks WHERE task_type = ? AND id != ?");
            $check_stmt->bind_param("si", $data['task_type'], $task_id);
            $check_stmt->execute();
            $check_stmt->store_result();
            if ($check_stmt->num_rows > 0) {
                sendResponse(400, 'Another task with this type already exists.');
            }
            $check_stmt->close();
        }
        if (isset($data['reward_coins'])) {
            $reward_coins = (int)$data['reward_coins'];
            if ($reward_coins <= 0) {
                sendResponse(400, 'Reward coins must be a positive integer.');
            }
            $updates[] = "reward_coins = ?";
            $params[] = $reward_coins;
            $types .= 'i';
        }
        if (isset($data['is_enabled'])) {
            $updates[] = "is_enabled = ?";
            $params[] = (int)$data['is_enabled'];
            $types .= 'i';
        }

        if (empty($updates)) {
            sendResponse(400, 'No fields to update provided.');
        }

        $sql = "UPDATE tasks SET " . implode(', ', $updates) . " WHERE id = ?";
        $params[] = $task_id;
        $types .= 'i';

        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            sendResponse(500, 'Database query preparation failed: ' . $conn->error);
        }
        $stmt->bind_param($types, ...$params);
        $stmt->execute();

        if ($stmt->affected_rows > 0) {
            sendResponse(200, 'Task updated successfully.');
        } else {
            sendResponse(404, 'Task 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']);
        $task_id = (int)$data['id'];

        // Optionally, check if there are questions associated with this task before deleting
        // If you want to prevent deletion if questions exist, add a check here.
        // E.g., SELECT COUNT(*) FROM task_questions WHERE task_id = ?

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

        if ($stmt->affected_rows > 0) {
            sendResponse(200, 'Task deleted successfully. Associated questions (if any) have also been deleted due to CASCADE.');
        } else {
            sendResponse(404, 'Task not found.');
        }
        break;

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

$conn->close();
// Note: $stmt->close() is handled within each case before sendResponse, or implicitly by $conn->close()
?>