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

<cfparam name="url.orderid" default="0">

<cfset orderId = val(url.orderid)>

<cfif orderId LTE 0>
  <cfcontent type="application/json; charset=utf-8">
  <cfoutput>{"OK": false, "ERROR": "Please provide orderid in URL: ?orderid=300"}</cfoutput>
  <cfabort>
</cfif>

<cftry>
  <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 = ?
    ORDER BY oli.OrderLineItemID
  ", [ { value = 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,
      "OrderLineItemIsDeleted": qLineItems.OrderLineItemIsDeleted,
      "ItemName": qLineItems.ItemName,
      "ItemParentItemID": qLineItems.ItemParentItemID
    })>
  </cfloop>

  <cfcontent type="application/json; charset=utf-8">
  <cfoutput>#serializeJSON({
    "OK": true,
    "OrderID": orderId,
    "TotalLineItems": arrayLen(lineItems),
    "LineItems": lineItems
  })#</cfoutput>

  <cfcatch>
    <cfcontent type="application/json; charset=utf-8">
    <cfoutput>#serializeJSON({
      "OK": false,
      "ERROR": "db_error",
      "MESSAGE": cfcatch.message
    })#</cfoutput>
  </cfcatch>
</cftry>
