<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 IsModifierTemplate column to Items
 * 2. Create lt_ItemID_TemplateItemID table
 */

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

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

    // Step 2: Create lt_ItemID_TemplateItemID table if it doesn't exist
    try {
        queryTimed("
            CREATE TABLE IF NOT EXISTS lt_ItemID_TemplateItemID (
                ID 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 lt_ItemID_TemplateItemID table");
    } catch (any e) {
        arrayAppend(response.steps, "lt_ItemID_TemplateItemID: " & e.message);
    }

    response["OK"] = true;

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

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