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

<cfscript>
// Delete (soft) a quick task template
// Input: BusinessID (required), QuickTaskTemplateID (required)
// Output: { OK: true }

function apiAbort(required struct payload) {
    writeOutput(serializeJSON(payload));
    abort;
}

function readJsonBody() {
    var raw = getHttpRequestData().content;
    if (isNull(raw)) raw = "";
    if (!len(trim(raw))) return {};
    try {
        var data = deserializeJSON(raw);
        if (isStruct(data)) return data;
    } catch (any e) {}
    return {};
}

try {
    data = readJsonBody();

    // Get BusinessID
    businessID = 0;
    httpHeaders = getHttpRequestData().headers;

    if (structKeyExists(data, "BusinessID") && isNumeric(data.BusinessID)) {
        businessID = int(data.BusinessID);
    } else if (structKeyExists(httpHeaders, "X-Business-ID") && isNumeric(httpHeaders["X-Business-ID"])) {
        businessID = int(httpHeaders["X-Business-ID"]);
    }

    if (businessID == 0) {
        apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "BusinessID is required" });
    }

    // Get template ID
    templateID = structKeyExists(data, "QuickTaskTemplateID") && isNumeric(data.QuickTaskTemplateID) ? int(data.QuickTaskTemplateID) : 0;

    if (templateID == 0) {
        apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "QuickTaskTemplateID is required" });
    }

    // Verify template exists and belongs to this business
    qCheck = queryTimed("
        SELECT ID FROM QuickTaskTemplates
        WHERE ID = :id AND BusinessID = :businessID
    ", {
        id: { value: templateID, cfsqltype: "cf_sql_integer" },
        businessID: { value: businessID, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    if (qCheck.recordCount == 0) {
        apiAbort({ "OK": false, "ERROR": "not_found", "MESSAGE": "Template not found" });
    }

    // Soft delete by setting IsActive to 0
    queryTimed("
        UPDATE QuickTaskTemplates SET IsActive = 0
        WHERE ID = :id
    ", {
        id: { value: templateID, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    apiAbort({
        "OK": true,
        "MESSAGE": "Template deleted"
    });

} catch (any e) {
    apiAbort({
        "OK": false,
        "ERROR": "server_error",
        "MESSAGE": e.message
    });
}
</cfscript>
