<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 BusinessID = val( structKeyExists(data,"BusinessID") ? data.BusinessID : 0 )>
<cfset CategoryID = val( structKeyExists(data,"CategoryID") ? data.CategoryID : 0 )>

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

<cftry>
  <!--- Get business name --->
  <cfset qBusiness = queryExecute("
    SELECT Name FROM Businesses WHERE ID = ?
  ", [ { value = BusinessID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>
  <cfset businessName = qBusiness.recordCount GT 0 ? qBusiness.Name : "">


  <!--- Build WHERE clause - unclaimed tasks only --->
  <cfset whereClauses = ["t.BusinessID = ?", "t.ClaimedByUserID = 0"]>
  <cfset params = [ { value = BusinessID, cfsqltype = "cf_sql_integer" } ]>

  <!--- Filter by category if provided --->
  <cfif CategoryID GT 0>
    <cfset arrayAppend(whereClauses, "t.CategoryID = ?")>
    <cfset arrayAppend(params, { value = CategoryID, cfsqltype = "cf_sql_integer" })>
  </cfif>

  <cfset whereSQL = arrayToList(whereClauses, " AND ")>

  <cfset qTasks = queryExecute("
    SELECT
      t.ID,
      t.BusinessID,
      t.CategoryID,
      t.OrderID,
      t.TaskTypeID,
      t.Title,
      t.Details,
      t.CreatedOn,
      t.ClaimedByUserID,
      tc.Name AS CategoryName,
      tc.Color AS CategoryColor,
      tt.Name AS TaskTypeName,
      tt.Icon AS TaskTypeIcon,
      tt.Color AS TaskTypeColor
    FROM Tasks t
    LEFT JOIN TaskCategories tc ON tc.ID = t.CategoryID
    LEFT JOIN tt_TaskTypes tt ON tt.ID = t.TaskTypeID
    WHERE #whereSQL#
    ORDER BY t.CreatedOn ASC
  ", params, { datasource = "payfrit" })>

  <cfset tasks = []>

  <cfloop query="qTasks">
    <!--- Use stored title if available, otherwise build from order --->
    <cfset taskTitle = "">
    <cfif len(trim(qTasks.Title))>
      <cfset taskTitle = qTasks.Title>
    <cfelseif qTasks.OrderID GT 0>
      <cfset taskTitle = "Order ##" & qTasks.OrderID>
    <cfelse>
      <cfset taskTitle = "Task ##" & qTasks.ID>
    </cfif>

    <cfset taskDetails = len(trim(qTasks.Details)) ? qTasks.Details : "">

    <cfset arrayAppend(tasks, {
      "TaskID": qTasks.ID,
      "BusinessID": qTasks.BusinessID,
      "TaskCategoryID": qTasks.CategoryID,
      "TaskTypeID": qTasks.TaskTypeID,
      "Title": taskTitle,
      "Details": taskDetails,
      "CreatedOn": dateFormat(qTasks.CreatedOn, "yyyy-mm-dd") & "T" & timeFormat(qTasks.CreatedOn, "HH:mm:ss"),
      "StatusID": qTasks.ClaimedByUserID GT 0 ? 1 : 0,
      "SourceType": "order",
      "SourceID": qTasks.OrderID,
      "CategoryName": len(trim(qTasks.CategoryName)) ? qTasks.CategoryName : "General",
      "CategoryColor": len(trim(qTasks.CategoryColor)) ? qTasks.CategoryColor : "##888888",
      "TaskTypeName": len(trim(qTasks.TaskTypeName)) ? qTasks.TaskTypeName : "",
      "TaskTypeIcon": len(trim(qTasks.TaskTypeIcon)) ? qTasks.TaskTypeIcon : "notifications",
      "TaskTypeColor": len(trim(qTasks.TaskTypeColor)) ? qTasks.TaskTypeColor : "##9C27B0"
    })>
  </cfloop>

  <cfset apiAbort({
    "OK": true,
    "ERROR": "",
    "TASKS": tasks,
    "COUNT": arrayLen(tasks),
    "BUSINESS_NAME": businessName
  })>

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