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

<cftry>
<cfset itemsDir = expandPath("/uploads/items")>
<cfscript>
// Get ItemID from form
itemId = 0;
if (structKeyExists(form, "ItemID") && isNumeric(form.ItemID) && form.ItemID GT 0) {
  itemId = int(form.ItemID);
}

if (itemId LTE 0) {
  apiAbort({ "OK": false, "ERROR": "missing_itemid", "MESSAGE": "ItemID is required" });
}
</cfscript>

<!--- Check if file was uploaded --->
<cfif NOT structKeyExists(form, "photo") OR form.photo 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="photo" destination="#itemsDir#/" 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="#itemsDir#/#uploadResult.ServerFile#">
  <cfoutput>#serializeJSON({ "OK": false, "ERROR": "invalid_type", "MESSAGE": "Only image files are accepted (jpg, jpeg, gif, png, webp)" })#</cfoutput>
  <cfabort>
</cfif>

<!--- Delete old photo if exists (any extension) --->
<cfscript>
for (ext in listToArray(allowedExtensions)) {
  oldFile = "#itemsDir#/#itemId#.#ext#";
  if (fileExists(oldFile)) {
    try { fileDelete(oldFile); } catch (any e) {}
  }
}
</cfscript>

<!--- Rename to ItemID.ext --->
<cffile action="RENAME" source="#itemsDir#/#uploadResult.ServerFile#" destination="#itemsDir#/#itemId#.#uploadResult.ClientFileExt#" mode="755">

<!--- Return success with image URL --->
<cfoutput>#serializeJSON({
  "OK": true,
  "ERROR": "",
  "MESSAGE": "Photo uploaded successfully",
  "IMAGEURL": "/uploads/items/#itemId#.#uploadResult.ClientFileExt#"
})#</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>
