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

<cfscript>
/**
 * Create Parent Business (Shell)
 *
 * Creates a minimal business record to serve as a parent for other businesses.
 * No menu items, categories, or hours required.
 *
 * POST body:
 * {
 *   "Name": "Century Casino",
 *   "UserID": 1,
 *   "ChildBusinessIDs": [47, 48]  // Optional: link existing businesses as children
 * }
 *
 * Returns the new BusinessID
 */

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

response = { "OK": false };

try {
    data = readJsonBody();

    Name = structKeyExists(data, "Name") ? trim(data.Name) : "";
    UserID = structKeyExists(data, "UserID") ? val(data.UserID) : 0;
    ChildBusinessIDs = structKeyExists(data, "ChildBusinessIDs") && isArray(data.ChildBusinessIDs) ? data.ChildBusinessIDs : [];

    if (!len(Name)) {
        response["ERROR"] = "missing_name";
        response["MESSAGE"] = "Name is required";
        writeOutput(serializeJSON(response));
        abort;
    }

    if (UserID <= 0) {
        response["ERROR"] = "missing_userid";
        response["MESSAGE"] = "UserID is required";
        writeOutput(serializeJSON(response));
        abort;
    }

    // Create minimal address record (just a placeholder)
    queryExecute("
        INSERT INTO Addresses (Line1, UserID, AddressTypeID, AddedOn)
        VALUES ('Parent Business - No Physical Location', :userID, 2, NOW())
    ", {
        userID: UserID
    }, { datasource = "payfrit" });

    qAddr = queryExecute("SELECT LAST_INSERT_ID() as id", {}, { datasource = "payfrit" });
    addressId = qAddr.id;

    // Create parent business (no menu, no hours, just a shell)
    queryExecute("
        INSERT INTO Businesses (Name, UserID, AddressID, ParentBusinessID, BusinessDeliveryZipCodes, AddedOn)
        VALUES (:name, :userId, :addressId, NULL, '', NOW())
    ", {
        name: Name,
        userId: UserID,
        addressId: addressId
    }, { datasource = "payfrit" });

    qBiz = queryExecute("SELECT LAST_INSERT_ID() as id", {}, { datasource = "payfrit" });
    newBusinessID = qBiz.id;

    // Link address back to business
    queryExecute("
        UPDATE Addresses SET BusinessID = :bizId WHERE ID = :addrId
    ", {
        bizId: newBusinessID,
        addrId: addressId
    }, { datasource = "payfrit" });

    // Update child businesses if provided
    linkedChildren = [];
    for (childID in ChildBusinessIDs) {
        childID = val(childID);
        if (childID > 0) {
            queryExecute("
                UPDATE Businesses SET ParentBusinessID = :parentId WHERE ID = :childId
            ", {
                parentId: newBusinessID,
                childId: childID
            }, { datasource = "payfrit" });
            arrayAppend(linkedChildren, childID);
        }
    }

    response["OK"] = true;
    response["BusinessID"] = newBusinessID;
    response["Name"] = Name;
    response["MESSAGE"] = "Parent business created";
    if (arrayLen(linkedChildren) > 0) {
        response["LinkedChildren"] = linkedChildren;
    }

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

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