<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 = val( structKeyExists(data,"BusinessID") ? data.BusinessID : 0 )>

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

<cftry>
  <cfset q = queryExecute("
    SELECT ID, BusinessID, Name, Color, SortOrder, IsActive
    FROM Stations
    WHERE BusinessID = ? AND IsActive = 1
    ORDER BY SortOrder, ID
  ", [ { value = BusinessID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

  <cfset rows = []>
  <cfloop query="q">
    <cfset arrayAppend(rows, {
      "StationID": q.ID,
      "BusinessID": q.BusinessID,
      "Name": q.Name,
      "Color": q.Color,
      "SortOrder": q.SortOrder
    })>
  </cfloop>

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

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