<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.ID, o.StatusID, o.BusinessID, o.ServicePointID,
           sp.Name AS Name
    FROM Orders o
    LEFT JOIN ServicePoints sp ON sp.ID = o.ServicePointID
    WHERE o.ID = ?
    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.StatusID>

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

  <!---
    Order Status Flow:
    0 = Cart
    1 = Submitted (paid via Stripe/other payment, or added to tab)
    2 = In Progress (Kitchen preparing)
    3 = Order Complete, Final Prep (Kitchen done, create delivery/pickup task)
    4 = Claimed (Worker claimed task - delivering to table, out for delivery, or notifying customer for pickup)
    5 = Delivered/Complete
    6 = Cancelled
    7 = Deleted (user abandoned cart and started new one)

    Task Types (auto-created at status 3):
    - Dine-in:   "Deliver Order #X to <Service Point>"
    - Takeaway:  "Prepare Order #X for customer pickup"
    - Delivery:  "Prepare Order #X for delivery worker pickup"

    Other system tasks (manually created or scheduled):
    - "Go to <Service Point>" (customer call server)
    - "Customer Chat"
    - Scheduled: "Clean Men's Washroom", "Clean Women's Restroom", "Silverware roll-ups", "Check Floor", "Check garbage cans", etc.
  --->

  <!--- Create delivery/pickup task when order moves to status 3 (Final Prep) --->
  <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 ID FROM Tasks WHERE ID = ? LIMIT 1
      ", [ { value = OrderID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

      <cfif qExisting.recordCount EQ 0>
        <!--- Get order type --->
        <cfset qOrderDetails = queryExecute("
          SELECT o.OrderTypeID
          FROM Orders o
          WHERE o.ID = ?
        ", [ { value = OrderID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

        <cfset orderTypeID = qOrderDetails.recordCount GT 0 ? val(qOrderDetails.OrderTypeID) : 1>

        <!--- OrderTypeID: 1=dine-in, 2=takeaway, 3=delivery --->
        <cfif orderTypeID EQ 1>
          <!--- Dine-in: Server delivers to service point --->
          <cfset tableName = len(qOrder.Name) ? qOrder.Name : "Table">
          <cfset taskTitle = "Deliver Order ###OrderID# to " & tableName>
          <cfset taskCategoryID = 3>
        <cfelseif orderTypeID EQ 2>
          <!--- Takeaway: Expo task to notify customer order is ready --->
          <cfset taskTitle = "Order ###OrderID# Ready for Pickup - Notify Customer">
          <cfset taskCategoryID = 4> <!--- Expo/Pickup category --->
        <cfelseif orderTypeID EQ 3>
          <!--- Delivery: Hand off to delivery driver --->
          <cfset taskTitle = "Order ###OrderID# Ready for Delivery Driver">
          <cfset taskCategoryID = 5> <!--- Delivery category --->
        <cfelse>
          <cfset taskTitle = "">
        </cfif>

        <cfif len(taskTitle)>
          <cfset queryExecute("
            INSERT INTO Tasks (
              BusinessID,
              OrderID,
              TaskTypeID,
              CategoryID,
              Title,
              ClaimedByUserID,
              CreatedOn
            ) VALUES (
              ?,
              ?,
              1,
              ?,
              ?,
              0,
              NOW()
            )
          ", [
            { value = qOrder.BusinessID, cfsqltype = "cf_sql_integer" },
            { value = OrderID, cfsqltype = "cf_sql_integer" },
            { value = taskCategoryID, cfsqltype = "cf_sql_integer" },
            { value = taskTitle, cfsqltype = "cf_sql_varchar" }
          ], { datasource = "payfrit" })>
          <cfset taskCreated = true>
        </cfif>
      </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>
