<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8" reset="true">

<cfscript>
// Update sort order for task types
// Input: BusinessID (required), Order (array of TaskTypeIDs in desired order)
// Output: { OK: true }

function apiAbort(required struct payload) {
    writeOutput(serializeJSON(payload));
    abort;
}

function readJsonBody() {
    var raw = getHttpRequestData().content;
    if (isNull(raw)) raw = "";
    if (!len(trim(raw))) return {};
    try {
        var data = deserializeJSON(raw);
        if (isStruct(data)) return data;
    } catch (any e) {}
    return {};
}

try {
    data = readJsonBody();

    // Get BusinessID
    businessID = 0;
    if (structKeyExists(data, "BusinessID") && isNumeric(data.BusinessID)) {
        businessID = int(data.BusinessID);
    }
    if (businessID == 0) {
        apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "BusinessID is required" });
    }

    // Get Order array
    if (!structKeyExists(data, "Order") || !isArray(data.Order)) {
        apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "Order array is required" });
    }
    orderArray = data.Order;

    // Update sort order for each task type
    sortOrder = 0;
    for (taskTypeID in orderArray) {
        if (isNumeric(taskTypeID)) {
            sortOrder++;
            queryTimed("
                UPDATE tt_TaskTypes
                SET SortOrder = :sortOrder
                WHERE tt_TaskTypeID = :taskTypeID
                  AND BusinessID = :businessID
            ", {
                sortOrder: { value: sortOrder, cfsqltype: "cf_sql_integer" },
                taskTypeID: { value: int(taskTypeID), cfsqltype: "cf_sql_integer" },
                businessID: { value: businessID, cfsqltype: "cf_sql_integer" }
            }, { datasource: "payfrit" });
        }
    }

    apiAbort({
        "OK": true,
        "MESSAGE": "Sort order updated"
    });

} catch (any e) {
    apiAbort({
        "OK": false,
        "ERROR": "server_error",
        "MESSAGE": e.message
    });
}
</cfscript>
