<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">

<cffunction name="readJsonBody" access="public" returntype="struct" output="false">
  <cfset var raw = getHttpRequestData().content>
  <cfif isNull(raw) OR len(trim(raw)) EQ 0>
    <cfreturn {}>
  </cfif>
  <cftry>
    <cfset var data = deserializeJSON(raw)>
    <cfif isStruct(data)>
      <cfreturn data>
    <cfelse>
      <cfreturn {}>
    </cfif>
    <cfcatch>
      <cfreturn {}>
    </cfcatch>
  </cftry>
</cffunction>

<cffunction name="apiAbort" access="public" returntype="void" output="true">
  <cfargument name="payload" type="struct" required="true">
  <cfcontent type="application/json; charset=utf-8">
  <cfoutput>#serializeJSON(arguments.payload)#</cfoutput>
  <cfabort>
</cffunction>

<cfset data = readJsonBody()>
<cfset BusinessID = 0>
<cfif structKeyExists(data, "BusinessID")>
  <cfset BusinessID = val(data.BusinessID)>
</cfif>

<cfif BusinessID LTE 0>
  <cfset apiAbort({ "OK": false, "ERROR": "missing_businessid", "MESSAGE": "BusinessID is required.", "DETAIL": "" })>
</cfif>

<cftry>
  <cfset q = queryExecute(
    "
      SELECT
        i.ItemID,
        i.ItemCategoryID,
        c.CategoryName,
        i.ItemName,
        i.ItemDescription,
        i.ItemParentItemID,
        i.ItemPrice,
        i.ItemIsActive,
        i.ItemIsCheckedByDefault,
        i.ItemRequiresChildSelection,
        i.ItemMaxNumSelectionReq,
        i.ItemIsCollapsible,
        i.ItemSortOrder
      FROM Items i
      INNER JOIN Categories c
        ON c.CategoryID = i.ItemCategoryID
      WHERE c.CategoryBusinessID = ?
      ORDER BY i.ItemParentItemID, i.ItemSortOrder, i.ItemID
    ",
    [ { value = BusinessID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>

  <cfset rows = []>
  <cfloop query="q">
    <cfset arrayAppend(rows, {
      "ItemID": q.ItemID,
      "ItemCategoryID": q.ItemCategoryID,
      "ItemCategoryName": q.CategoryName,
      "ItemName": q.ItemName,
      "ItemDescription": q.ItemDescription,
      "ItemParentItemID": q.ItemParentItemID,
      "ItemPrice": q.ItemPrice,
      "ItemIsActive": q.ItemIsActive,
      "ItemIsCheckedByDefault": q.ItemIsCheckedByDefault,
      "ItemRequiresChildSelection": q.ItemRequiresChildSelection,
      "ItemMaxNumSelectionReq": q.ItemMaxNumSelectionReq,
      "ItemIsCollapsible": q.ItemIsCollapsible,
      "ItemSortOrder": q.ItemSortOrder
    })>
  </cfloop>

  <cfset apiAbort({
    "OK": true,
    "ERROR": "",
    "Items": rows,
    "COUNT": arrayLen(rows)
  })>

  <cfcatch>
    <cfset apiAbort({
      "OK": false,
      "ERROR": "server_error",
      "MESSAGE": "DB error loading items",
      "DETAIL": cfcatch.message
    })>
  </cfcatch>
</cftry>
