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

<cfscript>
bizId = 27;

// Get the template items themselves
qTemplates = queryExecute("
  SELECT ItemID, ItemName, ItemIsCollapsible, ItemIsActive, ItemParentItemID, ItemBusinessID
  FROM Items
  WHERE ItemID IN (11267, 11251, 11246, 11224, 11233, 11230, 11240, 11243, 11237, 11227)
  ORDER BY ItemName
", {}, { datasource: "payfrit" });

templates = [];
for (row in qTemplates) {
  arrayAppend(templates, {
    "ItemID": row.ItemID,
    "ItemName": row.ItemName,
    "IsCollapsible": row.ItemIsCollapsible,
    "IsActive": row.ItemIsActive,
    "ParentID": row.ItemParentItemID,
    "BusinessID": row.ItemBusinessID
  });
}

// What templates are used by burgers vs all items?
qBurgerLinks = queryExecute("
  SELECT mi.ItemID, mi.ItemName, GROUP_CONCAT(t.ItemName ORDER BY tl.SortOrder) as Templates
  FROM Items mi
  JOIN ItemTemplateLinks tl ON tl.ItemID = mi.ItemID
  JOIN Items t ON t.ItemID = tl.TemplateItemID
  WHERE mi.ItemBusinessID = :bizId
    AND mi.ItemParentItemID = 11271
  GROUP BY mi.ItemID, mi.ItemName
  ORDER BY mi.ItemName
", { bizId: bizId }, { datasource: "payfrit" });

burgerLinks = [];
for (row in qBurgerLinks) {
  arrayAppend(burgerLinks, {
    "ItemID": row.ItemID,
    "ItemName": row.ItemName,
    "Templates": row.Templates
  });
}

// Also check: are there templates that SHOULD be linked to burgers?
// (e.g., Add Cheese, etc.)
qCheeseTemplate = queryExecute("
  SELECT ItemID, ItemName, ItemParentItemID, ItemIsActive
  FROM Items
  WHERE ItemBusinessID = :bizId
    AND ItemName LIKE '%Cheese%'
  ORDER BY ItemName
", { bizId: bizId }, { datasource: "payfrit" });

cheeseItems = [];
for (row in qCheeseTemplate) {
  arrayAppend(cheeseItems, {
    "ItemID": row.ItemID,
    "ItemName": row.ItemName,
    "ParentID": row.ItemParentItemID,
    "IsActive": row.ItemIsActive
  });
}

writeOutput(serializeJSON({
  "OK": true,
  "TemplatesUsed": templates,
  "BurgerTemplateLinks": burgerLinks,
  "CheeseRelatedItems": cheeseItems
}));
</cfscript>
