<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">

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

<cftry>
<cfset headersDir = expandPath("/uploads/headers")>
<cfscript>
// Get BusinessID from form, request scope, or header
bizId = 0;
if (structKeyExists(form, "BusinessID") && isNumeric(form.BusinessID) && form.BusinessID GT 0) {
  bizId = int(form.BusinessID);
} else if (structKeyExists(request, "BusinessID") && isNumeric(request.BusinessID) && request.BusinessID GT 0) {
  bizId = int(request.BusinessID);
} else {
  httpHeaders = getHttpRequestData().headers;
  if (structKeyExists(httpHeaders, "X-Business-ID") && isNumeric(httpHeaders["X-Business-ID"]) && httpHeaders["X-Business-ID"] GT 0) {
    bizId = int(httpHeaders["X-Business-ID"]);
  }
}

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

<!--- Check if file was uploaded --->
<cfif NOT structKeyExists(form, "header") OR form.header EQ "">
  <cfoutput>#serializeJSON({ "OK": false, "ERROR": "no_file", "MESSAGE": "No file was uploaded" })#</cfoutput>
  <cfabort>
</cfif>

<!--- Upload the file to temp location first --->
<cffile action="UPLOAD" filefield="header" destination="#headersDir#/" nameconflict="MAKEUNIQUE" mode="755" result="uploadResult">

<!--- Validate file type --->
<cfset allowedExtensions = "jpg,jpeg,gif,png,webp">
<cfif NOT listFindNoCase(allowedExtensions, uploadResult.ClientFileExt)>
  <cffile action="DELETE" file="#headersDir#/#uploadResult.ServerFile#">
  <cfoutput>#serializeJSON({ "OK": false, "ERROR": "invalid_type", "MESSAGE": "Only image files are accepted (jpg, jpeg, gif, png, webp)" })#</cfoutput>
  <cfabort>
</cfif>

<!--- Get image info --->
<cfimage source="#headersDir#/#uploadResult.ServerFile#" action="info" structName="imageInfo">

<!--- No resize - accept image as-is --->

<!--- Delete old header if exists --->
<cfquery name="qOldHeader" datasource="payfrit">
  SELECT HeaderImageExtension AS BusinessHeaderImageExtension
  FROM Businesses
  WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#bizId#">
</cfquery>

<cfif qOldHeader.recordCount GT 0 AND len(trim(qOldHeader.BusinessHeaderImageExtension)) GT 0>
  <cfset oldFile = "#headersDir#/#bizId#.#qOldHeader.BusinessHeaderImageExtension#">
  <cfif fileExists(oldFile)>
    <cftry>
      <cffile action="DELETE" file="#oldFile#">
      <cfcatch></cfcatch>
    </cftry>
  </cfif>
</cfif>

<!--- Also delete destination file if it exists (same extension re-upload) --->
<cfset destFile = "#headersDir#/#bizId#.#uploadResult.ClientFileExt#">
<cfif fileExists(destFile)>
  <cftry>
    <cffile action="DELETE" file="#destFile#">
    <cfcatch></cfcatch>
  </cftry>
</cfif>

<!--- Rename to BusinessID.ext --->
<cffile action="RENAME" source="#headersDir#/#uploadResult.ServerFile#" destination="#destFile#" mode="755">

<!--- Update database --->
<cfquery datasource="payfrit">
  UPDATE Businesses
  SET HeaderImageExtension = <cfqueryparam cfsqltype="cf_sql_varchar" value="#uploadResult.ClientFileExt#">
  WHERE ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#bizId#">
</cfquery>

<!--- Return success with image URL --->
<cfoutput>#serializeJSON({
  "OK": true,
  "ERROR": "",
  "MESSAGE": "Header uploaded successfully",
  "HEADERURL": "/uploads/headers/#bizId#.#uploadResult.ClientFileExt#",
  "WIDTH": imageInfo.width,
  "HEIGHT": imageInfo.height
})#</cfoutput>

<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>
