<!--- #10654 / Ashley: F175 Assessment Narrative per skill for a 485.
     Expects: narrativeOrderAssmtId (pCMS4857.Assmt_ID / Form.Assmt_ID).
     Sets: narrativeAdmitID, narrativeBySkill, narrativeAssmtIdBySkill.

     Prefer THIS order's Assmt_ID when it has F175. If empty (e.g. new Recert),
     fall back only to the same OASIS reason family (LEFT(F26,1) in 1/3/4) with
     Assmt_ID <= order Assmt — never pull ROC SN narrative onto SOC or Recert.

     Therapy (PT/OT/ST): also allow Adult/Pediatric Evaluation F175 on the same
     admit (evals use F26 like "OT Adult Evaluation", not digit 1/3/4), and
     same-reason therapy OASIS even when Assmt_ID > the 485 order Assmt
     (therapy often completed after SN SOC).

     narrativeAssmtIdBySkill: order Assmt's skill → order Assmt_ID (so SN edits on a
     new Recert write onto that Recert). Other skills → source Assmt_ID (PT F175
     must not save onto the SN order Assmt). --->
<cfparam name="narrativeOrderAssmtId" default="0" />
<cfset narrativeBySkill = StructNew() />
<cfset narrativeAssmtIdBySkill = StructNew() />
<cfset narrativeAdmitID = 0 />
<cfset narrativeOrderReason = "" />
<cfset narrativeOrderSkill = "" />

<cfif Val(narrativeOrderAssmtId) GT 0>
	<cfquery name="getNarrativeOrderAssmt" datasource="#Application.DataSrc#">
		SELECT Admit_ID, LEFT(F26, 1) AS ReasonDigit, UCase(Trim(IFNULL(F27, ''))) AS OrderSkill
		FROM #Request.prefix_db_agency#.pAssessments
		WHERE Assmt_ID = <cfqueryparam value="#Val(narrativeOrderAssmtId)#" cfsqltype="cf_sql_integer">
		ORDER BY CASE WHEN status = 0 THEN 0 ELSE 1 END
		LIMIT 1
	</cfquery>
	<cfif getNarrativeOrderAssmt.recordcount GT 0>
		<cfset narrativeAdmitID = Val(getNarrativeOrderAssmt.Admit_ID) />
		<cfset narrativeOrderReason = Trim(getNarrativeOrderAssmt.ReasonDigit & "") />
		<cfset narrativeOrderSkill = Trim(getNarrativeOrderAssmt.OrderSkill & "") />
	</cfif>
</cfif>

