<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">

<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>

<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="loadCartPayload" access="public" returntype="struct" output="false">
  <cfargument name="OrderID" type="numeric" required="true">

  <cfset var out = {}>
  <cfset var qOrder = queryExecute(
    "
      SELECT
        OrderID,
        OrderUUID,
        OrderUserID,
        OrderBusinessID,
        OrderBusinessDeliveryMultiplier,
        OrderTypeID,
        OrderDeliveryFee,
        OrderStatusID,
        OrderAddressID,
        OrderPaymentID,
        OrderRemarks,
        OrderAddedOn,
        OrderLastEditedOn,
        OrderSubmittedOn,
        OrderServicePointID
      FROM Orders
      WHERE OrderID = ?
      LIMIT 1
    ",
    [ { value = arguments.OrderID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>

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

  <cfset out.Order = {
    "OrderID": qOrder.OrderID,
    "OrderUUID": qOrder.OrderUUID,
    "OrderUserID": qOrder.OrderUserID,
    "OrderBusinessID": qOrder.OrderBusinessID,
    "OrderBusinessDeliveryMultiplier": qOrder.OrderBusinessDeliveryMultiplier,
    "OrderTypeID": qOrder.OrderTypeID,
    "OrderDeliveryFee": qOrder.OrderDeliveryFee,
    "OrderStatusID": qOrder.OrderStatusID,
    "OrderAddressID": qOrder.OrderAddressID,
    "OrderPaymentID": qOrder.OrderPaymentID,
    "OrderRemarks": qOrder.OrderRemarks,
    "OrderAddedOn": qOrder.OrderAddedOn,
    "OrderLastEditedOn": qOrder.OrderLastEditedOn,
    "OrderSubmittedOn": qOrder.OrderSubmittedOn,
    "OrderServicePointID": qOrder.OrderServicePointID
  }>

  <cfset var qLI = queryExecute(
    "
      SELECT
        OrderLineItemID,
        OrderLineItemParentOrderLineItemID,
        OrderLineItemOrderID,
        OrderLineItemItemID,
        OrderLineItemStatusID,
        OrderLineItemPrice,
        OrderLineItemQuantity,
        OrderLineItemRemark,
        OrderLineItemIsDeleted,
        OrderLineItemAddedOn
      FROM OrderLineItems
      WHERE OrderLineItemOrderID = ?
      ORDER BY OrderLineItemID
    ",
    [ { value = arguments.OrderID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>

  <cfset var rows = []>
  <cfloop query="qLI">
    <cfset arrayAppend(rows, {
      "OrderLineItemID": qLI.OrderLineItemID,
      "OrderLineItemParentOrderLineItemID": qLI.OrderLineItemParentOrderLineItemID,
      "OrderLineItemOrderID": qLI.OrderLineItemOrderID,
      "OrderLineItemItemID": qLI.OrderLineItemItemID,
      "OrderLineItemStatusID": qLI.OrderLineItemStatusID,
      "OrderLineItemPrice": qLI.OrderLineItemPrice,
      "OrderLineItemQuantity": qLI.OrderLineItemQuantity,
      "OrderLineItemRemark": qLI.OrderLineItemRemark,
      "OrderLineItemIsDeleted": qLI.OrderLineItemIsDeleted,
      "OrderLineItemAddedOn": qLI.OrderLineItemAddedOn
    })>
  </cfloop>

  <cfset out.OrderLineItems = rows>
  <cfset out.OK = true>
  <cfset out.ERROR = "">
  <cfreturn out>
</cffunction>

<cfset data = readJsonBody()>

<cfset BusinessID = val( structKeyExists(data,"BusinessID") ? data.BusinessID : 0 )>
<cfset OrderServicePointID = val( structKeyExists(data,"OrderServicePointID") ? data.OrderServicePointID : 0 )>
<cfset OrderTypeID = val( structKeyExists(data,"OrderTypeID") ? data.OrderTypeID : 0 )>
<cfset OrderUserID = val( structKeyExists(data,"OrderUserID") ? data.OrderUserID : 0 )>

<cfif BusinessID LTE 0 OR OrderServicePointID LTE 0 OR OrderTypeID NEQ 1 OR OrderUserID LTE 0>
  <cfset apiAbort({
    "OK": false,
    "ERROR": "missing_params",
    "MESSAGE": "BusinessID, OrderServicePointID, OrderTypeID=1, and OrderUserID are required.",
    "DETAIL": ""
  })>
</cfif>

<cftry>
  <!--- Find existing cart (OrderStatusID=0 assumed cart) --->
  <cfset qFind = queryExecute(
    "
      SELECT OrderID
      FROM Orders
      WHERE OrderUserID = ?
        AND OrderBusinessID = ?
        AND OrderTypeID = 1
        AND OrderStatusID = 0
        AND OrderServicePointID = ?
      ORDER BY OrderID DESC
      LIMIT 1
    ",
    [
      { value = OrderUserID, cfsqltype = "cf_sql_integer" },
      { value = BusinessID, cfsqltype = "cf_sql_integer" },
      { value = OrderServicePointID, cfsqltype = "cf_sql_integer" }
    ],
    { datasource = "payfrit" }
  )>

  <cfif qFind.recordCount GT 0>
    <cfset payload = loadCartPayload(qFind.OrderID)>
    <cfset apiAbort(payload)>
  </cfif>

  <!--- Create new cart order --->
  <cfset qBiz = queryExecute(
    "
      SELECT BusinessDeliveryMultiplier, BusinessDeliveryFlatFee
      FROM Businesses
      WHERE BusinessID = ?
      LIMIT 1
    ",
    [ { value = BusinessID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>

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

  <cfset nowDt = now()>
  <cfset newUUID = createUUID()>

  <!--- Generate new OrderID (table is not auto-inc in SSOT) --->
  <cfset qNext = queryExecute(
    "SELECT IFNULL(MAX(OrderID),0) + 1 AS NextID FROM Orders",
    [],
    { datasource = "payfrit" }
  )>
  <cfset NewOrderID = qNext.NextID>

  <cfset queryExecute(
    "
      INSERT INTO Orders (
        OrderID,
        OrderUUID,
        OrderUserID,
        OrderBusinessID,
        OrderBusinessDeliveryMultiplier,
        OrderTypeID,
        OrderDeliveryFee,
        OrderStatusID,
        OrderAddressID,
        OrderPaymentID,
        OrderRemarks,
        OrderAddedOn,
        OrderLastEditedOn,
        OrderSubmittedOn,
        OrderServicePointID
      ) VALUES (
        ?,
        ?,
        ?,
        ?,
        ?,
        1,
        ?,
        0,
        NULL,
        NULL,
        NULL,
        ?,
        ?,
        NULL,
        ?
      )
    ",
    [
      { value = NewOrderID, cfsqltype = "cf_sql_integer" },
      { value = newUUID, cfsqltype = "cf_sql_varchar" },
      { value = OrderUserID, cfsqltype = "cf_sql_integer" },
      { value = BusinessID, cfsqltype = "cf_sql_integer" },
      { value = qBiz.BusinessDeliveryMultiplier, cfsqltype = "cf_sql_decimal" },
      { value = qBiz.BusinessDeliveryFlatFee, cfsqltype = "cf_sql_decimal" },
      { value = nowDt, cfsqltype = "cf_sql_timestamp" },
      { value = nowDt, cfsqltype = "cf_sql_timestamp" },
      { value = OrderServicePointID, cfsqltype = "cf_sql_integer" }
    ],
    { datasource = "payfrit" }
  )>

  <!--- Per your rule: OrderID is determined by selecting highest after creation --->
  <cfset qLatest = queryExecute(
    "SELECT MAX(OrderID) AS OrderID FROM Orders",
    [],
    { datasource = "payfrit" }
  )>
  <cfset FinalOrderID = qLatest.OrderID>

  <cfset payload = loadCartPayload(FinalOrderID)>
  <cfset apiAbort(payload)>

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