<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8" reset="true">

<cfscript>
bizId = 27;

// Get all template links for Big Dean's with item names
qLinks = queryExecute("
  SELECT
    tl.ItemID as MenuItemID,
    mi.ItemName as MenuItemName,
    mi.ItemParentItemID,
    tl.TemplateItemID,
    t.ItemName as TemplateName,
    tl.SortOrder
  FROM ItemTemplateLinks tl
  JOIN Items mi ON mi.ItemID = tl.ItemID
  JOIN Items t ON t.ItemID = tl.TemplateItemID
  WHERE mi.ItemBusinessID = :bizId
  ORDER BY mi.ItemParentItemID, mi.ItemName, tl.SortOrder
", { bizId: bizId }, { datasource: "payfrit" });

links = [];
for (row in qLinks) {
  arrayAppend(links, {
    "MenuItemID": row.MenuItemID,
    "MenuItemName": row.MenuItemName,
    "ParentItemID": row.ItemParentItemID,
    "TemplateItemID": row.TemplateItemID,
    "TemplateName": row.TemplateName
  });
}

// Get burgers specifically (parent = 11271)
qBurgers = queryExecute("
  SELECT ItemID, ItemName FROM Items
  WHERE ItemBusinessID = :bizId AND ItemParentItemID = 11271 AND ItemIsActive = 1
  ORDER BY ItemSortOrder
", { bizId: bizId }, { datasource: "payfrit" });

burgers = [];
for (row in qBurgers) {
  // Get templates for this burger
  qBurgerTemplates = queryExecute("
    SELECT tl.TemplateItemID, t.ItemName as TemplateName
    FROM ItemTemplateLinks tl
    JOIN Items t ON t.ItemID = tl.TemplateItemID
    WHERE tl.ItemID = :itemId
  ", { itemId: row.ItemID }, { datasource: "payfrit" });

  templates = [];
  for (t in qBurgerTemplates) {
    arrayAppend(templates, t.TemplateName);
  }

  arrayAppend(burgers, {
    "ItemID": row.ItemID,
    "ItemName": row.ItemName,
    "Templates": templates
  });
}

writeOutput(serializeJSON({
  "OK": true,
  "totalLinks": qLinks.recordCount,
  "links": links,
  "burgers": burgers
}));
</cfscript>
