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

<cffunction name="apiAbort" access="public" returntype="void" output="true">
  <cfargument name="payload" type="struct" required="true">
  <cfcontent type="application/json; charset=utf-8">
  <cfoutput>#serializeJSON(arguments.payload)#</cfoutput>
  <cfabort>
</cffunction>

<cffunction name="readJsonBody" access="public" returntype="struct" output="false">
  <cfset var raw = getHttpRequestData().content>
  <cfif isNull(raw) OR len(trim(raw)) EQ 0>
    <cfreturn {}>
  </cfif>
  <cftry>
    <cfset var data = deserializeJSON(raw)>
    <cfif isStruct(data)>
      <cfreturn data>
    <cfelse>
      <cfreturn {}>
    </cfif>
    <cfcatch>
      <cfreturn {}>
    </cfcatch>
  </cftry>
</cffunction>

<cfset data = readJsonBody()>
<cfset UserID = val( structKeyExists(data,"UserID") ? data.UserID : 0 )>

<cfif UserID LTE 0>
  <cfset apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "UserID is required." })>
</cfif>

<cftry>
  <cfset qBusinesses = queryTimed("
    SELECT
      MIN(e.ID) AS EmployeeID,
      e.BusinessID,
      MIN(e.StatusID) AS StatusID,
      MAX(e.IsActive) AS IsActive,
      b.Name AS Name,
      (SELECT COUNT(*) FROM Tasks t WHERE t.BusinessID = e.BusinessID AND t.ClaimedByUserID = 0) AS PendingTaskCount
    FROM Employees e
    INNER JOIN Businesses b ON b.ID = e.BusinessID
    WHERE e.UserID = ? AND e.IsActive = b'1'
    GROUP BY e.BusinessID, b.Name
    ORDER BY b.Name ASC
  ", [ { value = UserID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

  <cfset businesses = []>

  <cfloop query="qBusinesses">
    <cfset arrayAppend(businesses, {
      "EmployeeID": qBusinesses.EmployeeID,
      "BusinessID": qBusinesses.BusinessID,
      "Name": qBusinesses.Name,
      "Address": "",
      "City": "",
      "StatusID": qBusinesses.StatusID,
      "PendingTaskCount": qBusinesses.PendingTaskCount
    })>
  </cfloop>

  <cfset apiAbort({
    "OK": true,
    "ERROR": "",
    "BUSINESSES": businesses,
    "COUNT": arrayLen(businesses)
  })>

  <cfcatch>
    <cfset apiAbort({
      "OK": false,
      "ERROR": "server_error",
      "MESSAGE": "Error loading businesses",
      "DETAIL": cfcatch.message
    })>
  </cfcatch>
</cftry>
