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

<cfscript>
// Check lt_ItemID_TemplateItemID for Big Dean's (BusinessID 27)
bizId = 27;

// Count total links
qCount = queryExecute("SELECT COUNT(*) as cnt FROM lt_ItemID_TemplateItemID", {}, { datasource: "payfrit" });

// Get template item IDs for this business
qTemplates = queryExecute("
  SELECT DISTINCT tl.TemplateItemID, i.Name
  FROM lt_ItemID_TemplateItemID tl
  JOIN Items i ON i.ID = tl.TemplateItemID
  WHERE i.BusinessID = :bizId
", { bizId: bizId }, { datasource: "payfrit" });

templates = [];
for (row in qTemplates) {
  arrayAppend(templates, { "TemplateItemID": row.TemplateItemID, "Name": row.Name });
}

// Get items that should be categories (ParentItemID=0, not templates)
qCategories = queryExecute("
  SELECT i.ID, i.Name, i.ParentItemID, i.IsCollapsible
  FROM Items i
  WHERE i.BusinessID = :bizId
    AND i.ParentItemID = 0
    AND i.IsCollapsible = 0
    AND NOT EXISTS (SELECT 1 FROM lt_ItemID_TemplateItemID tl WHERE tl.TemplateItemID = i.ID)
  ORDER BY i.SortOrder
", { bizId: bizId }, { datasource: "payfrit" });

categories = [];
for (row in qCategories) {
  arrayAppend(categories, { "ItemID": row.ID, "Name": row.Name });
}

writeOutput(serializeJSON({
  "OK": true,
  "totalTemplateLinks": qCount.cnt,
  "templatesForBusiness": templates,
  "categoriesForBusiness": categories
}));
</cfscript>
