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

<cfscript>
/**
 * Create Menus table for multiple menu support
 *
 * Menus can have:
 * - Name (e.g., "Lunch Menu", "Dinner Menu", "Happy Hour")
 * - Active days (bitmask linked to business hours days)
 * - Start/End times for when the menu is available
 * - Sort order for display
 */

response = { "OK": false };

try {
    // Check if Menus table exists
    qCheck = queryTimed("
        SELECT 1 FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'payfrit'
          AND TABLE_NAME = 'Menus'
    ", {}, { datasource: "payfrit" });

    if (qCheck.recordCount > 0) {
        response["OK"] = true;
        response["MESSAGE"] = "Menus table already exists";
    } else {
        // Create Menus table
        queryTimed("
            CREATE TABLE Menus (
                ID INT AUTO_INCREMENT PRIMARY KEY,
                BusinessID INT NOT NULL,
                Name VARCHAR(100) NOT NULL,
                Description VARCHAR(500) NULL,
                DaysActive INT NOT NULL DEFAULT 127,
                StartTime TIME NULL,
                EndTime TIME NULL,
                SortOrder INT NOT NULL DEFAULT 0,
                IsActive TINYINT NOT NULL DEFAULT 1,
                AddedOn DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_menus_business (BusinessID),
                INDEX idx_menus_active (BusinessID, IsActive)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ", {}, { datasource: "payfrit" });

        response["OK"] = true;
        response["MESSAGE"] = "Menus table created successfully";
        response["SCHEMA"] = {
            "DaysActive": "Bitmask: 1=Sun, 2=Mon, 4=Tue, 8=Wed, 16=Thu, 32=Fri, 64=Sat (127 = all days)"
        };
    }

    // Check if MenuID column exists in Categories table
    qCatCol = queryTimed("
        SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = 'payfrit'
          AND TABLE_NAME = 'Categories'
          AND COLUMN_NAME = 'MenuID'
    ", {}, { datasource: "payfrit" });

    if (qCatCol.recordCount == 0) {
        // Add MenuID column to Categories table
        queryTimed("
            ALTER TABLE Categories
            ADD COLUMN MenuID INT NULL DEFAULT NULL AFTER BusinessID,
            ADD INDEX idx_categories_menu (MenuID)
        ", {}, { datasource: "payfrit" });
        response["CATEGORIES_UPDATED"] = true;
        response["CATEGORIES_MESSAGE"] = "Added MenuID column to Categories table";
    } else {
        response["CATEGORIES_UPDATED"] = false;
        response["CATEGORIES_MESSAGE"] = "MenuID column already exists";
    }

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

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