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

<cfscript>
// Returns all task types for a business (for portal management)
// Input: BusinessID (required)
// Output: { OK: true, TASK_TYPES: [...] }

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 from body, header, or URL
    businessID = 0;
    httpHeaders = getHttpRequestData().headers;

    if (structKeyExists(data, "BusinessID") && isNumeric(data.BusinessID)) {
        businessID = int(data.BusinessID);
    } else if (structKeyExists(httpHeaders, "X-Business-ID") && isNumeric(httpHeaders["X-Business-ID"])) {
        businessID = int(httpHeaders["X-Business-ID"]);
    } else if (structKeyExists(url, "BusinessID") && isNumeric(url.BusinessID)) {
        businessID = int(url.BusinessID);
    }

    if (businessID == 0) {
        apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "BusinessID is required" });
    }

    // Get task types for this business
    q = queryExecute("
        SELECT
            tt_TaskTypeID as TaskTypeID,
            Name as TaskTypeName,
            Description as TaskTypeDescription,
            Icon as TaskTypeIcon,
            Color as TaskTypeColor,
            SortOrder as SortOrder,
            TaskCategoryID as CategoryID
        FROM tt_TaskTypes
        WHERE BusinessID = :businessID
        ORDER BY SortOrder, tt_TaskTypeID
    ", {
        businessID: { value: businessID, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    taskTypes = [];
    for (row in q) {
        arrayAppend(taskTypes, {
            "TaskTypeID": row.TaskTypeID,
            "TaskTypeName": row.TaskTypeName,
            "TaskTypeDescription": isNull(row.TaskTypeDescription) ? "" : row.TaskTypeDescription,
            "TaskTypeIcon": isNull(row.TaskTypeIcon) ? "notifications" : row.TaskTypeIcon,
            "TaskTypeColor": isNull(row.TaskTypeColor) ? "##9C27B0" : row.TaskTypeColor,
            "CategoryID": isNull(row.CategoryID) ? "" : row.CategoryID
        });
    }

    apiAbort({
        "OK": true,
        "TASK_TYPES": taskTypes,
        "COUNT": arrayLen(taskTypes)
    });

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