<cftry>

  <!--- Always defined, even if something below throws before reaching the
        real assignment further down - otherwise the caller's #admissionPdfFileId#
        reference in its JSON response throws its own "variable undefined"
        error on top of whatever actually failed here, masking the real cause. --->
  <cfset admissionPdfFileId = 0>

  <!--- ── Paths ─────────────────────────────────────────────────────── --->
  <cfset blankPdf  = expandPath("/patientadmin_new/patient/admission_pdfs/agency_#SESSION.agencyid#_HHCCN.pdf")>
  <cfset filepath  = expandPath("/datafiles/patientHHCCNPdf/")>
  <cfif NOT directoryExists(filepath)>
    <cfset directoryCreate(filepath)>
  </cfif>

  <!--- Suffix with the pAdmit_Forms row id so each submission cycle (including one
        created after the user hits "Clear" and resubmits) gets its own S3 object
        instead of overwriting a previously submitted, signed PDF. admitFormId is 0
        on the very first submit (INSERT path) - qResult.generatedKey is already
        populated by the caller's INSERT query by the time this include runs. --->
  <cfset submissionRowId = (val(admitFormId) GT 0) ? val(admitFormId) : qResult.generatedKey>
  <cfset filename   = "patient_#patientId#_admit_#admitId#_hhccn_#submissionRowId#.pdf">
  <cfset outputPdf  = filepath & filename>

  <!--- ── Helper: safe field read ──────────────────────────────────── --->
  <cffunction name="fv" returntype="string" access="private">
    <cfargument name="key" type="string">
    <cfif structKeyExists(requestBody, arguments.key) AND len(trim(toString(requestBody[arguments.key])))>
      <cfreturn trim(toString(requestBody[arguments.key]))>
    </cfif>
    <cfreturn "">
  </cffunction>

  <!--- ── Drawn signature support ───────────────────────────────────────
        Fields listed here send a base64 PNG data URL (e.g.
        "data:image/png;base64,....") instead of a typed name.
        cfpdfformparam can drop an image into a PDF field via
        imagefield="true", but only if that field is an image-type field
        in the PDF itself - NOT a plain text field. Both fields below have
        already been converted to image-capable fields in Acrobat Pro. --->
  <cffunction name="fSigVal" returntype="struct" access="private">
    <cfargument name="key" type="string">
    <cfset local.raw = fv(arguments.key)>
    <cfset local.result = {value: local.raw, isImage: false}>
    <cfif len(local.raw) GT 10 AND left(local.raw, 10) EQ "data:image">
      <cfset local.commaPos = find(",", local.raw)>
      <cfset local.imgValue = mid(local.raw, local.commaPos + 1, len(local.raw) - local.commaPos)>
      <cfset local.imgValue = replace(local.imgValue, chr(13), "", "all")>
      <cfset local.imgValue = replace(local.imgValue, chr(10), "", "all")>
      <cfset local.result = {value: local.imgValue, isImage: true}>
    </cfif>
    <cfreturn local.result>
  </cffunction>

  <cfset sig_PatientRep  = fSigVal('patient_rep_signature')>
  <cfset sig_Clinician   = fSigVal('clinician_signature')>

  <!--- ── Fill PDF using cfpdfform + cfpdfformparam ────────────────────── --->
  <cfpdfform action="populate"
        source="#blankPdf#"
        destination="#outputPdf#"
        overwrite="yes">

    <cfpdfformparam name="patient_name"             value="#fv('patient_name')#">
    <cfpdfformparam name="patient_identification"   value="#fv('patient_identification')#">
    <cfpdfformparam name="effective_date"           value="#fv('effective_date')#">
    <cfpdfformparam name="items_services"           value="#fv('items_services')#">
    <cfpdfformparam name="reason_for_change"        value="#fv('reason_for_change')#">
    <cfpdfformparam name="additional_information"   value="#fv('additional_information')#">
    <cfpdfformparam name="patient_rep_signature"    value="#sig_PatientRep.value#" imagefield="#sig_PatientRep.isImage#">
    <cfpdfformparam name="patient_rep_printed_name" value="#fv('patient_rep_printed_name')#">
    <cfpdfformparam name="patient_rep_sign_date"    value="#fv('patient_rep_sign_date')#">
    <cfpdfformparam name="clinician_signature"      value="#sig_Clinician.value#" imagefield="#sig_Clinician.isImage#">
    <cfpdfformparam name="clinician_sign_date"      value="#fv('clinician_sign_date')#">

  </cfpdfform>

  <cfset path = 'Patient_files/agency_'&#session.AgencyId# />
  <!--- Upload to Amazon S3--->
  <cfset s3PrefixPath = "s3://#Request.bucket_accesskey#:#Request.bucket_secretkey#@#Request.bucket_name#/#path#" />
  <cfif not directoryExists(s3PrefixPath)>
    <cftry>
      <cfdirectory action="create" directory="#s3PrefixPath#" />
      <cfcatch type="any">
        <!--- S3 bucket/prefix may already exist; directoryExists can be false while create returns 409 BucketAlreadyOwnedByYou --->
        <cfset s3DirErr = cfcatch.message & " " & cfcatch.detail />
        <cfif structKeyExists(cfcatch, "rootCause") AND isStruct(cfcatch.rootCause) AND structKeyExists(cfcatch.rootCause, "message")>
          <cfset s3DirErr = s3DirErr & " " & cfcatch.rootCause.message />
        </cfif>
        <cfif findNoCase("BucketAlreadyOwnedByYou", s3DirErr) EQ 0
          AND findNoCase("BucketAlreadyExists", s3DirErr) EQ 0
          AND findNoCase("ResponseCode: 409", s3DirErr) EQ 0>
          <cfrethrow />
        </cfif>
      </cfcatch>
    </cftry>
  </cfif>
  <cfset pdfBinaryContent = fileReadBinary("#filepath##filename#")>
  <cffile action = "move" destination="s3://#Request.bucket_accesskey#:#Request.bucket_secretkey#@#Request.bucket_name#/#path#/#filename#"
          source = "#filepath##filename#" >

  <!--- ── Register the final submitted PDF in `files` so it can be reused by the
        existing Send Fax / S3 viewer flows (Print, Download, Fax buttons).
        Draft saves (isSubmitted EQ 0) are intentionally skipped. ──────────── --->
  <cfif isSubmitted EQ 1>
    <cfquery name="InsertAdmissionPdfFile" datasource="#Application.DataSrc#">
      INSERT INTO #Request.prefix_db_agency#.files (
        AgencyId, PatientId, Title, FileName, FileType, Dup_file_name, File, CreatedBy
      ) VALUES (
        <cfqueryparam value="#session.AgencyId#" cfsqltype="cf_sql_integer">,
        <cfqueryparam value="#patientId#" cfsqltype="cf_sql_integer">,
        <cfqueryparam value="HHCCN Form" cfsqltype="cf_sql_varchar">,
        <cfqueryparam value="#filename#" cfsqltype="cf_sql_varchar">,
        <cfqueryparam value="application/pdf" cfsqltype="cf_sql_varchar">,
        <cfqueryparam value="#filename#" cfsqltype="cf_sql_varchar">,
        <cfqueryparam value="#pdfBinaryContent#" cfsqltype="cf_sql_blob">,
        <cfqueryparam value="#val(session.employeeid)#" cfsqltype="cf_sql_integer">
      )
    </cfquery>
    <cfquery name="GetAdmissionPdfFileId" datasource="#Application.DataSrc#">
      SELECT LAST_INSERT_ID() AS fileId
    </cfquery>
    <cfset admissionPdfFileId = val(GetAdmissionPdfFileId.fileId)>
  </cfif>

<cfcatch type="any">
</cfcatch>
</cftry>
