<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
qLinks = queryExecute("
  SELECT
    tl.ItemID as MenuItemID,
    mi.ItemName as MenuItemName,
    mi.ItemParentItemID as MenuItemParentID,
    tl.TemplateItemID,
    t.ItemName as TemplateName,
    t.ItemIsActive as TemplateActive,
    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.ItemName, tl.SortOrder
", { bizId: bizId }, { datasource: "payfrit" });

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

// Get all templates that exist for this business
qTemplates = queryExecute("
  SELECT ItemID, ItemName, ItemIsActive, ItemParentItemID
  FROM Items
  WHERE ItemBusinessID = :bizId
    AND ItemIsCollapsible = 1
  ORDER BY ItemName
", { bizId: bizId }, { datasource: "payfrit" });

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

writeOutput(serializeJSON({
  "OK": true,
  "TemplateLinksCount": arrayLen(links),
  "TemplateLinks": links,
  "TemplatesCount": arrayLen(templates),
  "Templates": templates
}));
</cfscript>
