<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 = queryTimed("
    SELECT
      oli.ID,
      oli.ParentOrderLineItemID,
      oli.ItemID,
      oli.Price,
      oli.Quantity,
      oli.Remark,
      oli.IsDeleted,
      i.Name,
      i.ParentItemID
    FROM OrderLineItems oli
    INNER JOIN Items i ON i.ID = oli.ItemID
    WHERE oli.OrderID = ?
    ORDER BY oli.ID
  ", [ { value = orderId, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

  <cfset lineItems = []>
  <cfloop query="qLineItems">
    <cfset arrayAppend(lineItems, {
      "OrderLineItemID": qLineItems.ID,
      "ParentOrderLineItemID": qLineItems.ParentOrderLineItemID,
      "ItemID": qLineItems.ID,
      "Price": qLineItems.Price,
      "Quantity": qLineItems.Quantity,
      "Remark": qLineItems.Remark,
      "IsDeleted": qLineItems.IsDeleted,
      "Name": qLineItems.Name,
      "ParentItemID": qLineItems.ParentItemID
    })>
  </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>
