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

<cfscript>
response = { "OK": false };

try {
    requestBody = toString(getHttpRequestData().content);
    requestData = {};
    if (len(requestBody)) {
        requestData = deserializeJSON(requestBody);
    }

    businessID = val(requestData.BusinessID ?: 0);
    confirmDelete = requestData.confirm ?: "";

    if (businessID == 0) {
        throw("BusinessID is required");
    }

    if (confirmDelete != "DELETE_ALL_DATA") {
        throw("Must pass confirm: 'DELETE_ALL_DATA' to proceed");
    }

    // Get counts before deletion
    qItemCount = queryTimed("SELECT COUNT(*) as cnt FROM Items WHERE BusinessID = :bid", { bid: businessID }, { datasource: "payfrit" });
    qCatCount = queryTimed("SELECT COUNT(*) as cnt FROM Categories WHERE BusinessID = :bid", { bid: businessID }, { datasource: "payfrit" });

    // Get item IDs for this business to delete template links
    qItemIds = queryTimed("SELECT ID FROM Items WHERE BusinessID = :bid", { bid: businessID }, { datasource: "payfrit" });
    itemIds = [];
    for (row in qItemIds) {
        arrayAppend(itemIds, row.ID);
    }

    deletedLinks = 0;
    if (arrayLen(itemIds) > 0) {
        // Delete template links for these items
        queryTimed("DELETE FROM lt_ItemID_TemplateItemID WHERE ItemID IN (:ids) OR TemplateItemID IN (:ids)",
            { ids: { value: arrayToList(itemIds), cfsqltype: "cf_sql_varchar", list: true } },
            { datasource: "payfrit" });
        deletedLinks = arrayLen(itemIds);
    }

    // Delete all items for this business
    queryTimed("DELETE FROM Items WHERE BusinessID = :bid", { bid: businessID }, { datasource: "payfrit" });

    // Delete all categories for this business
    queryTimed("DELETE FROM Categories WHERE BusinessID = :bid", { bid: businessID }, { datasource: "payfrit" });

    response = {
        "OK": true,
        "deleted": {
            "items": qItemCount.cnt,
            "categories": qCatCount.cnt,
            "templateLinks": deletedLinks
        },
        "businessID": businessID
    };

} catch (any e) {
    response = {
        "OK": false,
        "ERROR": e.message
    };
}

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