<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 = queryTimed(
    "
      SELECT
        ID,
        UUID,
        UserID,
        BusinessID,
        DeliveryMultiplier,
        OrderTypeID,
        DeliveryFee,
        StatusID,
        AddressID,
        PaymentID,
        Remarks,
        AddedOn,
        LastEditedOn,
        SubmittedOn,
        ServicePointID,
        GrantID,
        GrantOwnerBusinessID,
        GrantEconomicsType,
        GrantEconomicsValue
      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 and tax rate for display in cart --->
  <cfset var qBusiness = queryTimed(
    "SELECT DeliveryFlatFee, TaxRate 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 var businessTaxRate = qBusiness.recordCount GT 0 AND isNumeric(qBusiness.TaxRate) ? qBusiness.TaxRate : 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),
    "TaxRate": val(businessTaxRate),
    "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),
    "GrantID": val(qOrder.GrantID),
    "GrantOwnerBusinessID": val(qOrder.GrantOwnerBusinessID),
    "GrantEconomicsType": qOrder.GrantEconomicsType ?: "",
    "GrantEconomicsValue": val(qOrder.GrantEconomicsValue)
  }>

  <cfset var 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 = ?
      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>

<cfinclude template="../grants/_grantUtils.cfm">
<cfset data = readJsonBody()>

<cfset BusinessID = val( structKeyExists(data,"BusinessID") ? data.BusinessID : 0 )>
<cfset ServicePointID = val( structKeyExists(data,"ServicePointID") ? data.ServicePointID : 0 )>
<cfset OrderTypeID = val( structKeyExists(data,"OrderTypeID") ? data.OrderTypeID : 0 )>
<cfset UserID = val( structKeyExists(data,"UserID") ? data.UserID : 0 )>

<!--- OrderTypeID: 0=undecided, 1=dine-in, 2=takeaway, 3=delivery --->
<cfif BusinessID LTE 0 OR UserID LTE 0>
  <cfset apiAbort({
    "OK": false,
    "ERROR": "missing_params",
    "MESSAGE": "BusinessID and UserID are required.",
    "DETAIL": ""
  })>
</cfif>

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

<cftry>
  <!--- Find existing cart (StatusID=0 assumed cart) --->
  <!--- Look for any active cart for this user/business - order type can be changed later --->
  <cfset qFind = queryTimed(
    "
      SELECT ID, OrderTypeID
      FROM Orders
      WHERE UserID = ?
        AND BusinessID = ?
        AND StatusID = 0
      ORDER BY ID DESC
      LIMIT 1
    ",
    [
      { value = UserID, cfsqltype = "cf_sql_integer" },
      { value = BusinessID, cfsqltype = "cf_sql_integer" }
    ],
    { datasource = "payfrit" }
  )>

  <cfif qFind.recordCount GT 0>
    <!--- Always update the service point to match the current table/beacon --->
    <cfif ServicePointID GT 0>
      <cfset queryTimed(
        "UPDATE Orders SET ServicePointID = ?, LastEditedOn = ? WHERE ID = ?",
        [
          { value = ServicePointID, cfsqltype = "cf_sql_integer" },
          { value = now(), cfsqltype = "cf_sql_timestamp" },
          { value = qFind.ID, cfsqltype = "cf_sql_integer" }
        ],
        { datasource = "payfrit" }
      )>
    </cfif>

    <!--- Check if cart order type differs from requested and cart is empty --->
    <!--- If so, update the cart's order type to match the new flow --->
    <cfif qFind.OrderTypeID NEQ OrderTypeID>
      <cfset qLineItems = queryTimed(
        "SELECT COUNT(*) AS ItemCount FROM OrderLineItems WHERE OrderID = ? AND IsDeleted = 0",
        [ { value = qFind.ID, cfsqltype = "cf_sql_integer" } ],
        { datasource = "payfrit" }
      )>
      <!--- Only update order type if cart is empty (allows switching flows) --->
      <cfif qLineItems.ItemCount EQ 0>
        <cfset queryTimed(
          "UPDATE Orders SET OrderTypeID = ?, LastEditedOn = ? WHERE ID = ?",
          [
            { value = OrderTypeID, cfsqltype = "cf_sql_integer" },
            { value = now(), cfsqltype = "cf_sql_timestamp" },
            { value = qFind.ID, cfsqltype = "cf_sql_integer" }
          ],
          { datasource = "payfrit" }
        )>
      </cfif>
    </cfif>
    <cfset payload = loadCartPayload(qFind.ID)>
    <cfset apiAbort(payload)>
  </cfif>

  <!--- Create new cart order --->
  <cfset qBiz = queryTimed(
    "
      SELECT DeliveryFlatFee
      FROM Businesses
      WHERE ID = ?
      LIMIT 1
    ",
    [ { value = BusinessID, cfsqltype = "cf_sql_integer" } ],
    { datasource = "payfrit" }
  )>

  <cfif qBiz.recordCount EQ 0>
    <cfset apiAbort({ "OK": false, "ERROR": "bad_business", "MESSAGE": "Business not found", "DETAIL": "" })>
  </cfif>

  <!--- SP-SM: Resolve grant if ServicePoint doesn't belong to this business --->
  <cfset grantID = 0>
  <cfset grantOwnerBusinessID = 0>
  <cfset grantEconomicsType = "">
  <cfset grantEconomicsValue = 0>
  <cfif ServicePointID GT 0>
    <cfset qSPOwner = queryTimed(
      "SELECT BusinessID FROM ServicePoints WHERE ID = ? LIMIT 1",
      [ { value = ServicePointID, cfsqltype = "cf_sql_integer" } ],
      { datasource = "payfrit" }
    )>
    <cfif qSPOwner.recordCount GT 0 AND qSPOwner.BusinessID NEQ BusinessID>
      <!--- SP belongs to another business - check if ordering business is a child of SP owner --->
      <cfset qParent = queryTimed(
        "SELECT ParentBusinessID FROM Businesses WHERE ID = ? LIMIT 1",
        [ { value = BusinessID, cfsqltype = "cf_sql_integer" } ],
        { datasource = "payfrit" }
      )>
      <cfset isChildOfSPOwner = qParent.recordCount GT 0 AND val(qParent.ParentBusinessID) EQ qSPOwner.BusinessID>

      <cfif NOT isChildOfSPOwner>
        <!--- Not a child business - check for active grant --->
        <cfset qGrant = queryTimed(
          "SELECT ID, OwnerBusinessID, EconomicsType, EconomicsValue, EligibilityScope, TimePolicyType, TimePolicyData
           FROM ServicePointGrants
           WHERE GuestBusinessID = ? AND ServicePointID = ? AND StatusID = 1
           LIMIT 1",
          [
            { value = BusinessID, cfsqltype = "cf_sql_integer" },
            { value = ServicePointID, cfsqltype = "cf_sql_integer" }
          ],
          { datasource = "payfrit" }
        )>
        <cfif qGrant.recordCount EQ 0>
          <cfset apiAbort({ "OK": false, "ERROR": "sp_not_accessible", "MESSAGE": "Service point is not accessible to your business.", "DETAIL": "" })>
        </cfif>
        <!--- Validate time policy --->
        <cfif NOT isGrantTimeActive(qGrant.TimePolicyType, qGrant.TimePolicyData)>
          <cfset apiAbort({ "OK": false, "ERROR": "grant_time_inactive", "MESSAGE": "Service point access is not available at this time.", "DETAIL": "" })>
        </cfif>
        <!--- Validate eligibility --->
        <cfif NOT checkGrantEligibility(qGrant.EligibilityScope, UserID, qGrant.OwnerBusinessID, BusinessID)>
          <cfset apiAbort({ "OK": false, "ERROR": "grant_eligibility_failed", "MESSAGE": "You are not eligible to order at this service point.", "DETAIL": "" })>
        </cfif>
        <cfset grantID = qGrant.ID>
        <cfset grantOwnerBusinessID = qGrant.OwnerBusinessID>
        <cfset grantEconomicsType = qGrant.EconomicsType>
        <cfset grantEconomicsValue = qGrant.EconomicsValue>
      </cfif>
      <!--- If isChildOfSPOwner is true, no grant needed - child can use parent's service points --->
    </cfif>
  </cfif>

  <cfset nowDt = now()>
  <cfset newUUID = createObject("java", "java.util.UUID").randomUUID().toString()>

  <!--- Calculate delivery fee: only for delivery orders (OrderTypeID = 3)
        OrderTypeID: 0=undecided, 1=dine-in, 2=takeaway, 3=delivery
        Only delivery (3) should have delivery fee.
        Note: For undecided orders (0), fee is set later via setOrderType.cfm --->
  <cfset deliveryFee = (OrderTypeID EQ 3) ? qBiz.DeliveryFlatFee : 0>

  <!--- Generate new OrderID (table is not auto-inc in SSOT) --->
  <cfset qNext = queryTimed(
    "SELECT IFNULL(MAX(ID),0) + 1 AS NextID FROM Orders",
    [],
    { datasource = "payfrit" }
  )>
  <cfset NewOrderID = qNext.NextID>

  <cfset queryTimed(
    "
      INSERT INTO Orders (
        ID,
        UUID,
        UserID,
        BusinessID,
        DeliveryMultiplier,
        OrderTypeID,
        DeliveryFee,
        StatusID,
        AddressID,
        PaymentID,
        Remarks,
        AddedOn,
        LastEditedOn,
        SubmittedOn,
        ServicePointID,
        GrantID,
        GrantOwnerBusinessID,
        GrantEconomicsType,
        GrantEconomicsValue
      ) VALUES (
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        ?,
        0,
        NULL,
        NULL,
        NULL,
        ?,
        ?,
        NULL,
        ?,
        ?,
        ?,
        ?,
        ?
      )
    ",
    [
      { value = NewOrderID, cfsqltype = "cf_sql_integer" },
      { value = newUUID, cfsqltype = "cf_sql_varchar" },
      { value = UserID, cfsqltype = "cf_sql_integer" },
      { value = BusinessID, cfsqltype = "cf_sql_integer" },
      { value = 1.0, cfsqltype = "cf_sql_decimal" },
      { value = OrderTypeID, cfsqltype = "cf_sql_integer" },
      { value = deliveryFee, cfsqltype = "cf_sql_decimal" },
      { value = nowDt, cfsqltype = "cf_sql_timestamp" },
      { value = nowDt, cfsqltype = "cf_sql_timestamp" },
      { value = ServicePointID, cfsqltype = "cf_sql_integer" },
      { value = grantID, cfsqltype = "cf_sql_integer", null = (grantID EQ 0) },
      { value = grantOwnerBusinessID, cfsqltype = "cf_sql_integer", null = (grantOwnerBusinessID EQ 0) },
      { value = grantEconomicsType, cfsqltype = "cf_sql_varchar", null = (len(grantEconomicsType) EQ 0) },
      { value = grantEconomicsValue, cfsqltype = "cf_sql_decimal", null = (grantEconomicsType EQ "" OR grantEconomicsType EQ "none") }
    ],
    { datasource = "payfrit" }
  )>

  <!--- Per your rule: OrderID is determined by selecting highest after creation --->
  <cfset qLatest = queryTimed(
    "SELECT MAX(ID) AS NextID FROM Orders",
    [],
    { datasource = "payfrit" }
  )>
  <cfset FinalOrderID = qLatest.NextID>

  <cfset payload = loadCartPayload(FinalOrderID)>
  <cfset apiAbort(payload)>

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