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

data = readJsonBody();

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

BusinessID = int(data.BusinessID);
SessionEnabled = structKeyExists(data, "SessionEnabled") && isNumeric(data.SessionEnabled) ? int(data.SessionEnabled) : 0;
SessionLockMinutes = structKeyExists(data, "SessionLockMinutes") && isNumeric(data.SessionLockMinutes) ? int(data.SessionLockMinutes) : 30;
SessionPaymentStrategy = structKeyExists(data, "SessionPaymentStrategy") ? left(trim(data.SessionPaymentStrategy), 1) : "A";

// Validate
if (SessionLockMinutes < 5) SessionLockMinutes = 5;
if (SessionLockMinutes > 480) SessionLockMinutes = 480;
if (SessionPaymentStrategy != "A" && SessionPaymentStrategy != "P") SessionPaymentStrategy = "A";
</cfscript>

<cftry>
  <cfquery datasource="payfrit">
    UPDATE Businesses
    SET SessionEnabled = <cfqueryparam cfsqltype="cf_sql_tinyint" value="#SessionEnabled#">,
        SessionLockMinutes = <cfqueryparam cfsqltype="cf_sql_integer" value="#SessionLockMinutes#">,
        SessionPaymentStrategy = <cfqueryparam cfsqltype="cf_sql_char" value="#SessionPaymentStrategy#">
    WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#BusinessID#">
  </cfquery>

  <cfoutput>#serializeJSON({
    "OK" = true,
    "ERROR" = "",
    "BusinessID" = BusinessID,
    "SessionEnabled" = SessionEnabled,
    "SessionLockMinutes" = SessionLockMinutes,
    "SessionPaymentStrategy" = SessionPaymentStrategy
  })#</cfoutput>

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