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

<cfscript>
// Show all beacons with their current business/service point assignments
q = queryExecute("
  SELECT
    b.BeaconID,
    b.BeaconUUID,
    b.BeaconName,
    lt.BusinessID,
    lt.ServicePointID,
    biz.BusinessName,
    sp.ServicePointName
  FROM Beacons b
  LEFT JOIN lt_Beacon_Businesses_ServicePoints lt ON lt.BeaconID = b.BeaconID
  LEFT JOIN Businesses biz ON biz.BusinessID = lt.BusinessID
  LEFT JOIN ServicePoints sp ON sp.ServicePointID = lt.ServicePointID
  WHERE b.BeaconIsActive = 1
  ORDER BY b.BeaconID
", {}, { datasource: "payfrit" });

rows = [];
for (row in q) {
  arrayAppend(rows, {
    "BeaconID": row.BeaconID,
    "BeaconUUID": row.BeaconUUID,
    "BeaconName": row.BeaconName ?: "",
    "BusinessID": row.BusinessID ?: 0,
    "BusinessName": row.BusinessName ?: "",
    "ServicePointID": row.ServicePointID ?: 0,
    "ServicePointName": row.ServicePointName ?: ""
  });
}

// Also get service points for reference
spQuery = queryExecute("
  SELECT sp.ServicePointID, sp.ServicePointName, sp.ServicePointBusinessID, b.BusinessName
  FROM ServicePoints sp
  JOIN Businesses b ON b.BusinessID = sp.ServicePointBusinessID
  ORDER BY sp.ServicePointBusinessID, sp.ServicePointID
", {}, { datasource: "payfrit" });

servicePoints = [];
for (sp in spQuery) {
  arrayAppend(servicePoints, {
    "ServicePointID": sp.ServicePointID,
    "ServicePointName": sp.ServicePointName,
    "BusinessID": sp.ServicePointBusinessID,
    "BusinessName": sp.BusinessName
  });
}

writeOutput(serializeJSON({
  "OK": true,
  "BEACONS": rows,
  "SERVICE_POINTS": servicePoints
}));
</cfscript>
