<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8" reset="true">
<cfheader name="Cache-Control" value="no-store">

<cfscript>
/**
 * List Categories for a Business
 *
 * POST body:
 * {
 *   "BusinessID": 37
 * }
 *
 * Returns all categories with their schedule settings.
 */

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

response = { "OK": false };

try {
    data = readJsonBody();

    BusinessID = structKeyExists(data, "BusinessID") ? val(data.BusinessID) : 0;

    if (BusinessID <= 0) {
        response["ERROR"] = "missing_businessid";
        response["MESSAGE"] = "BusinessID is required";
        writeOutput(serializeJSON(response));
        abort;
    }

    q = queryExecute("
        SELECT
            ID,
            BusinessID,
            ParentCategoryID,
            Name,
            ImageExtension,
            OrderTypes,
            ScheduleStart,
            ScheduleEnd,
            ScheduleDays,
            SortOrder,
            AddedOn
        FROM Categories
        WHERE BusinessID = :bizId
        ORDER BY SortOrder, Name
    ", { bizId: BusinessID }, { datasource = "payfrit" });

    categories = [];
    for (row in q) {
        arrayAppend(categories, {
            "CategoryID": row.ID,
            "BusinessID": row.BusinessID,
            "ParentCategoryID": row.ParentCategoryID,
            "Name": row.Name,
            "ImageExtension": len(trim(row.ImageExtension)) ? row.ImageExtension : "",
            "OrderTypes": row.OrderTypes,
            "ScheduleStart": isNull(row.ScheduleStart) ? "" : timeFormat(row.ScheduleStart, "HH:mm:ss"),
            "ScheduleEnd": isNull(row.ScheduleEnd) ? "" : timeFormat(row.ScheduleEnd, "HH:mm:ss"),
            "ScheduleDays": isNull(row.ScheduleDays) ? "" : row.ScheduleDays,
            "SortOrder": row.SortOrder,
            "AddedOn": dateTimeFormat(row.AddedOn, "yyyy-mm-dd HH:nn:ss")
        });
    }

    response["OK"] = true;
    response["Categories"] = categories;
    response["COUNT"] = arrayLen(categories);

} catch (any e) {
    response["ERROR"] = "server_error";
    response["MESSAGE"] = e.message;
    response["DETAIL"] = e.detail;
}

writeOutput(serializeJSON(response));
</cfscript>
