<cfscript>
// Create a task (service bell request or photo task)
// Input for service bell: BusinessID, ServicePointID, TaskTypeID, Message
// Input for photo task: 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);

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

    // Check if this is a service bell request (has TaskTypeID)
    taskTypeID = val(jsonData.TaskTypeID ?: 0);

    if (taskTypeID > 0) {
        // Service bell task
        servicePointID = val(jsonData.ServicePointID ?: 0);
        orderID = val(jsonData.OrderID ?: 0);
        userID = val(jsonData.UserID ?: 0);
        message = jsonData.Message ?: "";

        // Get task type name for display
        taskTypeQuery = queryTimed("
            SELECT Name FROM tt_TaskTypes WHERE ID = :taskTypeID
        ", { taskTypeID: taskTypeID }, { datasource: "payfrit" });

        taskTitle = message;
        if (taskTypeQuery.recordCount && len(trim(taskTypeQuery.Name))) {
            taskTitle = taskTypeQuery.Name;
        }

        // Use message as details
        taskDetails = message;

        // Insert service bell task (no CategoryID - using TaskTypeID only)
        queryTimed("
            INSERT INTO Tasks (
                BusinessID,
                ServicePointID,
                TaskTypeID,
                OrderID,
                UserID,
                Title,
                Details,
                CreatedOn,
                ClaimedByUserID
            ) VALUES (
                :businessID,
                :servicePointID,
                :taskTypeID,
                :orderID,
                :userID,
                :taskTitle,
                :taskDetails,
                NOW(),
                0
            )
        ", {
            businessID: businessID,
            servicePointID: servicePointID,
            taskTypeID: taskTypeID,
            orderID: orderID,
            userID: userID,
            taskTitle: taskTitle,
            taskDetails: taskDetails
        }, { datasource: "payfrit" });

    } else {
        // Legacy photo task
        itemID = val(jsonData.ItemID ?: 0);
        taskType = jsonData.TaskType ?: "employee_photo";
        instructions = jsonData.Instructions ?: "";
        pytReward = val(jsonData.PYTReward ?: 0);

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

        // 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 legacy task
        queryTimed("
            INSERT INTO Tasks (
                BusinessID,
                TaskItemID,
                TaskType,
                TaskDescription,
                TaskInstructions,
                TaskPYTReward,
                TaskStatus,
                CreatedOn
            ) 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 = queryTimed("SELECT LAST_INSERT_ID() as newID", {}, { datasource: "payfrit" });
    taskID = result.newID;

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

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

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