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

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

<cftry>
<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, "BusinessID") || !isNumeric(request.BusinessID) || request.BusinessID LTE 0) {
  apiAbort({ OK=false, ERROR="no_business_selected" });
}

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

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

spName = normStr(data.Name);
spCode = structKeyExists(data, "Code") ? normStr(data.Code) : "";
spTypeID = structKeyExists(data, "TypeID") && isNumeric(data.TypeID) ? int(data.TypeID) : 1;
sortOrder = structKeyExists(data, "SortOrder") && isNumeric(data.SortOrder) ? int(data.SortOrder) : 0;

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 servicePointId GT 0>
  <!--- Update, scoped to this business --->
  <cfquery datasource="payfrit">
    UPDATE ServicePoints
    SET
      Name     = <cfqueryparam cfsqltype="cf_sql_varchar" value="#spName#">,
      Code     = <cfqueryparam cfsqltype="cf_sql_varchar" value="#spCode#" null="#(len(spCode) EQ 0)#">,
      TypeID   = <cfqueryparam cfsqltype="cf_sql_integer" value="#spTypeID#">,
      IsActive = <cfqueryparam cfsqltype="cf_sql_tinyint" value="#isActive#">,
      SortOrder            = <cfqueryparam cfsqltype="cf_sql_integer" value="#sortOrder#">
    WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#servicePointId#">
      AND BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
  </cfquery>

  <!--- confirm it exists/belongs to business --->
  <cfquery name="qCheck" datasource="payfrit">
    SELECT ID
    FROM ServicePoints
    WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#servicePointId#">
      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="payfrit">
    INSERT INTO ServicePoints (
      BusinessID,
      Name,
      Code,
      TypeID,
      IsActive,
      SortOrder
    ) VALUES (
      <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">,
      <cfqueryparam cfsqltype="cf_sql_varchar" value="#spName#">,
      <cfqueryparam cfsqltype="cf_sql_varchar" value="#spCode#" null="#(len(spCode) EQ 0)#">,
      <cfqueryparam cfsqltype="cf_sql_integer" value="#spTypeID#">,
      <cfqueryparam cfsqltype="cf_sql_tinyint" value="#isActive#">,
      <cfqueryparam cfsqltype="cf_sql_integer" value="#sortOrder#">
    )
  </cfquery>

  <cfquery name="qId" datasource="payfrit">
    SELECT LAST_INSERT_ID() AS ServicePointID
  </cfquery>
  <cfset servicePointId = qId.ServicePointID>
</cfif>

<!--- Return saved row --->
<cfquery name="qOut" datasource="payfrit">
  SELECT
    ID,
    BusinessID,
    Name,
    Code,
    TypeID,
    IsActive,
    SortOrder
  FROM ServicePoints
  WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#servicePointId#">
    AND BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
  LIMIT 1
</cfquery>

<cfset servicePoint = {
  "ServicePointID"    = qOut.ServicePointID,
  "BusinessID"        = qOut.BusinessID,
  "Name"  = qOut.Name,
  "Code"  = qOut.Code,
  "TypeID"= qOut.TypeID,
  "IsActive"          = qOut.IsActive,
  "SortOrder"         = qOut.SortOrder
}>

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

<cfcatch type="any">
  <cfheader statuscode="200" statustext="OK">
  <cfcontent type="application/json; charset=utf-8" reset="true">
  <cfoutput>#serializeJSON({ OK=false, ERROR="server_error", MESSAGE=cfcatch.message, DETAIL=cfcatch.detail })#</cfoutput>
</cfcatch>
</cftry>
