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

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

<cftry>
  <!--- Build WHERE clause based on filter type --->
  <cfset whereClauses = ["t.TaskClaimedByUserID = ?"]>
  <cfset params = [ { value = UserID, cfsqltype = "cf_sql_integer" } ]>

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

  <!--- Filter by type: active (not completed), completed, today, week --->
  <cfswitch expression="#FilterType#">
    <cfcase value="active">
      <cfset arrayAppend(whereClauses, "t.TaskCompletedOn IS NULL")>
    </cfcase>
    <cfcase value="completed">
      <cfset arrayAppend(whereClauses, "t.TaskCompletedOn IS NOT NULL")>
    </cfcase>
    <cfcase value="today">
      <cfset arrayAppend(whereClauses, "DATE(t.TaskClaimedOn) = CURDATE()")>
    </cfcase>
    <cfcase value="week">
      <cfset arrayAppend(whereClauses, "t.TaskClaimedOn >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)")>
    </cfcase>
  </cfswitch>

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

  <cfset qTasks = queryExecute("
    SELECT
      t.TaskID,
      t.TaskBusinessID,
      t.TaskCategoryID,
      t.TaskOrderID,
      t.TaskTypeID,
      t.TaskAddedOn,
      t.TaskClaimedByUserID,
      t.TaskClaimedOn,
      t.TaskCompletedOn,
      tc.TaskCategoryName,
      tc.TaskCategoryColor,
      b.BusinessName
    FROM Tasks t
    LEFT JOIN TaskCategories tc ON tc.TaskCategoryID = t.TaskCategoryID
    LEFT JOIN Businesses b ON b.BusinessID = t.TaskBusinessID
    WHERE #whereSQL#
    ORDER BY t.TaskClaimedOn DESC
  ", params, { datasource = "payfrit" })>

  <cfset tasks = []>

  <cfloop query="qTasks">
    <cfset taskTitle = "Task ##" & qTasks.TaskID>
    <cfif qTasks.TaskOrderID GT 0>
      <cfset taskTitle = "Order ##" & qTasks.TaskOrderID>
    </cfif>

    <cfset arrayAppend(tasks, {
      "TaskID": qTasks.TaskID,
      "TaskBusinessID": qTasks.TaskBusinessID,
      "BusinessName": qTasks.BusinessName,
      "TaskCategoryID": qTasks.TaskCategoryID,
      "TaskTypeID": qTasks.TaskTypeID,
      "TaskTitle": taskTitle,
      "TaskDetails": "",
      "TaskCreatedOn": dateFormat(qTasks.TaskAddedOn, "yyyy-mm-dd") & "T" & timeFormat(qTasks.TaskAddedOn, "HH:mm:ss"),
      "TaskClaimedOn": (isNull(qTasks.TaskClaimedOn) OR len(trim(qTasks.TaskClaimedOn)) EQ 0) ? "" : dateFormat(qTasks.TaskClaimedOn, "yyyy-mm-dd") & "T" & timeFormat(qTasks.TaskClaimedOn, "HH:mm:ss"),
      "TaskCompletedOn": (isNull(qTasks.TaskCompletedOn) OR len(trim(qTasks.TaskCompletedOn)) EQ 0) ? "" : dateFormat(qTasks.TaskCompletedOn, "yyyy-mm-dd") & "T" & timeFormat(qTasks.TaskCompletedOn, "HH:mm:ss"),
      "TaskStatusID": (isNull(qTasks.TaskCompletedOn) OR len(trim(qTasks.TaskCompletedOn)) EQ 0) ? 1 : 3,
      "TaskSourceType": "order",
      "TaskSourceID": qTasks.TaskOrderID,
      "TaskCategoryName": len(trim(qTasks.TaskCategoryName)) ? qTasks.TaskCategoryName : "General",
      "TaskCategoryColor": len(trim(qTasks.TaskCategoryColor)) ? qTasks.TaskCategoryColor : "##888888"
    })>
  </cfloop>

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

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