<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
        ID,
        UUID,
        UserID,
        BusinessID,
        DeliveryMultiplier,
        OrderTypeID,
        DeliveryFee,
        StatusID,
        AddressID,
        PaymentID,
        Remarks,
        AddedOn,
        LastEditedOn,
        SubmittedOn,
        ServicePointID
      FROM Orders
      WHERE ID = ?
      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 DeliveryFlatFee FROM Businesses WHERE ID = ? LIMIT 1",
    [ { value = qOrder.BusinessID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>
  <cfset var businessDeliveryFee = qBusiness.recordCount GT 0 ? qBusiness.DeliveryFlatFee : 0>

  <cfset out.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": val(qOrder.DeliveryFee),
    "BusinessDeliveryFee": val(businessDeliveryFee),
    "StatusID": val(qOrder.StatusID),
    "AddressID": val(qOrder.AddressID),
    "PaymentID": val(qOrder.PaymentID),
    "Remarks": qOrder.Remarks ?: "",
    "AddedOn": qOrder.AddedOn,
    "LastEditedOn": qOrder.LastEditedOn,
    "SubmittedOn": qOrder.SubmittedOn,
    "ServicePointID": val(qOrder.ServicePointID)
  }>

  <cfset var qLI = queryExecute(
    "
      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 = ?
      ORDER BY oli.ID
    ",
    [ { value = arguments.OrderID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>

  <cfset var rows = []>
  <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)
    })>
  </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: 0=undecided, 1=dine-in, 2=takeaway, 3=delivery --->
<cfif OrderTypeID LT 0 OR OrderTypeID GT 3>
  <cfset apiAbort({
    "OK": false,
    "ERROR": "invalid_order_type",
    "MESSAGE": "OrderTypeID must be 0 (undecided), 1 (dine-in), 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 ID, BusinessID, StatusID
      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>

  <cfif qOrder.StatusID 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 DeliveryFlatFee FROM Businesses WHERE ID = ? LIMIT 1",
      [ { value = qOrder.BusinessID, cfsqltype = "cf_sql_integer" } ],
      { datasource = "payfrit" }
    )>
    <cfif qBiz.recordCount GT 0>
      <cfset deliveryFee = qBiz.DeliveryFlatFee>
    </cfif>
  </cfif>

  <!--- Update order type and address --->
  <cftry>
    <cfif OrderTypeID EQ 3>
      <!--- Delivery: set address and fee --->
      <cfset queryExecute(
        "
          UPDATE Orders
          SET OrderTypeID = ?,
              AddressID = ?,
              DeliveryFee = ?,
              LastEditedOn = ?
          WHERE ID = ?
        ",
        [
          { value = OrderTypeID, cfsqltype = "cf_sql_integer" },
          { value = AddressID, cfsqltype = "cf_sql_integer" },
          { value = deliveryFee, cfsqltype = "cf_sql_decimal" },
          { value = now(), cfsqltype = "cf_sql_timestamp" },
          { value = OrderID, cfsqltype = "cf_sql_integer" }
        ],
        { datasource = "payfrit" }
      )>
    <cfelse>
      <!--- Takeaway/Dine-in: clear address and fee --->
      <cfset queryExecute(
        "
          UPDATE Orders
          SET OrderTypeID = ?,
              AddressID = NULL,
              DeliveryFee = 0,
              LastEditedOn = ?
          WHERE ID = ?
        ",
        [
          { value = OrderTypeID, cfsqltype = "cf_sql_integer" },
          { value = now(), cfsqltype = "cf_sql_timestamp" },
          { value = OrderID, cfsqltype = "cf_sql_integer" }
        ],
        { datasource = "payfrit" }
      )>
    </cfif>
    <cfcatch>
      <cfset apiAbort({
        "OK": false,
        "ERROR": "update_error",
        "MESSAGE": "Failed to update order type: " & cfcatch.message & " | SQL: " & (structKeyExists(cfcatch, "sql") ? cfcatch.sql : "none"),
        "DETAIL": cfcatch.message
      })>
    </cfcatch>
  </cftry>

  <!--- Return updated cart --->
  <cftry>
    <cfset payload = loadCartPayload(OrderID)>
    <cfset apiAbort(payload)>
    <cfcatch>
      <cfset apiAbort({
        "OK": false,
        "ERROR": "load_error",
        "MESSAGE": "Failed to load updated cart",
        "DETAIL": cfcatch.message
      })>
    </cfcatch>
  </cftry>

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