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

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

<cftry>
  <!--- Get the task and linked order details --->
  <cfset qTask = queryExecute("
    SELECT
      t.TaskID,
      t.TaskBusinessID,
      t.TaskCategoryID,
      t.TaskOrderID,
      t.TaskTypeID,
      t.TaskAddedOn,
      t.TaskClaimedByUserID,
      tc.TaskCategoryName,
      tc.TaskCategoryColor,
      o.OrderID,
      o.OrderUUID,
      o.OrderUserID,
      o.OrderTypeID,
      o.OrderStatusID,
      o.OrderServicePointID,
      o.OrderRemarks,
      o.OrderSubmittedOn,
      sp.ServicePointName,
      sp.ServicePointTypeID,
      u.UserID as CustomerUserID,
      u.UserFirstName,
      u.UserLastName,
      u.UserContactNumber
    FROM Tasks t
    LEFT JOIN TaskCategories tc ON tc.TaskCategoryID = t.TaskCategoryID
    LEFT JOIN Orders o ON o.OrderID = t.TaskOrderID
    LEFT JOIN ServicePoints sp ON sp.ServicePointID = o.OrderServicePointID
    LEFT JOIN Users u ON u.UserID = o.OrderUserID
    WHERE t.TaskID = ?
  ", [ { value = TaskID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

  <cfif qTask.recordCount EQ 0>
    <cfset apiAbort({ "OK": false, "ERROR": "not_found", "MESSAGE": "Task not found." })>
  </cfif>

  <!--- Build basic task info --->
  <cfset taskTitle = "Task ##" & qTask.TaskID>
  <cfif qTask.TaskOrderID GT 0>
    <cfset taskTitle = "Order ##" & qTask.TaskOrderID>
  </cfif>

  <!--- Check if user photo file exists (try both .jpg and .png) --->
  <cfset customerPhotoUrl = "">
  <cfif qTask.CustomerUserID GT 0>
    <cfset uploadDir = expandPath("/uploads/users/")>
    <cfset jpgPath = uploadDir & qTask.CustomerUserID & ".jpg">
    <cfset pngPath = uploadDir & qTask.CustomerUserID & ".png">
    <cfset pngPathUpper = uploadDir & qTask.CustomerUserID & ".PNG">
    <cfif fileExists(jpgPath)>
      <cfset customerPhotoUrl = "https://biz.payfrit.com/uploads/users/" & qTask.CustomerUserID & ".jpg">
    <cfelseif fileExists(pngPath)>
      <cfset customerPhotoUrl = "https://biz.payfrit.com/uploads/users/" & qTask.CustomerUserID & ".png">
    <cfelseif fileExists(pngPathUpper)>
      <cfset customerPhotoUrl = "https://biz.payfrit.com/uploads/users/" & qTask.CustomerUserID & ".PNG">
    </cfif>
  </cfif>

  <cfset result = {
    "TaskID": qTask.TaskID,
    "TaskBusinessID": qTask.TaskBusinessID,
    "TaskCategoryID": qTask.TaskCategoryID,
    "TaskTitle": taskTitle,
    "TaskCreatedOn": dateFormat(qTask.TaskAddedOn, "yyyy-mm-dd") & "T" & timeFormat(qTask.TaskAddedOn, "HH:mm:ss"),
    "TaskStatusID": qTask.TaskClaimedByUserID GT 0 ? 1 : 0,
    "TaskCategoryName": len(trim(qTask.TaskCategoryName)) ? qTask.TaskCategoryName : "General",
    "TaskCategoryColor": len(trim(qTask.TaskCategoryColor)) ? qTask.TaskCategoryColor : "##888888",
    "OrderID": qTask.OrderID ?: 0,
    "OrderRemarks": qTask.OrderRemarks ?: "",
    "OrderSubmittedOn": isDate(qTask.OrderSubmittedOn) ? (dateFormat(qTask.OrderSubmittedOn, "yyyy-mm-dd") & "T" & timeFormat(qTask.OrderSubmittedOn, "HH:mm:ss")) : "",
    "ServicePointID": qTask.OrderServicePointID ?: 0,
    "ServicePointName": qTask.ServicePointName ?: "",
    "ServicePointTypeID": qTask.ServicePointTypeID ?: 0,
    "DeliveryAddress": "",
    "DeliveryLat": 0,
    "DeliveryLng": 0,
    "CustomerUserID": qTask.CustomerUserID ?: 0,
    "CustomerFirstName": qTask.UserFirstName ?: "",
    "CustomerLastName": qTask.UserLastName ?: "",
    "CustomerPhone": qTask.UserContactNumber ?: "",
    "CustomerPhotoUrl": customerPhotoUrl,
    "BeaconUUID": "",
    "LineItems": []
  }>

  <!--- Get beacon UUID for the service point (for auto-completion on Works app) --->
  <cfif val(qTask.OrderServicePointID) GT 0>
    <cfset qBeacon = queryExecute("
      SELECT b.BeaconUUID
      FROM lt_Beacon_Businesses_ServicePoints lt
      INNER JOIN Beacons b ON b.BeaconID = lt.BeaconID
      WHERE lt.ServicePointID = ?
        AND b.BeaconIsActive = 1
      LIMIT 1
    ", [ { value = qTask.OrderServicePointID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>
    <cfif qBeacon.recordCount GT 0>
      <cfset result.BeaconUUID = qBeacon.BeaconUUID>
    </cfif>
  </cfif>

  <!--- Get order line items if there's an order --->
  <cfif qTask.OrderID GT 0>
    <cfset qLineItems = queryExecute("
      SELECT
        oli.OrderLineItemID,
        oli.OrderLineItemParentOrderLineItemID,
        oli.OrderLineItemItemID,
        oli.OrderLineItemPrice,
        oli.OrderLineItemQuantity,
        oli.OrderLineItemRemark,
        i.ItemID,
        i.ItemName,
        i.ItemParentItemID,
        i.ItemPrice,
        i.ItemIsCheckedByDefault
      FROM OrderLineItems oli
      INNER JOIN Items i ON i.ItemID = oli.OrderLineItemItemID
      WHERE oli.OrderLineItemOrderID = ?
        AND oli.OrderLineItemIsDeleted = b'0'
      ORDER BY oli.OrderLineItemID
    ", [ { value = qTask.OrderID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

    <cfloop query="qLineItems">
      <cfset arrayAppend(result.LineItems, {
        "LineItemID": qLineItems.OrderLineItemID,
        "ParentLineItemID": qLineItems.OrderLineItemParentOrderLineItemID,
        "ItemID": qLineItems.OrderLineItemItemID,
        "ItemName": qLineItems.ItemName,
        "ItemPrice": qLineItems.OrderLineItemPrice,
        "Quantity": qLineItems.OrderLineItemQuantity,
        "Remark": qLineItems.OrderLineItemRemark,
        "IsModifier": qLineItems.OrderLineItemParentOrderLineItemID GT 0
      })>
    </cfloop>
  </cfif>

  <cfset apiAbort({
    "OK": true,
    "ERROR": "",
    "TASK": result
  })>

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