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

<!--- Only allow from localhost --->
<cfif NOT (cgi.remote_addr EQ "127.0.0.1" OR cgi.remote_addr EQ "::1" OR findNoCase("localhost", cgi.server_name))>
    <cfoutput>#serializeJSON({"OK": false, "ERROR": "admin_only"})#</cfoutput>
    <cfabort>
</cfif>

<cfscript>
/**
 * Setup Modifier Templates system
 * 1. Add ItemIsModifierTemplate column to Items
 * 2. Create ItemTemplateLinks table
 */

response = { "OK": false, "steps": [] };

try {
    // Step 1: Add ItemIsModifierTemplate column if it doesn't exist
    try {
        queryExecute("
            ALTER TABLE Items ADD COLUMN ItemIsModifierTemplate TINYINT(1) DEFAULT 0
        ", {}, { datasource: "payfrit" });
        arrayAppend(response.steps, "Added ItemIsModifierTemplate column");
    } catch (any e) {
        if (findNoCase("Duplicate column", e.message)) {
            arrayAppend(response.steps, "ItemIsModifierTemplate column already exists");
        } else {
            arrayAppend(response.steps, "Error adding column: " & e.message);
        }
    }

    // Step 2: Create ItemTemplateLinks table if it doesn't exist
    try {
        queryExecute("
            CREATE TABLE IF NOT EXISTS ItemTemplateLinks (
                LinkID INT AUTO_INCREMENT PRIMARY KEY,
                ItemID INT NOT NULL,
                TemplateItemID INT NOT NULL,
                SortOrder INT DEFAULT 0,
                UNIQUE KEY unique_link (ItemID, TemplateItemID),
                INDEX idx_item (ItemID),
                INDEX idx_template (TemplateItemID)
            )
        ", {}, { datasource: "payfrit" });
        arrayAppend(response.steps, "Created ItemTemplateLinks table");
    } catch (any e) {
        arrayAppend(response.steps, "ItemTemplateLinks: " & e.message);
    }

    response["OK"] = true;

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

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