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

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

<cftry>
  <!--- Get business name --->
  <cfset qBusiness = queryTimed("
    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 and incomplete tasks only --->
  <cfset whereClauses = ["t.BusinessID = ?", "t.ClaimedByUserID = 0", "t.CompletedOn IS NULL"]>
  <cfset params = [ { value = BusinessID, cfsqltype = "cf_sql_integer" } ]>

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

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

  <cfset qTasks = queryTimed("
    SELECT
      t.ID,
      t.BusinessID,
      t.OrderID,
      t.TaskTypeID,
      t.Title,
      t.Details,
      t.CreatedOn,
      t.ClaimedByUserID,
      t.UserID,
      tt.Name AS TaskTypeName,
      tt.Icon AS TaskTypeIcon,
      tt.Color AS TaskTypeColor,
      t.ServicePointID,
      sp.Name AS ServicePointName,
      u.FirstName AS CustomerFirstName,
      u.LastName AS CustomerLastName
    FROM Tasks t
    LEFT JOIN tt_TaskTypes tt ON tt.ID = t.TaskTypeID
    LEFT JOIN Orders o ON o.ID = t.OrderID
    LEFT JOIN ServicePoints sp ON sp.ID = COALESCE(t.ServicePointID, o.ServicePointID)
    LEFT JOIN Users u ON u.ID = t.UserID
    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 customerName = "">
    <cfif NOT isNull(qTasks.CustomerFirstName) AND len(trim(qTasks.CustomerFirstName))>
      <cfset customerName = qTasks.CustomerFirstName>
      <cfif NOT isNull(qTasks.CustomerLastName) AND len(trim(qTasks.CustomerLastName))>
        <cfset customerName = customerName & " " & qTasks.CustomerLastName>
      </cfif>
    </cfif>

    <cfset arrayAppend(tasks, {
      "TaskID": qTasks.ID,
      "BusinessID": qTasks.BusinessID,
      "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,
      "TaskTypeName": len(trim(qTasks.TaskTypeName)) ? qTasks.TaskTypeName : "",
      "TaskTypeIcon": len(trim(qTasks.TaskTypeIcon)) ? qTasks.TaskTypeIcon : "notifications",
      "TaskTypeColor": len(trim(qTasks.TaskTypeColor)) ? qTasks.TaskTypeColor : "##9C27B0",
      "ServicePointID": val(qTasks.ServicePointID),
      "ServicePointName": isNull(qTasks.ServicePointName) ? "" : qTasks.ServicePointName,
      "CustomerID": val(qTasks.UserID),
      "CustomerName": customerName
    })>
  </cfloop>

  <!--- Calculate OrderTotal for tasks with linked orders --->
  <cfloop from="1" to="#arrayLen(tasks)#" index="i">
    <cfif val(tasks[i].SourceID) GT 0>
      <cfset qOT = queryTimed("
        SELECT SUM(oli.Price * oli.Quantity) AS Subtotal, o.TipAmount, o.DeliveryFee, o.OrderTypeID, b.TaxRate
        FROM Orders o
        INNER JOIN Businesses b ON b.ID = o.BusinessID
        LEFT JOIN OrderLineItems oli ON oli.OrderID = o.ID AND oli.IsDeleted = b'0'
        WHERE o.ID = ?
        GROUP BY o.ID
      ", [{ value = tasks[i].SourceID, cfsqltype = "cf_sql_integer" }], { datasource = "payfrit" })>
      <cfif qOT.recordCount GT 0>
        <cfset sub = val(qOT.Subtotal)>
        <cfset tasks[i]["OrderTotal"] = numberFormat(sub + (sub * val(qOT.TaxRate)) + val(qOT.TipAmount) + ((val(qOT.OrderTypeID) EQ 3) ? val(qOT.DeliveryFee) : 0) + (sub * 0.05), "0.00")>
      <cfelse>
        <cfset tasks[i]["OrderTotal"] = 0>
      </cfif>
    <cfelse>
      <cfset tasks[i]["OrderTotal"] = 0>
    </cfif>
  </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>
