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

<cfset data = readJsonBody()>
<cfset OrderID = val( structKeyExists(data,"OrderID") ? data.OrderID : 0 )>

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

<cftry>
  <cfset qOrder = queryTimed(
    "
      SELECT
        ID,
        UUID,
        UserID,
        BusinessID,
        DeliveryMultiplier,
        OrderTypeID,
        DeliveryFee,
        StatusID,
        AddressID,
        PaymentID,
        PaymentStatus,
        Remarks,
        AddedOn,
        LastEditedOn,
        SubmittedOn,
        ServicePointID
      FROM Orders
      WHERE 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>

  <!--- Get business info for display in cart --->
  <cfset qBusiness = queryTimed(
    "SELECT DeliveryFlatFee, OrderTypes, TaxRate, PayfritFee FROM Businesses WHERE ID = ? LIMIT 1",
    [ { value = qOrder.BusinessID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>
  <cfset businessDeliveryFee = qBusiness.recordCount GT 0 ? qBusiness.DeliveryFlatFee : 0>
  <cfset businessTaxRate = qBusiness.recordCount GT 0 AND isNumeric(qBusiness.TaxRate) ? qBusiness.TaxRate : 0>
  <cfset businessPayfritFee = qBusiness.recordCount GT 0 AND isNumeric(qBusiness.PayfritFee) ? qBusiness.PayfritFee : 0.05>
  <cfset businessOrderTypes = qBusiness.recordCount GT 0 AND len(trim(qBusiness.OrderTypes)) ? qBusiness.OrderTypes : "1,2,3">
  <cfset businessOrderTypesArray = listToArray(businessOrderTypes, ",")>

  <cfset qLI = queryTimed(
    "
      SELECT
        oli.ID,
        oli.ParentOrderLineItemID,
        oli.OrderID,
        oli.ItemID,
        oli.StatusID,
        oli.Price,
        oli.Quantity,
        oli.Remark,
        oli.IsDeleted,
        oli.AddedOn,
        i.Name,
        i.ParentItemID,
        i.IsCheckedByDefault,
        parent.Name AS ItemParentName
      FROM OrderLineItems oli
      INNER JOIN Items i ON i.ID = oli.ItemID
      LEFT JOIN Items parent ON parent.ID = i.ParentItemID
      WHERE oli.OrderID = ?
        AND oli.IsDeleted = 0
      ORDER BY oli.ID
    ",
    [ { value = OrderID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>

  <cfset rows = []>
  <cfset subtotal = 0>
  <cfloop query="qLI">
    <cfset arrayAppend(rows, {
      "OrderLineItemID": val(qLI.ID),
      "ParentOrderLineItemID": val(qLI.ParentOrderLineItemID),
      "OrderID": val(qLI.OrderID),
      "ItemID": val(qLI.ItemID),
      "StatusID": val(qLI.StatusID),
      "Price": val(qLI.Price),
      "Quantity": val(qLI.Quantity),
      "Remark": qLI.Remark ?: "",
      "IsDeleted": val(qLI.IsDeleted),
      "AddedOn": qLI.AddedOn,
      "Name": qLI.Name ?: "",
      "ParentItemID": val(qLI.ParentItemID),
      "ItemParentName": qLI.ItemParentName ?: "",
      "IsCheckedByDefault": val(qLI.IsCheckedByDefault)
    })>
    <!--- Add to subtotal (root items only - modifiers are included in parent price) --->
    <cfif val(qLI.ParentOrderLineItemID) EQ 0>
      <cfset subtotal = subtotal + (val(qLI.Price) * val(qLI.Quantity))>
    </cfif>
  </cfloop>

  <!--- Calculate tax (no default - business must configure their rate) --->
  <cfset taxAmount = subtotal * val(businessTaxRate)>
  <cfset deliveryFee = val(qOrder.OrderTypeID) EQ 3 ? val(qOrder.DeliveryFee) : 0>
  <cfset total = subtotal + taxAmount + deliveryFee>

  <cfset apiAbort({
    "OK": true,
    "ERROR": "",
    "ORDER": {
      "OrderID": val(qOrder.ID),
      "UUID": qOrder.UUID ?: "",
      "UserID": val(qOrder.UserID),
      "BusinessID": val(qOrder.BusinessID),
      "DeliveryMultiplier": val(qOrder.DeliveryMultiplier),
      "OrderTypeID": val(qOrder.OrderTypeID),
      "DeliveryFee": deliveryFee,
      "BusinessDeliveryFee": val(businessDeliveryFee),
      "TaxRate": val(businessTaxRate),
      "PayfritFee": val(businessPayfritFee),
      "Subtotal": subtotal,
      "Tax": taxAmount,
      "Total": total,
      "OrderTypes": businessOrderTypesArray,
      "StatusID": val(qOrder.StatusID),
      "AddressID": val(qOrder.AddressID),
      "PaymentID": val(qOrder.PaymentID),
      "PaymentStatus": qOrder.PaymentStatus ?: "",
      "Remarks": qOrder.Remarks ?: "",
      "AddedOn": qOrder.AddedOn,
      "LastEditedOn": qOrder.LastEditedOn,
      "SubmittedOn": qOrder.SubmittedOn,
      "ServicePointID": val(qOrder.ServicePointID)
    },
    "ORDERLINEITEMS": rows
  })>

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