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

<cftry>

<cfset requestData = deserializeJSON(toString(getHttpRequestData().content))>

<cfif NOT structKeyExists(requestData, "UUIDs") OR NOT isArray(requestData.UUIDs) OR arrayLen(requestData.UUIDs) EQ 0>
  <cfoutput>#serializeJSON({
    "OK" = true,
    "ERROR" = "",
    "BEACONS" = []
  })#</cfoutput>
  <cfabort>
</cfif>

<!--- Clean and normalize UUIDs (remove dashes, uppercase) --->
<cfset cleanUUIDs = []>
<cfloop array="#requestData.UUIDs#" index="uuid">
  <cfset cleanUUID = uCase(reReplace(uuid, "-", "", "all"))>
  <cfif len(cleanUUID) EQ 32>
    <cfset arrayAppend(cleanUUIDs, cleanUUID)>
  </cfif>
</cfloop>

<cfif arrayLen(cleanUUIDs) EQ 0>
  <cfoutput>#serializeJSON({
    "OK" = true,
    "ERROR" = "",
    "BEACONS" = []
  })#</cfoutput>
  <cfabort>
</cfif>

<!--- Query for matching beacons with business info --->
<cfquery name="qBeacons" datasource="payfrit">
  SELECT
    b.ID AS BeaconID,
    b.Name AS BeaconName,
    b.UUID,
    COALESCE(sp.ID, 0) AS ServicePointID,
    COALESCE(sp.Name, '') AS ServicePointName,
    COALESCE(sp.BusinessID, lt.BusinessID, b.BusinessID) AS BusinessID,
    biz.Name AS BusinessName,
    biz.ParentBusinessID AS ParentBusinessID,
    COALESCE(parent.Name, '') AS ParentBusinessName,
    (SELECT COUNT(*) FROM Businesses WHERE ParentBusinessID = biz.ID) AS ChildCount
  FROM Beacons b
  LEFT JOIN ServicePoints sp ON sp.BeaconID = b.ID
  LEFT JOIN lt_BeaconsID_BusinessesID lt ON lt.BeaconID = b.ID
  INNER JOIN Businesses biz ON COALESCE(sp.BusinessID, lt.BusinessID, b.BusinessID) = biz.ID
  LEFT JOIN Businesses parent ON biz.ParentBusinessID = parent.ID
  WHERE b.UUID IN (<cfqueryparam value="#arrayToList(cleanUUIDs)#" cfsqltype="cf_sql_varchar" list="true">)
    AND b.IsActive = 1
    AND biz.IsDemo = 0
    AND biz.IsPrivate = 0
</cfquery>

<cfset beacons = []>
<cfloop query="qBeacons">
  <cfset arrayAppend(beacons, {
    "UUID" = qBeacons.UUID,
    "BeaconID" = qBeacons.BeaconID,
    "BeaconName" = qBeacons.BeaconName,
    "BusinessID" = qBeacons.BusinessID,
    "BusinessName" = qBeacons.BusinessName,
    "ServicePointID" = qBeacons.ServicePointID,
    "ServicePointName" = qBeacons.ServicePointName,
    "ParentBusinessID" = val(qBeacons.ParentBusinessID),
    "ParentBusinessName" = qBeacons.ParentBusinessName,
    "HasChildren" = qBeacons.ChildCount GT 0
  })>
</cfloop>

<cfoutput>#serializeJSON({
  "OK" = true,
  "ERROR" = "",
  "BEACONS" = beacons
})#</cfoutput>

<cfcatch type="any">
  <cfoutput>#serializeJSON({
    "OK" = false,
    "ERROR" = cfcatch.message
  })#</cfoutput>
</cfcatch>
</cftry>
