<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) return {};
  try {
    parsed = deserializeJSON(raw);
  } catch(any e) {
    apiAbort({ OK=false, ERROR="bad_json", MESSAGE="Invalid JSON body" });
  }
  if (!isStruct(parsed)) return {};
  return parsed;
}

function normStr(v) {
  if (isNull(v)) return "";
  return trim(toString(v));
}

data = readJsonBody();

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" });
}

if (!structKeyExists(data, "BeaconName") || len(normStr(data.BeaconName)) EQ 0) {
  apiAbort({ OK=false, ERROR="missing_beacon_name", MESSAGE="BeaconName is required" });
}

beaconId = 0;
if (structKeyExists(data, "BeaconID") && isNumeric(data.BeaconID) && int(data.BeaconID) GT 0) {
  beaconId = int(data.BeaconID);
}

beaconName  = normStr(data.BeaconName);
uuid        = structKeyExists(data, "UUID") ? normStr(data.UUID) : "";
namespaceId = structKeyExists(data, "NamespaceId") ? normStr(data.NamespaceId) : "";
instanceId  = structKeyExists(data, "InstanceId") ? normStr(data.InstanceId) : "";

isActive = 1;
if (structKeyExists(data, "IsActive")) {
  if (isBoolean(data.IsActive)) isActive = (data.IsActive ? 1 : 0);
  else if (isNumeric(data.IsActive)) isActive = int(data.IsActive);
  else if (isSimpleValue(data.IsActive)) isActive = (lcase(trim(toString(data.IsActive))) EQ "true" ? 1 : 0);
}
</cfscript>

<cfif beaconId GT 0>
  <!--- Update, scoped to this business --->
  <cfquery datasource="#application.datasource#">
    UPDATE Beacons
    SET
      BeaconName  = <cfqueryparam cfsqltype="cf_sql_varchar" value="#beaconName#">,
      UUID        = <cfqueryparam cfsqltype="cf_sql_varchar" value="#uuid#" null="#(len(uuid) EQ 0)#">,
      NamespaceId = <cfqueryparam cfsqltype="cf_sql_varchar" value="#namespaceId#" null="#(len(namespaceId) EQ 0)#">,
      InstanceId  = <cfqueryparam cfsqltype="cf_sql_varchar" value="#instanceId#" null="#(len(instanceId) EQ 0)#">,
      IsActive    = <cfqueryparam cfsqltype="cf_sql_tinyint" value="#isActive#">
    WHERE BeaconID = <cfqueryparam cfsqltype="cf_sql_integer" value="#beaconId#">
      AND BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
  </cfquery>

  <!--- confirm it exists/belongs to business --->
  <cfquery name="qCheck" datasource="#application.datasource#">
    SELECT BeaconID
    FROM Beacons
    WHERE BeaconID = <cfqueryparam cfsqltype="cf_sql_integer" value="#beaconId#">
      AND BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
    LIMIT 1
  </cfquery>

  <cfif qCheck.recordCount EQ 0>
    <cfoutput>#serializeJSON({ OK=false, ERROR="not_found" })#</cfoutput>
    <cfabort>
  </cfif>

<cfelse>
  <!--- Insert --->
  <cfquery datasource="#application.datasource#">
    INSERT INTO Beacons (
      BusinessID,
      BeaconName,
      UUID,
      NamespaceId,
      InstanceId,
      IsActive
    ) VALUES (
      <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">,
      <cfqueryparam cfsqltype="cf_sql_varchar" value="#beaconName#">,
      <cfqueryparam cfsqltype="cf_sql_varchar" value="#uuid#" null="#(len(uuid) EQ 0)#">,
      <cfqueryparam cfsqltype="cf_sql_varchar" value="#namespaceId#" null="#(len(namespaceId) EQ 0)#">,
      <cfqueryparam cfsqltype="cf_sql_varchar" value="#instanceId#" null="#(len(instanceId) EQ 0)#">,
      <cfqueryparam cfsqltype="cf_sql_tinyint" value="#isActive#">
    )
  </cfquery>

  <cfquery name="qId" datasource="#application.datasource#">
    SELECT LAST_INSERT_ID() AS BeaconID
  </cfquery>
  <cfset beaconId = qId.BeaconID>
</cfif>

<!--- Return saved row --->
<cfquery name="qOut" datasource="#application.datasource#">
  SELECT
    BeaconID,
    BusinessID,
    BeaconName,
    UUID,
    NamespaceId,
    InstanceId,
    IsActive,
    CreatedAt,
    UpdatedAt
  FROM Beacons
  WHERE BeaconID = <cfqueryparam cfsqltype="cf_sql_integer" value="#beaconId#">
    AND BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
  LIMIT 1
</cfquery>

<cfset beacon = {
  "BeaconID"    = qOut.BeaconID,
  "BusinessID"  = qOut.BusinessID,
  "BeaconName"  = qOut.BeaconName,
  "UUID"        = qOut.UUID,
  "NamespaceId" = qOut.NamespaceId,
  "InstanceId"  = qOut.InstanceId,
  "IsActive"    = qOut.IsActive,
  "CreatedAt"   = qOut.CreatedAt,
  "UpdatedAt"   = qOut.UpdatedAt
}>

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