<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8" reset="true">
<cfheader name="Cache-Control" value="no-store">

<cfscript>
/**
 * Get the user's active cart (status=0) if one exists
 * Used at app startup to check if user has an existing order in progress
 *
 * Query params:
 *   UserID - the user's ID
 *
 * Returns the cart info including businessId, orderTypeId, and item count
 */

response = { "OK": false };

try {
    UserID = val(url.UserID ?: 0);

    if (UserID LTE 0) {
        response["ERROR"] = "missing_user";
        response["MESSAGE"] = "UserID is required";
        writeOutput(serializeJSON(response));
        abort;
    }

    // Get active cart (status = 0) for this user
    qCart = queryExecute("
        SELECT
            o.ID,
            o.UUID,
            o.BusinessID,
            o.OrderTypeID,
            o.StatusID,
            o.ServicePointID,
            o.AddedOn,
            b.Name AS BusinessName,
            b.OrderTypes AS BusinessOrderTypes,
            sp.Name AS ServicePointName,
            (SELECT COUNT(*)
             FROM OrderLineItems oli
             WHERE oli.OrderID = o.ID
               AND oli.IsDeleted = 0
               AND oli.ParentOrderLineItemID = 0) as ItemCount
        FROM Orders o
        LEFT JOIN Businesses b ON b.ID = o.BusinessID
        LEFT JOIN ServicePoints sp ON sp.ID = o.ServicePointID
        WHERE o.UserID = :userId
          AND o.StatusID = 0
        ORDER BY o.ID DESC
        LIMIT 1
    ", {
        userId: { value: UserID, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    if (qCart.recordCount GT 0) {
        orderTypeName = "";
        switch (qCart.OrderTypeID) {
            case 0: orderTypeName = "Undecided"; break;
            case 1: orderTypeName = "Dine-In"; break;
            case 2: orderTypeName = "Takeaway"; break;
            case 3: orderTypeName = "Delivery"; break;
        }

        // Parse business order types (e.g., "1,2,3" -> array of ints)
        businessOrderTypes = len(trim(qCart.BusinessOrderTypes)) ? qCart.BusinessOrderTypes : "1,2,3";
        orderTypesArray = listToArray(businessOrderTypes, ",");

        response["OK"] = true;
        response["HAS_CART"] = true;
        response["CART"] = {
            "OrderID": val(qCart.ID),
            "UUID": qCart.UUID ?: "",
            "BusinessID": val(qCart.BusinessID),
            "Name": len(trim(qCart.BusinessName)) ? qCart.BusinessName : "",
            "OrderTypes": orderTypesArray,
            "OrderTypeID": val(qCart.OrderTypeID),
            "OrderTypeName": orderTypeName,
            "ServicePointID": val(qCart.ServicePointID),
            "ServicePointName": len(trim(qCart.ServicePointName)) ? qCart.ServicePointName : "",
            "ItemCount": val(qCart.ItemCount),
            "AddedOn": dateTimeFormat(qCart.AddedOn, "yyyy-mm-dd HH:nn:ss")
        };
    } else {
        response["OK"] = true;
        response["HAS_CART"] = false;
        response["CART"] = javacast("null", "");
    }

} catch (any e) {
    response["ERROR"] = "server_error";
    response["MESSAGE"] = e.message;
}

writeOutput(serializeJSON(response));
</cfscript>
