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

<cfscript>
// List task categories for a business
// Categories ARE Task Types (merged concept)
// Input: BusinessID (required)
// Output: { OK: true, CATEGORIES: [...] }

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

    if (structKeyExists(url, "bid") && isNumeric(url.bid)) {
        businessID = int(url.bid);
    } else if (structKeyExists(url, "BusinessID") && isNumeric(url.BusinessID)) {
        businessID = int(url.BusinessID);
    } else 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"]);
    }

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

    // Get Task Categories (separate from Services/Task Types)
    qCategories = queryTimed("
        SELECT
            ID,
            Name,
            Color
        FROM TaskCategories
        WHERE BusinessID = :businessID
          AND IsActive = 1
        ORDER BY Name
    ", {
        businessID: { value: businessID, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    categories = [];
    for (row in qCategories) {
        arrayAppend(categories, {
            "TaskCategoryID": row.ID,
            "Name": row.Name,
            "Color": row.Color
        });
    }

    apiAbort({
        "OK": true,
        "CATEGORIES": categories
    });

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