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

<cftry>
<cfscript>
/**
 * Save Business Brand Color
 * POST JSON: { "BusinessID": 37, "BrandColor": "#1B4D3E" }
 */

requestBody = toString(getHttpRequestData().content);
if (!len(requestBody)) {
  apiAbort({ "OK": false, "ERROR": "no_body", "MESSAGE": "No request body provided" });
}

data = deserializeJSON(requestBody);

// Get BusinessID from body or request scope
bizId = 0;
if (structKeyExists(data, "BusinessID") && isNumeric(data.BusinessID) && data.BusinessID GT 0) {
  bizId = int(data.BusinessID);
} else if (structKeyExists(request, "BusinessID") && isNumeric(request.BusinessID) && request.BusinessID GT 0) {
  bizId = int(request.BusinessID);
}

if (bizId LTE 0) {
  apiAbort({ "OK": false, "ERROR": "missing_businessid", "MESSAGE": "BusinessID is required" });
}

// Validate color format
brandColor = structKeyExists(data, "BrandColor") && isSimpleValue(data.BrandColor) ? trim(data.BrandColor) : "";

// Allow empty to clear, or validate hex format
if (len(brandColor) GT 0) {
  // Strip leading # if present
  if (left(brandColor, 1) == chr(35)) {
    brandColor = right(brandColor, len(brandColor) - 1);
  }
  // Must be exactly 6 hex chars
  if (len(brandColor) != 6 || !reFind("^[0-9A-Fa-f]{6}$", brandColor)) {
    apiAbort({ "OK": false, "ERROR": "invalid_color", "MESSAGE": "Color must be a valid 6-digit hex color (e.g. 1B4D3E or ##1B4D3E)" });
  }
  // Store uppercase, no # prefix
  brandColor = uCase(brandColor);
}

// Update the database
queryTimed("
  UPDATE Businesses
  SET BrandColor = :color
  WHERE ID = :bizId
", {
  color: { value: brandColor, cfsqltype: "cf_sql_varchar" },
  bizId: { value: bizId, cfsqltype: "cf_sql_integer" }
}, { datasource: "payfrit" });

writeOutput(serializeJSON({
  "OK": true,
  "ERROR": "",
  "MESSAGE": "Brand color saved",
  "BRANDCOLOR": brandColor
}));
</cfscript>

<cfcatch type="any">
  <cfheader statuscode="200" statustext="OK">
  <cfcontent type="application/json; charset=utf-8" reset="true">
  <cfoutput>#serializeJSON({ "OK": false, "ERROR": "server_error", "MESSAGE": cfcatch.message, "DETAIL": cfcatch.detail })#</cfoutput>
</cfcatch>
</cftry>
