<cfscript>
// Create a task (e.g., photo task for menu item)
// Input: BusinessID, ItemID, TaskType, Instructions, PYTReward
// Output: { OK: true, TASK_ID: ... }

response = { "OK": false };

try {
    requestBody = toString(getHttpRequestData().content);
    if (!len(requestBody)) {
        throw("Request body is required");
    }

    jsonData = deserializeJSON(requestBody);
    businessID = val(jsonData.BusinessID ?: 0);
    itemID = val(jsonData.ItemID ?: 0);
    taskType = jsonData.TaskType ?: "employee_photo";
    instructions = jsonData.Instructions ?: "";
    pytReward = val(jsonData.PYTReward ?: 0);

    if (businessID == 0) {
        throw("BusinessID is required");
    }

    // Get item info if itemID provided
    itemName = "";
    if (itemID > 0) {
        itemQuery = queryExecute("
            SELECT ItemName FROM Items WHERE ItemID = :itemID
        ", { itemID: itemID });
        if (itemQuery.recordCount) {
            itemName = itemQuery.ItemName;
        }
    }

    // Create task description
    taskDescription = "";
    switch(taskType) {
        case "employee_photo":
            taskDescription = "Take a photo of: " & itemName;
            break;
        case "user_photo":
            taskDescription = "Submit a photo of " & itemName & " to earn " & pytReward & " PYT";
            break;
        default:
            taskDescription = instructions;
    }

    // Insert task
    queryExecute("
        INSERT INTO Tasks (
            TaskBusinessID,
            TaskItemID,
            TaskType,
            TaskDescription,
            TaskInstructions,
            TaskPYTReward,
            TaskStatus,
            TaskCreatedOn
        ) VALUES (
            :businessID,
            :itemID,
            :taskType,
            :description,
            :instructions,
            :pytReward,
            'pending',
            NOW()
        )
    ", {
        businessID: businessID,
        itemID: itemID,
        taskType: taskType,
        description: taskDescription,
        instructions: instructions,
        pytReward: pytReward
    });

    // Get the new task ID
    result = queryExecute("SELECT LAST_INSERT_ID() as newID");
    taskID = result.newID;

    response = {
        "OK": true,
        "TASK_ID": taskID,
        "MESSAGE": "Task created successfully"
    };

} catch (any e) {
    response = {
        "OK": false,
        "ERROR": e.message
    };
}

cfheader(name="Content-Type", value="application/json");
writeOutput(serializeJSON(response));
</cfscript>
