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

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

<cftry>
  <!--- Build WHERE clause for filtering --->
  <cfset whereClauses = ["o.OrderBusinessID = ?"]>
  <cfset params = [ { value = BusinessID, cfsqltype = "cf_sql_integer" } ]>

  <!--- Filter by service point if provided --->
  <cfif ServicePointID GT 0>
    <cfset arrayAppend(whereClauses, "o.OrderServicePointID = ?")>
    <cfset arrayAppend(params, { value = ServicePointID, cfsqltype = "cf_sql_integer" })>
  </cfif>

  <!--- Only show submitted orders (StatusID >= 1) --->
  <cfset arrayAppend(whereClauses, "o.OrderStatusID >= 1")>

  <!--- Don't show completed orders (assuming StatusID 4 is completed) --->
  <cfset arrayAppend(whereClauses, "o.OrderStatusID < 4")>

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

  <cfset qOrders = queryExecute("
    SELECT
      o.OrderID,
      o.OrderUUID,
      o.OrderUserID,
      o.OrderBusinessID,
      o.OrderTypeID,
      o.OrderStatusID,
      o.OrderServicePointID,
      o.OrderRemarks,
      o.OrderSubmittedOn,
      o.OrderLastEditedOn,
      sp.ServicePointName,
      u.UserFirstName,
      u.UserLastName
    FROM Orders o
    LEFT JOIN ServicePoints sp ON sp.ServicePointID = o.OrderServicePointID
    LEFT JOIN Users u ON u.UserID = o.OrderUserID
    WHERE #whereSQL#
    ORDER BY o.OrderSubmittedOn ASC, o.OrderID ASC
  ", params, { datasource = "payfrit" })>

  <cfset orders = []>

  <cfloop query="qOrders">
    <!--- Get line items for this order --->
    <cfset qLineItems = queryExecute("
      SELECT
        oli.OrderLineItemID,
        oli.OrderLineItemParentOrderLineItemID,
        oli.OrderLineItemItemID,
        oli.OrderLineItemPrice,
        oli.OrderLineItemQuantity,
        oli.OrderLineItemRemark,
        oli.OrderLineItemIsDeleted,
        i.ItemName,
        i.ItemParentItemID
      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 = qOrders.OrderID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

    <cfset lineItems = []>
    <cfloop query="qLineItems">
      <cfset arrayAppend(lineItems, {
        "OrderLineItemID": qLineItems.OrderLineItemID,
        "OrderLineItemParentOrderLineItemID": qLineItems.OrderLineItemParentOrderLineItemID,
        "OrderLineItemItemID": qLineItems.OrderLineItemItemID,
        "OrderLineItemPrice": qLineItems.OrderLineItemPrice,
        "OrderLineItemQuantity": qLineItems.OrderLineItemQuantity,
        "OrderLineItemRemark": qLineItems.OrderLineItemRemark,
        "ItemName": qLineItems.ItemName,
        "ItemParentItemID": qLineItems.ItemParentItemID
      })>
    </cfloop>

    <cfset arrayAppend(orders, {
      "OrderID": qOrders.OrderID,
      "OrderUUID": qOrders.OrderUUID,
      "OrderUserID": qOrders.OrderUserID,
      "OrderBusinessID": qOrders.OrderBusinessID,
      "OrderTypeID": qOrders.OrderTypeID,
      "OrderStatusID": qOrders.OrderStatusID,
      "OrderServicePointID": qOrders.OrderServicePointID,
      "OrderRemarks": qOrders.OrderRemarks,
      "OrderSubmittedOn": qOrders.OrderSubmittedOn,
      "OrderLastEditedOn": qOrders.OrderLastEditedOn,
      "ServicePointName": qOrders.ServicePointName,
      "UserFirstName": qOrders.UserFirstName,
      "UserLastName": qOrders.UserLastName,
      "LineItems": lineItems
    })>
  </cfloop>

  <cfset apiAbort({
    "OK": true,
    "ERROR": "",
    "ORDERS": orders
  })>

  <cfcatch>
    <cfset apiAbort({
      "OK": false,
      "ERROR": "server_error",
      "MESSAGE": "DB error loading orders for KDS",
      "DETAIL": cfcatch.message
    })>
  </cfcatch>
</cftry>
