<!---
$Description: Redesigned 3-page Form 485 PDF per draft design (tickets #10398-#10400)
Data fields sourced from PrintAssesmentForm.cfm
--->
<cfsetting showdebugoutput="no" enablecfoutputonly="no" />
<!--- PDF must not render inside index.cfm layout (header/sidebar breaks PDF output) --->
<cfif FindNoCase("PrintAssesmentForm_Redesign.cfm", CGI.script_name) EQ 0>
	<cflocation url="#application.siteURL#/patientadmin_new/patient/PrintAssesmentForm_Redesign.cfm?#CGI.query_string#" addtoken="no" />
</cfif>
<cfif NOT isDefined("session.AgencyId") OR session.AgencyId LT 1>
	<cflocation url="#application.secure#" addtoken="no" />
</cfif>

<cfif NOT isNumeric("url.afId")>
	<cfset url.afId = decrypt(url.afId, "54kczhzgHTj4a8n+SRZPyg==", "AES", "Hex") />
</cfif>

<!--- Same queries / field setup as PrintAssesmentForm.cfm --->
<cfquery name="Form" datasource="#Application.DataSrc#">
	SELECT *, Order_ID, Assmt_ID, Form_Type, Date_Create, Date_sent, Insured_HIC,
		"" SOC_Item_2, Certification_From, Certification_To,
		Agy_CCN, Pt_First, Pt_Last, Pt_Street, Pt_City, Pt_State, Pt_Zip, Pt_Phone, Pt_Agy_ID,
		Agy_Name, Agy_Street, Agy_City, Agy_State, Agy_Zip, Agy_Phone, Agy_NPI,
		"" Name_Item_6, "" Provider_name_Item_7,
		Pt_DOB, Pt_Gender, Medications, ICD10, Description, ICD_Date,
		DME, Safety, Diet, Form_Status, Allergies,
		Functional_Limits_Extra, Functional_Limitations, Activities_Permitted, Activities_Permitted_Extra,
		Mental_Status, Mental_Status_Extra, Prognosis,
		"" AS Order_item_21, "" AS Goals_Item_22,
		Date_Received, Render_Phys_ID,
		"" AS Addendum_Details_10, "" AS Addendum_Details_21, "" AS Addendum_Details_22,
		Change_by, Discharge_Plan, "" AS Digital_Signature,
		Created_by, Rehabilitation_Potential, Clinician_Signature,
		MD_Homebound, MD_Clinical_Condition, "" AS CMS_485, record_timestamp,
		Date_Sent AS Physician_Last_Seen_Date, 0 AS Location
	FROM #Request.prefix_db_agency#.pCMS4857
	WHERE Order_ID = '#url.afId#'
</cfquery>

<cfset diagnosis = listToArray(Form.Description, "~", false, true) />
<cfset ICD = listToArray(Form.ICD10, "~", false, true) />
<cfset ICD_Date = listToArray(Form.ICD_Date, "~", false, true) />
<cfset primarydiagnosis = listToArray(diagnosis[1], "<br/>", false, true) />
<cfset otherdiagnosis = listToArray(diagnosis[2], "<br/>", false, true) />
<cfset PrimaryICD = listToArray(ICD[1], "<br/>", false, true) />
<cfset OtherICD = listToArray(ICD[2], "<br/>", false, true) />
<cfset primaryICDDate = arrayNew(1) />
<cfset otherICDDate = arrayNew(1) />
<cfif arrayIsDefined(ICD_Date, 1)>
	<cfset primaryICDDate = listToArray(ICD_Date[1], ",", false, true) />
</cfif>
<cfif arrayIsDefined(ICD_Date, 2)>
	<cfset otherICDDate = listToArray(ICD_Date[2], ",", false, true) />
</cfif>

<cfquery datasource="#Application.DataSrc#" name="GetPhysician">
	SELECT pPhysicians.*
	FROM #Request.prefix_db_lookup#.pPhysicians
	WHERE Phys_ID = '#Form.Render_Phys_ID#'
</cfquery>

<cfquery datasource="#Application.DataSrc#" name="GetAssessDet">
	SELECT Assmt_ID, F179 AS Start_of_Care_M0030, F26 AS Assessment_Reason_M0100,
		F176 AS Assessment_Completed_M0090, F177 AS Certification_Start,
		F178 AS Certification_End, "" AS Rehab_Prognosis_M0270,
		pAdmit.M0030_START_CARE_DT, pAdmit.Date_F2F,
		pAdmit.clinical_authorization, pAdmit.Clinical_Manager, pAdmit.Case_Manager, pAdmit.case_authorization,
		pAdmit.Advance_Directive, pAssessments.F73, pAssessments.F72, pAssessments.Patient_ID
	FROM #Request.prefix_db_agency#.pAssessments
	JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID
	WHERE Assmt_ID = '#Form.Assmt_ID#'
	AND pAssessments.status = 0 AND pAdmit.status = 0
	ORDER BY F176 DESC
</cfquery>

<cfset F176 = GetAssessDet.Assessment_Completed_M0090 />

<cfquery name="GetEmps" datasource="#Application.DataSrc#">
	SELECT * FROM #Request.prefix_db_lookup#.pEmployee
	WHERE
	<cfif GetAssessDet.clinical_authorization EQ 1>
		Emp_ID = '#GetAssessDet.Clinical_Manager#'
	<cfelseif GetAssessDet.case_authorization EQ 1>
		Emp_ID = '#GetAssessDet.Case_Manager#'
	<cfelse>
		Emp_ID = '#Form.Created_by#'
	</cfif>
</cfquery>

<cfquery name="formagency" datasource="#Application.DataSrc#">
	SELECT Agency_Name, Agency_Address1, Agency_City, Agency_State, Agency_Zip, Natl_Provider_ID,
		Agency_Contact_Phone, Agency_Fax
	FROM #Request.prefix_db_lookup#.Agency
	WHERE Agency_ID = '#session.AgencyID#'
</cfquery>

<cfquery name="Get_location" datasource="#Application.DataSrc#">
	SELECT * FROM #Request.prefix_db_agency#.Locations
	WHERE Location_ID = '#Form.Location#'
</cfquery>

<cfquery name="GetPatient" datasource="#Application.DataSrc#">
	SELECT Email, Pt_language
	FROM #Request.prefix_db_agency#.pPatients
	WHERE Patient_ID = '#GetAssessDet.Patient_ID#'
</cfquery>

<cfquery name="GetAuths" datasource="#Application.DataSrc#">
	SELECT pAuths.Skill, pVisit_Frequency.Frequency
	FROM #Request.prefix_db_agency#.pAuths
	JOIN #Request.prefix_db_lookup#.pVisit_Frequency ON pAuths.visit_freq = pVisit_Frequency.Visit_No
	WHERE pAuths.Status = 0 AND pAuths.Assmt_ID = '#Form.Assmt_ID#'
	ORDER BY pAuths.Skill
</cfquery>

<cfif Form.Form_Status NEQ 'Signed & Received via Fax' AND Form.Form_Status NEQ 'Sent via Fax' AND len(getTimeZone.FAX_APINumber) GT 0>
	<cfquery name="updatepCMS4857" datasource="#Application.DataSrc#">
		UPDATE #Request.prefix_db_agency#.pCMS4857
		SET Form_Status = 'Printed Only'
		WHERE Order_ID = <cfqueryparam value="#url.afId#" cfsqltype="CF_SQL_INTEGER">
	</cfquery>
</cfif>

<cfset CrLf = Chr(13) />
<cfset socDate = Form.SOC_Item_2 NEQ '' ? Form.SOC_Item_2 : GetAssessDet.M0030_START_CARE_DT />
<cfset certFrom = Form.Certification_From NEQ '' ? Form.Certification_From : GetAssessDet.Certification_Start />
<cfset certTo = Form.Certification_To NEQ '' ? Form.Certification_To : GetAssessDet.Certification_End />

<!--- Provider block (same as PrintAssesmentForm.cfm) --->
<cfif Get_location.RecordCount GT 0>
	<cfset data = formagency.Agency_Name & ' (' & Get_location.Natl_Provider_ID & ')' & '*' & Get_location.Agency_Address1 & '*' & Get_location.Agency_City & ' ' & Get_location.Agency_State & ' ' & left(Get_location.Agency_Zip, 5) & '<br/>telephone ' & Get_location.Agency_Contact_Phone & ' fax ' & Get_location.Agency_Fax />
<cfelse>
	<cfset data = Form.Agy_Name & ' (' & Form.Agy_State & ')' & '*' & Form.Agy_Street & '*' & Form.Agy_City & ' ' & Form.Agy_State & ' ' & Form.Agy_State & '<br/>telephone ' & Form.Agy_State />
</cfif>
<cfset data = Form.Agy_Name & '<br/>' & Form.Agy_Street & '<br/>' & Form.Agy_City & ', ' & Form.Agy_State & ' ' & Form.Agy_Zip & '<br/>' & Form.Agy_Phone & '<br/>NPI ' & Form.Agy_NPI />
<cfset agencyFax = formagency.Agency_Fax />
<cfif Get_location.RecordCount GT 0>
	<cfset agencyFax = Get_location.Agency_Fax />
</cfif>

<cfset ordersDiscipline = "" />
<cfloop query="GetAuths">
	<cfset ordersDiscipline = ordersDiscipline & (ordersDiscipline NEQ "" ? ", " : "") & Skill & " " & Frequency />
</cfloop>

<!--- F175 narrative per skill: one row per skill for this admission.
      Falls back to F175 from pCMS4857 if pAssessments has none. --->
<cfquery name="GetNarratives" datasource="#Application.DataSrc#">
	SELECT F27 AS Skill, IFNULL(TRIM(F175),'') AS Narrative
	FROM #Request.prefix_db_agency#.pAssessments
	WHERE Admit_ID = (
		SELECT Admit_ID FROM #Request.prefix_db_agency#.pAssessments
		WHERE Assmt_ID = <cfqueryparam value="#Form.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">
		AND Status = 0
		LIMIT 1
	)
	AND (pAssessments.F26 NOT LIKE '9%' AND pAssessments.F26 NOT LIKE '7%' AND pAssessments.F26 NOT LIKE '8%' AND pAssessments.F26 NOT LIKE '6%')
	AND status = 0
	AND TRIM(IFNULL(F175,'')) <> ''
	ORDER BY F27
</cfquery>

<!--- Build a struct keyed by skill for easy lookup in the body template --->
<cfset narrativeBySkill = structNew() />
<cfloop query="GetNarratives">
	<cfset narrativeBySkill[Skill] = Narrative />
</cfloop>

<!--- Helper: return narrative for a skill, or empty string --->
<cffunction name="getNarrative" returntype="string" output="false">
	<cfargument name="skill"     type="string" required="yes" />
	<cfargument name="narratives" type="struct" required="yes" />
	<cfif structKeyExists(arguments.narratives, arguments.skill)>
		<cfreturn Trim(arguments.narratives[arguments.skill]) />
	</cfif>
	<cfreturn "" />
</cffunction>

<cffunction name="fmtBr" returntype="string" output="false">
	<cfargument name="txt" type="string" required="yes">
	<cfreturn Trim(Replace(Replace(arguments.txt, Chr(13), "<br/>", "ALL"), Chr(10), "<br/>", "ALL")) />
</cffunction>

<!--- Count valid other-diagnosis rows for medications rowspan --->
<cfset diagRowCount = 0 />
<cfloop from="1" to="#arrayLen(otherdiagnosis)#" index="di">
	<cfif otherdiagnosis[di] NEQ 1><cfset diagRowCount = diagRowCount + 1 /></cfif>
</cfloop>
<cfif diagRowCount LT 1><cfset diagRowCount = 1 /></cfif>

<cfset principalDx = "" />
<cfif ICD[1] NEQ 1 AND len(trim(ICD[1])) GT 0>
	<cfset principalDx = ICD[1] />
	<cfif diagnosis[1] NEQ 1 AND len(trim(diagnosis[1])) GT 0>
		<cfset principalDx = principalDx & ". " & diagnosis[1] />
	</cfif>
<cfelseif diagnosis[1] NEQ 1>
	<cfset principalDx = diagnosis[1] />
</cfif>

<cfset medDelims = Chr(13) & Chr(10) />

<!--- Caregiver Status: M2102d (F73) and M2102f (F72) from pAssessments --->
<cfset caregiverStatus = "" />
<cfif len(trim(GetAssessDet.F73)) GT 0>
	<cfset caregiverStatus = trim(GetAssessDet.F73) />
</cfif>
<cfif len(trim(GetAssessDet.F72)) GT 0>
	<cfif len(caregiverStatus) GT 0>
		<cfset caregiverStatus = caregiverStatus & "; " />
	</cfif>
	<cfset caregiverStatus = caregiverStatus & trim(GetAssessDet.F72) />
</cfif>

<cfparam name="url.format" default="pdf" />

<!--- HTML layout from PrintAssesmentForm_Redesign_Page1.html --->
<!--- PDF: cfdocument (cfhtmltopdf requires PDF Service Manager — not available on this server) --->
<cfif url.format EQ "html">
	<cfcontent type="text/html; charset=utf-8" reset="true" />
	<cfinclude template="PrintAssesmentForm_Redesign_Shell.cfm" />
<cfelse>
	<cfdocument format="pdf" orientation="portrait" overwrite="yes" fontEmbed="true"
		marginleft="0.35" marginright="0.35" margintop="0.35" marginbottom="0.5">
		<cfinclude template="PrintAssesmentForm_Redesign_Shell.cfm" />
	</cfdocument>
</cfif>
<cfabort />
