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

  <!--- Get business delivery fee for display in cart --->
  <cfset var qBusiness = queryExecute(
    "SELECT BusinessDeliveryFlatFee FROM Businesses WHERE BusinessID = ? LIMIT 1",
    [ { value = qOrder.OrderBusinessID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>
  <cfset var businessDeliveryFee = qBusiness.recordCount GT 0 ? qBusiness.BusinessDeliveryFlatFee : 0>

  <cfset out.Order = {
    "OrderID": qOrder.OrderID,
    "OrderUUID": qOrder.OrderUUID,
    "OrderUserID": qOrder.OrderUserID,
    "OrderBusinessID": qOrder.OrderBusinessID,
    "OrderBusinessDeliveryMultiplier": qOrder.OrderBusinessDeliveryMultiplier,
    "OrderTypeID": qOrder.OrderTypeID,
    "OrderDeliveryFee": qOrder.OrderDeliveryFee,
    "BusinessDeliveryFee": businessDeliveryFee,
    "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 OrderID = val( structKeyExists(data,"OrderID") ? data.OrderID : 0 )>
<cfset OrderTypeID = val( structKeyExists(data,"OrderTypeID") ? data.OrderTypeID : 0 )>
<cfset AddressID = structKeyExists(data,"AddressID") ? val(data.AddressID) : 0>

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

<!--- OrderTypeID: 2=takeaway, 3=delivery --->
<cfif OrderTypeID LT 2 OR OrderTypeID GT 3>
  <cfset apiAbort({
    "OK": false,
    "ERROR": "invalid_order_type",
    "MESSAGE": "OrderTypeID must be 2 (takeaway) or 3 (delivery).",
    "DETAIL": ""
  })>
</cfif>

<!--- Delivery requires address --->
<cfif OrderTypeID EQ 3 AND AddressID LTE 0>
  <cfset apiAbort({
    "OK": false,
    "ERROR": "missing_address",
    "MESSAGE": "Delivery orders require an AddressID.",
    "DETAIL": ""
  })>
</cfif>

<cftry>
  <!--- Verify order exists and is still a cart (status 0) --->
  <cfset qOrder = queryExecute(
    "
      SELECT OrderID, OrderBusinessID, OrderStatusID
      FROM Orders
      WHERE OrderID = ?
      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>

  <cfif qOrder.OrderStatusID NEQ 0>
    <cfset apiAbort({ "OK": false, "ERROR": "invalid_status", "MESSAGE": "Order type can only be changed while in cart status.", "DETAIL": "" })>
  </cfif>

  <!--- Get delivery fee from business if delivery --->
  <cfset deliveryFee = 0>
  <cfif OrderTypeID EQ 3>
    <cfset qBiz = queryExecute(
      "SELECT BusinessDeliveryFlatFee FROM Businesses WHERE BusinessID = ? LIMIT 1",
      [ { value = qOrder.OrderBusinessID, cfsqltype = "cf_sql_integer" } ],
      { datasource = "payfrit" }
    )>
    <cfif qBiz.recordCount GT 0>
      <cfset deliveryFee = qBiz.BusinessDeliveryFlatFee>
    </cfif>
  </cfif>

  <!--- Update order type and address --->
  <cfset queryExecute(
    "
      UPDATE Orders
      SET OrderTypeID = ?,
          OrderAddressID = ?,
          OrderDeliveryFee = ?,
          OrderLastEditedOn = ?
      WHERE OrderID = ?
    ",
    [
      { value = OrderTypeID, cfsqltype = "cf_sql_integer" },
      { value = (OrderTypeID EQ 3 ? AddressID : javaCast("null", "")), cfsqltype = "cf_sql_integer", null = (OrderTypeID NEQ 3) },
      { value = deliveryFee, cfsqltype = "cf_sql_decimal" },
      { value = now(), cfsqltype = "cf_sql_timestamp" },
      { value = OrderID, cfsqltype = "cf_sql_integer" }
    ],
    { datasource = "payfrit" }
  )>

  <!--- Return updated cart --->
  <cfset payload = loadCartPayload(OrderID)>
  <cfset apiAbort(payload)>

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