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

<cfif OrderID LTE 0 OR NewStatusID LTE 0>
  <cfset apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "OrderID and StatusID are required.", "DETAIL": "" })>
</cfif>

<cftry>
  <!--- Verify order exists and get details --->
  <cfset qOrder = queryExecute("
    SELECT o.OrderID, o.OrderStatusID, o.OrderBusinessID, o.OrderServicePointID,
           sp.ServicePointName
    FROM Orders o
    LEFT JOIN ServicePoints sp ON sp.ServicePointID = o.OrderServicePointID
    WHERE o.OrderID = ?
    LIMIT 1
  ", [ { value = OrderID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

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

  <cfset oldStatusID = qOrder.OrderStatusID>

  <!--- Update status --->
  <cfset queryExecute("
    UPDATE Orders
    SET OrderStatusID = ?,
        OrderLastEditedOn = ?
    WHERE OrderID = ?
  ", [
    { value = NewStatusID, cfsqltype = "cf_sql_integer" },
    { value = now(), cfsqltype = "cf_sql_timestamp" },
    { value = OrderID, cfsqltype = "cf_sql_integer" }
  ], { datasource = "payfrit" })>

  <!--- Create delivery task when order is marked as Ready (status 3) --->
  <cfset taskCreated = false>
  <cfif NewStatusID EQ 3 AND oldStatusID NEQ 3>
    <cftry>
      <!--- Check if task already exists for this order to prevent duplicates --->
      <cfset qExisting = queryExecute("
        SELECT TaskID FROM Tasks WHERE TaskOrderID = ? LIMIT 1
      ", [ { value = OrderID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

      <cfif qExisting.recordCount EQ 0>
        <cfset queryExecute("
          INSERT INTO Tasks (
            TaskBusinessID,
            TaskOrderID,
            TaskTypeID,
            TaskClaimedByUserID,
            TaskAddedOn
          ) VALUES (
            ?,
            ?,
            1,
            0,
            NOW()
          )
        ", [
          { value = qOrder.OrderBusinessID, cfsqltype = "cf_sql_integer" },
          { value = OrderID, cfsqltype = "cf_sql_integer" }
        ], { datasource = "payfrit" })>
        <cfset taskCreated = true>
      </cfif>
      <cfcatch>
        <!--- Task creation failed, but don't fail the status update --->
      </cfcatch>
    </cftry>
  </cfif>

  <cfset apiAbort({
    "OK": true,
    "ERROR": "",
    "MESSAGE": "Order status updated successfully.",
    "OrderID": OrderID,
    "StatusID": NewStatusID,
    "TaskCreated": taskCreated
  })>

  <cfcatch>
    <cfset apiAbort({
      "OK": false,
      "ERROR": "server_error",
      "MESSAGE": "DB error updating order status",
      "DETAIL": cfcatch.message
    })>
  </cfcatch>
</cftry>
