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

<cfscript>
response = {};

try {
    // Get all businesses with items
    qBusinesses = queryTimed("
        SELECT DISTINCT i.BusinessID, COUNT(*) as ItemCount
        FROM Items i
        WHERE i.BusinessID > 0
        GROUP BY i.BusinessID
    ", {}, { datasource: "payfrit" });

    response["businesses_with_items"] = [];
    for (b in qBusinesses) {
        arrayAppend(response["businesses_with_items"], {
            "businessID": b.ID,
            "itemCount": b.ItemCount
        });
    }

    // Get categories
    qCategories = queryTimed("
        SELECT ID, COUNT(*) as cnt
        FROM Categories
        GROUP BY BusinessID
    ", {}, { datasource: "payfrit" });

    response["categories_by_business"] = [];
    for (c in qCategories) {
        arrayAppend(response["categories_by_business"], {
            "businessID": c.BusinessID,
            "count": c.cnt
        });
    }

    // Get sample items
    qItems = queryTimed("
        SELECT ID, BusinessID, CategoryID, ParentItemID, Name, IsActive
        FROM Items
        WHERE IsActive = 1
        LIMIT 20
    ", {}, { datasource: "payfrit" });

    response["sample_items"] = [];
    for (i in qItems) {
        arrayAppend(response["sample_items"], {
            "id": i.ID,
            "businessID": i.BusinessID,
            "categoryID": i.CategoryID,
            "parentID": i.ParentItemID,
            "name": i.Name,
            "active": i.IsActive
        });
    }

    // Get template links
    qLinks = queryTimed("
        SELECT COUNT(*) as cnt FROM lt_ItemID_TemplateItemID
    ", {}, { datasource: "payfrit" });
    response["template_link_count"] = qLinks.cnt;

    response["OK"] = true;

} catch (any e) {
    response["ERROR"] = e.message;
    response["DETAIL"] = e.detail ?: "";
}

writeOutput(serializeJSON(response));
</cfscript>
