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

<cftry>
  <cfset qTasks = queryExecute("
    SELECT
      t.TaskID,
      t.TaskBusinessID,
      t.TaskOrderID,
      t.TaskClaimedByUserID,
      t.TaskClaimedOn,
      t.TaskCompletedOn,
      o.OrderStatusID
    FROM Tasks t
    LEFT JOIN Orders o ON o.OrderID = t.TaskOrderID
    ORDER BY t.TaskID DESC
    LIMIT 20
  ", [], { datasource = "payfrit" })>

  <cfset tasks = []>
  <cfloop query="qTasks">
    <cfset arrayAppend(tasks, {
      "TaskID": qTasks.TaskID,
      "TaskBusinessID": qTasks.TaskBusinessID,
      "TaskOrderID": qTasks.TaskOrderID,
      "TaskClaimedByUserID": qTasks.TaskClaimedByUserID,
      "TaskClaimedOn": isNull(qTasks.TaskClaimedOn) ? "NULL" : dateTimeFormat(qTasks.TaskClaimedOn, "yyyy-mm-dd HH:nn:ss"),
      "TaskCompletedOn": isNull(qTasks.TaskCompletedOn) ? "NULL" : dateTimeFormat(qTasks.TaskCompletedOn, "yyyy-mm-dd HH:nn:ss"),
      "OrderStatusID": isNull(qTasks.OrderStatusID) ? "NULL" : qTasks.OrderStatusID
    })>
  </cfloop>

  <cfset qStats = queryExecute("
    SELECT
      COUNT(*) as Total,
      SUM(CASE WHEN TaskClaimedByUserID > 0 AND TaskCompletedOn IS NULL THEN 1 ELSE 0 END) as ClaimedNotCompleted,
      SUM(CASE WHEN TaskClaimedByUserID = 0 OR TaskClaimedByUserID IS NULL THEN 1 ELSE 0 END) as Unclaimed,
      SUM(CASE WHEN TaskCompletedOn IS NOT NULL THEN 1 ELSE 0 END) as Completed
    FROM Tasks
  ", [], { datasource = "payfrit" })>

  <cfoutput>#serializeJSON({
    "OK": true,
    "TASKS": tasks,
    "STATS": {
      "Total": qStats.Total,
      "ClaimedNotCompleted": qStats.ClaimedNotCompleted,
      "Unclaimed": qStats.Unclaimed,
      "Completed": qStats.Completed
    }
  })#</cfoutput>

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