<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 = queryTimed("
        SELECT ID, Name, ParentItemID, Price, IsCollapsible, RequiresChildSelection
        FROM Items
        WHERE BusinessID = 17 AND Name LIKE '%Fountain%'
    ", {}, { datasource: "payfrit" });

    response["FountainDrinks"] = [];
    for (row in qFountain) {
        fountainItem = {
            "ItemID": row.ID,
            "Name": row.Name,
            "Price": row.Price,
            "IsCollapsible": row.IsCollapsible,
            "RequiresChildSelection": row.RequiresChildSelection,
            "Children": []
        };

        // Get children of this item
        qChildren = queryTimed("
            SELECT ID, Name, ParentItemID, Price, IsCollapsible, RequiresChildSelection, IsCheckedByDefault
            FROM Items
            WHERE ParentItemID = :parentId
            ORDER BY SortOrder
        ", { parentId: row.ID }, { datasource: "payfrit" });

        for (child in qChildren) {
            childItem = {
                "ItemID": child.ItemID,
                "Name": child.Name,
                "Price": child.Price,
                "IsCollapsible": child.IsCollapsible,
                "IsCheckedByDefault": child.IsCheckedByDefault,
                "Grandchildren": []
            };

            // Get grandchildren
            qGrandchildren = queryTimed("
                SELECT ID, Name, Price, IsCheckedByDefault
                FROM Items
                WHERE ParentItemID = :parentId
                ORDER BY SortOrder
            ", { parentId: child.ItemID }, { datasource: "payfrit" });

            for (gc in qGrandchildren) {
                arrayAppend(childItem.Grandchildren, {
                    "ItemID": gc.ItemID,
                    "Name": gc.Name,
                    "Price": gc.Price,
                    "IsCheckedByDefault": gc.IsCheckedByDefault
                });
            }

            arrayAppend(fountainItem.Children, childItem);
        }

        arrayAppend(response.FountainDrinks, fountainItem);
    }

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

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