<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8">

<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 )>

<cftry>
  <!--- Get raw employee records ---  >
  <cfset qEmployees = queryExecute("
    SELECT e.*, b.BusinessName
    FROM lt_Users_Businesses_Employees e
    INNER JOIN Businesses b ON b.BusinessID = e.BusinessID
    WHERE e.UserID = ?
    ORDER BY b.BusinessName ASC
  ", [ { value = UserID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

  <cfset employees = []>
  <cfloop query="qEmployees">
    <cfset arrayAppend(employees, {
      "EmployeeID": qEmployees.EmployeeID,
      "UserID": qEmployees.UserID,
      "BusinessID": qEmployees.BusinessID,
      "BusinessName": qEmployees.BusinessName,
      "EmployeeIsActive": qEmployees.EmployeeIsActive
    })>
  </cfloop>

  <!--- Check for duplicate businesses ---  >
  <cfset qDuplicates = queryExecute("
    SELECT BusinessName, COUNT(*) AS cnt
    FROM Businesses
    GROUP BY BusinessName
    HAVING COUNT(*) > 1
  ", [], { datasource = "payfrit" })>

  <cfset duplicates = []>
  <cfloop query="qDuplicates">
    <cfset arrayAppend(duplicates, {
      "BusinessName": qDuplicates.BusinessName,
      "Count": qDuplicates.cnt
    })>
  </cfloop>

  <cfoutput>#serializeJSON({
    "OK": true,
    "EMPLOYEE_COUNT": arrayLen(employees),
    "EMPLOYEES": employees,
    "DUPLICATE_BUSINESSES": duplicates
  })#</cfoutput>

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