<cfif narrativeAdmitID GT 0 AND Val(narrativeOrderAssmtId) GT 0>
	<cfquery name="getAdmitNarratives" datasource="#Application.DataSrc#">
		SELECT Assmt_ID, F27 AS Skill, IFNULL(TRIM(F175), '') AS Narrative, F26
		FROM #Request.prefix_db_agency#.pAssessments
		WHERE Admit_ID = <cfqueryparam value="#narrativeAdmitID#" cfsqltype="cf_sql_integer">
		AND status = 0
		AND (F26 NOT LIKE '9%' AND F26 NOT LIKE '7%' AND F26 NOT LIKE '8%' AND F26 NOT LIKE '6%')
		AND TRIM(IFNULL(F175, '')) <> ''
		AND (
			Assmt_ID = <cfqueryparam value="#Val(narrativeOrderAssmtId)#" cfsqltype="cf_sql_integer">
			<!--- Same SOC/ROC/Recert family only; newest prior with narrative (e.g. Recert→prior Recert, not ROC) --->
			<cfif Len(narrativeOrderReason) EQ 1>
				OR (
					LEFT(F26, 1) = <cfqueryparam value="#narrativeOrderReason#" cfsqltype="cf_sql_varchar">
					AND Assmt_ID <= <cfqueryparam value="#Val(narrativeOrderAssmtId)#" cfsqltype="cf_sql_integer">
				)
				<!--- Therapy evals / later therapy OASIS for the same reason (not SN cross-reason) --->
				OR (
					F27 IN ('PT', 'OT', 'ST')
					AND (
						F26 LIKE '%Evaluation%'
						OR LEFT(F26, 1) = <cfqueryparam value="#narrativeOrderReason#" cfsqltype="cf_sql_varchar">
					)
				)
			</cfif>
		)
		ORDER BY
			F27,
			CASE WHEN Assmt_ID = <cfqueryparam value="#Val(narrativeOrderAssmtId)#" cfsqltype="cf_sql_integer"> THEN 0 ELSE 1 END,
			<!--- Prefer same-reason OASIS over Evaluation when both qualify --->
			CASE
				WHEN <cfqueryparam value="#narrativeOrderReason#" cfsqltype="cf_sql_varchar"> <> ''
					AND LEFT(F26, 1) = <cfqueryparam value="#narrativeOrderReason#" cfsqltype="cf_sql_varchar">
				THEN 0 ELSE 1
			END,
			Assmt_ID DESC
	</cfquery>
	<cfloop query="getAdmitNarratives">
		<cfset narrSkill = UCase(Trim(Skill)) />
		<cfset narrText = Trim(Narrative) />
		<cfif Len(narrSkill) AND Len(narrText) AND NOT StructKeyExists(narrativeBySkill, narrSkill)>
			<!--- Plain text for textarea (match SOC notes display) --->
			<cfset narrText = reReplace(narrText, "<[^>]*>", "", "all") />
			<cfset narrText = Replace(narrText, "&nbsp;", " ", "all") />
			<cfset narrText = Replace(narrText, "&amp;", "&", "all") />
			<cfset narrText = Replace(narrText, "&lt;", "<", "all") />
			<cfset narrText = Replace(narrText, "&gt;", ">", "all") />
			<cfset narrText = Replace(narrText, "&quot;", '"', "all") />
			<cfset narrativeBySkill[narrSkill] = Trim(narrText) />
			<!--- Same skill as the 485 order Assmt (usually SN): save onto THIS order Assmt even when
			     text was copied from a prior same-reason Assmt (new Recert with empty F175).
			     Other skills (PT/OT/ST/…): save onto the Assmt that owns that skill's F175 —
			     never write PT narrative onto the SN order Assmt. --->
			<cfif Len(narrativeOrderSkill) AND narrSkill EQ narrativeOrderSkill>
				<cfset narrativeAssmtIdBySkill[narrSkill] = Val(narrativeOrderAssmtId) />
			<cfelse>
				<cfset narrativeAssmtIdBySkill[narrSkill] = Val(Assmt_ID) />
			</cfif>
		</cfif>
	</cfloop>
	<!--- Therapy eval Assmts with empty F175 still need F175_Assmt_ID_* so new OT/PT text
	     does not save onto the SN SOC order Assmt (Baker / Cook). --->
	<cfquery name="getTherapyEvalAssmtIds" datasource="#Application.DataSrc#">
		SELECT Assmt_ID, UCase(Trim(IFNULL(F27, ''))) AS Skill, F26
		FROM #Request.prefix_db_agency#.pAssessments
		WHERE Admit_ID = <cfqueryparam value="#narrativeAdmitID#" cfsqltype="cf_sql_integer">
		AND status = 0
		AND F27 IN ('PT', 'OT', 'ST')
		AND F26 LIKE '%Evaluation%'
		ORDER BY
			CASE WHEN TRIM(IFNULL(F175, '')) <> '' THEN 0 ELSE 1 END,
			Assmt_ID DESC
	</cfquery>
	<cfloop query="getTherapyEvalAssmtIds">
		<cfset narrSkill = UCase(Trim(Skill)) />
		<cfif Len(narrSkill) AND NOT StructKeyExists(narrativeAssmtIdBySkill, narrSkill)>
			<cfset narrativeAssmtIdBySkill[narrSkill] = Val(Assmt_ID) />
		</cfif>
	</cfloop>
	<!--- #10838: OT/PT/ST visit notes that were merged into the SN admission narrative
	     display and print under that discipline. Saving the 485 writes them back to the right F175. --->
	<cfif StructKeyExists(narrativeBySkill, "SN") AND Len(Trim(narrativeBySkill["SN"]))>
		<cfset f175SplitCFC = createObject("component", "components.general.progressnotes") />
		<cfquery name="getAdmitVisitNotes10838" datasource="#Application.DataSrc#">
			SELECT TRIM(s.Notes) AS Notes,
				IFNULL(s.Skill, '') AS Skill,
				IFNULL(s.Visit_Type, '') AS Visit_Type,
				IFNULL(r.HCPCS, '') AS HCPCS
			FROM #Request.prefix_db_agency#.pSchedules s
			INNER JOIN #Request.prefix_db_agency#.pAssessments a
				ON a.Assmt_ID = s.Assmt_ID AND a.Status = 0
			LEFT JOIN #Request.prefix_db_agency#.pRevenue_Code r
				ON r.Rev_CodeID = s.HCPCS_ID AND r.Status = 0
			WHERE a.Admit_ID = <cfqueryparam value="#narrativeAdmitID#" cfsqltype="cf_sql_integer">
			AND s.Status = 0
			AND CHAR_LENGTH(TRIM(IFNULL(s.Notes, ''))) >= 40
			ORDER BY CHAR_LENGTH(TRIM(s.Notes)) DESC
		</cfquery>
		<cfset snNarrSplit = narrativeBySkill["SN"] />
		<cfloop query="getAdmitVisitNotes10838">
			<cfset noteSkill10838 = f175SplitCFC.normalizeNarrativeSkill(Skill, HCPCS, Visit_Type) />
			<cfif NOT ListFind("PT,OT,ST", noteSkill10838) OR NOT f175SplitCFC.f175SectionMatchesNote(snNarrSplit, Notes)>
				<cfcontinue />
			</cfif>
			<cfset snNarrSplit = f175SplitCFC.removeF175Section(snNarrSplit, Notes) />
			<cfset already10838 = StructKeyExists(narrativeBySkill, noteSkill10838) ? narrativeBySkill[noteSkill10838] : "" />
			<cfif NOT Len(already10838) OR NOT f175SplitCFC.f175SectionMatchesNote(already10838, Notes)>
				<cfif Len(already10838)>
					<cfset narrativeBySkill[noteSkill10838] = already10838 & chr(13) & chr(10) & "------------------------------" & chr(13) & chr(10) & Trim(Notes) />
				<cfelse>
					<cfset narrativeBySkill[noteSkill10838] = Trim(Notes) />
				</cfif>
			</cfif>
		</cfloop>
		<cfset narrativeBySkill["SN"] = Trim(snNarrSplit) />
	</cfif>
</cfif>
