<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 ID, Name, IsCollapsible, IsActive, ParentItemID, BusinessID
  FROM Items
  WHERE ID IN (11267, 11251, 11246, 11224, 11233, 11230, 11240, 11243, 11237, 11227)
  ORDER BY Name
", {}, { datasource: "payfrit" });

templates = [];
for (row in qTemplates) {
  arrayAppend(templates, {
    "ItemID": row.ID,
    "Name": row.Name,
    "IsCollapsible": row.IsCollapsible,
    "IsActive": row.IsActive,
    "ParentID": row.ParentItemID,
    "BusinessID": row.BusinessID
  });
}

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

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

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

cheeseItems = [];
for (row in qCheeseTemplate) {
  arrayAppend(cheeseItems, {
    "ItemID": row.ID,
    "Name": row.Name,
    "ParentID": row.ParentItemID,
    "IsActive": row.IsActive
  });
}

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