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

<cfscript>
// Find Fountain Drinks in In-N-Out (BusinessID 17) and show its hierarchy
response = { "OK": true };

try {
    // Get Fountain Drinks item
    qFountain = queryExecute("
        SELECT ItemID, ItemName, ItemParentItemID, ItemPrice, ItemIsCollapsible, ItemRequiresChildSelection
        FROM Items
        WHERE ItemBusinessID = 17 AND ItemName LIKE '%Fountain%'
    ", {}, { datasource: "payfrit" });

    response["FountainDrinks"] = [];
    for (row in qFountain) {
        fountainItem = {
            "ItemID": row.ItemID,
            "ItemName": row.ItemName,
            "ItemPrice": row.ItemPrice,
            "ItemIsCollapsible": row.ItemIsCollapsible,
            "ItemRequiresChildSelection": row.ItemRequiresChildSelection,
            "Children": []
        };

        // Get children of this item
        qChildren = queryExecute("
            SELECT ItemID, ItemName, ItemParentItemID, ItemPrice, ItemIsCollapsible, ItemRequiresChildSelection, ItemIsCheckedByDefault
            FROM Items
            WHERE ItemParentItemID = :parentId
            ORDER BY ItemSortOrder
        ", { parentId: row.ItemID }, { datasource: "payfrit" });

        for (child in qChildren) {
            childItem = {
                "ItemID": child.ItemID,
                "ItemName": child.ItemName,
                "ItemPrice": child.ItemPrice,
                "ItemIsCollapsible": child.ItemIsCollapsible,
                "ItemIsCheckedByDefault": child.ItemIsCheckedByDefault,
                "Grandchildren": []
            };

            // Get grandchildren
            qGrandchildren = queryExecute("
                SELECT ItemID, ItemName, ItemPrice, ItemIsCheckedByDefault
                FROM Items
                WHERE ItemParentItemID = :parentId
                ORDER BY ItemSortOrder
            ", { parentId: child.ItemID }, { datasource: "payfrit" });

            for (gc in qGrandchildren) {
                arrayAppend(childItem.Grandchildren, {
                    "ItemID": gc.ItemID,
                    "ItemName": gc.ItemName,
                    "ItemPrice": gc.ItemPrice,
                    "ItemIsCheckedByDefault": gc.ItemIsCheckedByDefault
                });
            }

            arrayAppend(fountainItem.Children, childItem);
        }

        arrayAppend(response.FountainDrinks, fountainItem);
    }

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

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