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

<cfquery name="qBiz" datasource="payfrit">
  SELECT ID, Name, BeaconShardID, BeaconMajor
  FROM Businesses
  WHERE Name LIKE '%john%'
</cfquery>

<cfif qBiz.recordCount EQ 0>
  <cfoutput>#serializeJSON({ "OK": false, "ERROR": "No business found" })#</cfoutput>
  <cfabort>
</cfif>

<cfif qBiz.recordCount GT 1>
  <cfset bizList = []>
  <cfloop query="qBiz">
    <cfset arrayAppend(bizList, { "ID": qBiz.ID, "Name": qBiz.Name })>
  </cfloop>
  <cfoutput>#serializeJSON({ "OK": false, "ERROR": "Multiple businesses found", "Businesses": bizList })#</cfoutput>
  <cfabort>
</cfif>

<cfquery name="qSP" datasource="payfrit">
  SELECT ID, Name, BeaconMinor, IsActive
  FROM ServicePoints
  WHERE BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#qBiz.ID#">
  ORDER BY SortOrder, Name
</cfquery>

<cfset spList = []>
<cfloop query="qSP">
  <cfset arrayAppend(spList, {
    "ID": qSP.ID,
    "Name": qSP.Name,
    "BeaconMinor": isNull(qSP.BeaconMinor) ? "NULL" : val(qSP.BeaconMinor),
    "IsActive": qSP.IsActive
  })>
</cfloop>

<cfoutput>#serializeJSON({
  "OK": true,
  "Business": {
    "ID": qBiz.ID,
    "Name": qBiz.Name,
    "BeaconShardID": val(qBiz.BeaconShardID),
    "BeaconMajor": val(qBiz.BeaconMajor)
  },
  "ServicePoints": spList
})#</cfoutput>
