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

<cfcontent type="application/json; charset=utf-8" reset="true">
<cfheader name="Cache-Control" value="no-store">

<cfscript>
function apiAbort(obj){
  writeOutput(serializeJSON(obj));
  abort;
}

function readJsonBody(){
  raw = toString(getHttpRequestData().content);
  if (isNull(raw) || len(trim(raw)) EQ 0){
    apiAbort({OK=false,ERROR="missing_body"});
  }
  try {
    parsed = deserializeJSON(raw);
  } catch(any e){
    apiAbort({OK=false,ERROR="bad_json",MESSAGE="Invalid JSON body"});
  }
  if (!isStruct(parsed)){
    apiAbort({OK=false,ERROR="bad_json",MESSAGE="JSON must be an object"});
  }
  return parsed;
}

/* ---------- AUTH CONTEXT ---------- */
if (!structKeyExists(request,"UserID") || !isNumeric(request.UserID) || request.UserID LTE 0){
  apiAbort({OK=false,ERROR="not_logged_in"});
}
if (!structKeyExists(request,"BusinessID") || !isNumeric(request.BusinessID) || request.BusinessID LTE 0){
  apiAbort({OK=false,ERROR="no_business_selected"});
}

/* ---------- INPUT ---------- */
data = readJsonBody();

if (
  !structKeyExists(data,"lt_Beacon_Businesses_ServicePointID")
  || !isNumeric(data.lt_Beacon_Businesses_ServicePointID)
  || int(data.lt_Beacon_Businesses_ServicePointID) LTE 0
){
  apiAbort({OK=false,ERROR="missing_lt_Beacon_Businesses_ServicePointID"});
}

RelID = int(data.lt_Beacon_Businesses_ServicePointID);
</cfscript>

<!--- Confirm the row exists for this BusinessID (and capture what it was) --->
<cfquery name="qFind" datasource="#application.datasource#">
  SELECT
    lt_Beacon_Businesses_ServicePointID,
    BeaconID,
    ServicePointID
  FROM lt_Beacon_Businesses_ServicePoints
  WHERE lt_Beacon_Businesses_ServicePointID =
    <cfqueryparam cfsqltype="cf_sql_integer" value="#RelID#">
    AND BusinessID =
    <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
  LIMIT 1
</cfquery>

<cfif qFind.recordCount EQ 0>
  <cfoutput>#serializeJSON({
    "OK"=false,
    "ERROR"="not_found",
    "lt_Beacon_Businesses_ServicePointID"=RelID,
    "BusinessID"=(request.BusinessID & "")
  })#</cfoutput>
  <cfabort>
</cfif>

<!--- Delete it --->
<cfquery datasource="#application.datasource#">
  DELETE FROM lt_Beacon_Businesses_ServicePoints
  WHERE lt_Beacon_Businesses_ServicePointID =
    <cfqueryparam cfsqltype="cf_sql_integer" value="#RelID#">
    AND BusinessID =
    <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
  LIMIT 1
</cfquery>

<cfoutput>#serializeJSON({
  "OK"=true,
  "ERROR"="",
  "ACTION"="deleted",
  "lt_Beacon_Businesses_ServicePointID"=RelID,
  "BeaconID"=qFind.BeaconID,
  "ServicePointID"=qFind.ServicePointID,
  "BusinessID"=(request.BusinessID & "")
})#</cfoutput>
