<!---
  blockRecertF176Move for sync_followup_assessment_f176.cfm. Kept in its own template so it is included only once
  per request: that sync template can be included several times (e.g. patientvisit_action.cfm), and ColdFusion
  rejects a cffunction declared again by a second include. Reads the sync* variables set by the calling template.
--->
<cffunction name="blockRecertF176Move" returntype="boolean" output="false">
	<cfargument name="targetAssmtId" type="numeric" required="true" />
	<cfargument name="oldF176" type="any" required="true" />
	<cfset var oldDate = "" />
	<cfset var ownedByActive = "" />
	<cfset var missedOwner = "" />
	<cfif NOT syncIsRecert OR NOT IsDate(arguments.oldF176)>
		<cfreturn false />
	</cfif>
	<cfset oldDate = DateFormat(arguments.oldF176, "yyyy-mm-dd") />
	<cfif oldDate EQ syncVisitDateSql>
		<cfreturn false />
	</cfif>
	<cfquery name="ownedByActive" datasource="#Application.DataSrc#">
		SELECT Schedule_ID
		FROM #Request.prefix_db_agency#.pSchedules
		WHERE Patient_ID = <cfqueryparam value="#syncPatientId#" cfsqltype="cf_sql_integer">
		AND Status = 0 AND IFNULL(Missed, 0) = 0
		AND Visit_Type = <cfqueryparam value="#syncVisitType#" cfsqltype="cf_sql_varchar">
		AND (
			Assmt_ID = <cfqueryparam value="#Val(arguments.targetAssmtId)#" cfsqltype="cf_sql_integer">
			OR Visit_Date = <cfqueryparam value="#oldDate#" cfsqltype="cf_sql_date">
		)
		<cfif syncExcludeScheduleId GT 0>
			AND Schedule_ID <> <cfqueryparam value="#syncExcludeScheduleId#" cfsqltype="cf_sql_integer">
		</cfif>
		LIMIT 1
	</cfquery>
	<cfif ownedByActive.recordcount GT 0>
		<cfreturn true />
	</cfif>
	<cfif syncNewVisit>
		<cfquery name="missedOwner" datasource="#Application.DataSrc#">
			SELECT Schedule_ID
			FROM #Request.prefix_db_agency#.pSchedules
			WHERE Patient_ID = <cfqueryparam value="#syncPatientId#" cfsqltype="cf_sql_integer">
			AND Status = 0 AND IFNULL(Missed, 0) > 0
			AND Visit_Type = <cfqueryparam value="#syncVisitType#" cfsqltype="cf_sql_varchar">
			AND Visit_Date = <cfqueryparam value="#oldDate#" cfsqltype="cf_sql_date">
			<cfif syncExcludeScheduleId GT 0>
				AND Schedule_ID <> <cfqueryparam value="#syncExcludeScheduleId#" cfsqltype="cf_sql_integer">
			</cfif>
			LIMIT 1
		</cfquery>
		<cfif missedOwner.recordcount EQ 0>
			<cfreturn true />
		</cfif>
	</cfif>
	<cfreturn false />
</cffunction>
