<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8" reset="true">
<cfheader name="Cache-Control" value="no-store">

<cfscript>
/**
 * Add Schedule Fields to Categories Table
 *
 * Adds time-based scheduling fields:
 * - ScheduleStart: TIME - Start time when category is available (e.g., 06:00:00 for breakfast)
 * - ScheduleEnd: TIME - End time when category stops being available (e.g., 11:00:00)
 * - ScheduleDays: VARCHAR(20) - Comma-separated list of day IDs (1=Sun, 2=Mon, etc.) or NULL for all days
 *
 * Run this once to migrate the schema.
 */

response = { "OK": false };

try {
    // Check if columns already exist
    qCheck = queryTimed("
        SELECT COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = 'payfrit'
          AND TABLE_NAME = 'Categories'
          AND COLUMN_NAME IN ('ScheduleStart', 'ScheduleEnd', 'ScheduleDays')
    ", {}, { datasource: "payfrit" });

    existingCols = valueList(qCheck.COLUMN_NAME);

    added = [];

    // Add ScheduleStart if not exists
    if (!listFindNoCase(existingCols, "ScheduleStart")) {
        queryTimed("
            ALTER TABLE Categories
            ADD COLUMN ScheduleStart TIME NULL
        ", {}, { datasource: "payfrit" });
        arrayAppend(added, "ScheduleStart");
    }

    // Add ScheduleEnd if not exists
    if (!listFindNoCase(existingCols, "ScheduleEnd")) {
        queryTimed("
            ALTER TABLE Categories
            ADD COLUMN ScheduleEnd TIME NULL
        ", {}, { datasource: "payfrit" });
        arrayAppend(added, "ScheduleEnd");
    }

    // Add ScheduleDays if not exists
    if (!listFindNoCase(existingCols, "ScheduleDays")) {
        queryTimed("
            ALTER TABLE Categories
            ADD COLUMN ScheduleDays VARCHAR(20) NULL
        ", {}, { datasource: "payfrit" });
        arrayAppend(added, "ScheduleDays");
    }

    response["OK"] = true;
    response["ColumnsAdded"] = added;
    response["AlreadyExisted"] = listToArray(existingCols);
    response["MESSAGE"] = arrayLen(added) > 0
        ? "Added #arrayLen(added)# column(s): #arrayToList(added)#"
        : "All columns already exist";

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

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