<!---
#10120 - Audit Trail > display edits to pAssessments
For pAssessments table: Status 3 = retired (previous version).
Record_Mod_By < 50: get user from SuperUsers; >= 50: from pEmployee.
Most recent edit first. Supports encrypted AID (Assmt_ID).
--->
<cfparam name="url.AID" default="0">
<cfparam name="url.admitid" default="0">

<cfif session.eaRole does not contain 'Project Manager'>
	<div class="alert alert-danger">Access denied. Audit Trail is available only for Project Manager role.</div>
	<cfabort>
</cfif>

<cfset assmtId = 0>
<cfif isNumeric(url.AID)>
	<cfset assmtId = val(url.AID)>
<cfelseif len(trim(url.AID)) GT 0>
	<cftry>
		<cfset assmtId = decrypt(url.AID, application.enckey, "AES", "Hex")>
		<cfcatch>
			<cftry>
				<cfset assmtId = decrypt(url.AID, "54kczhzgHTj4a8n+SRZPyg==", "AES", "Hex")>
				<cfcatch>
					<cfset assmtId = 0>
				</cfcatch>
			</cftry>
		</cfcatch>
	</cftry>
</cfif>

<cfset admitId = 0>
<cfif isNumeric(url.admitid)>
	<cfset admitId = val(url.admitid)>
<cfelseif len(trim(url.admitid)) GT 0>
	<cftry>
		<cfset admitId = decrypt(url.admitid, application.enckey, "AES", "Hex")>
		<cfcatch>
			<cfset admitId = 0>
		</cfcatch>
	</cftry>
</cfif>
<cfset encAdmitId = (isNumeric(admitId) AND admitId GT 0) ? encrypt(admitId, application.enckey, "AES", "Hex") : 0>

<cfscript>
	pm = CreateObject("Component", "Menu");
	myArgument = 'chart';
	pid = (isDefined("getP") AND getP.recordcount GT 0) ? getP.Patient_Id : session.cs.patientid;
	pm.MenuFunction(myArgument, pid, '', '', '', '');
</cfscript>

<cfquery name="GetColumns" datasource="#Application.DataSrc#">
	SELECT COLUMN_NAME, ORDINAL_POSITION
	FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA = <cfqueryparam value="#Request.prefix_db_agency#" cfsqltype="cf_sql_varchar">
	AND TABLE_NAME = 'pAssessments'
	ORDER BY ORDINAL_POSITION
</cfquery>

<cfset auditColumns = "">
<cfloop query="GetColumns">
	<cfset auditColumns = listAppend(auditColumns, COLUMN_NAME)>
</cfloop>

<cfset statusLabels = {0="Active",1="Inactive",2="Deleted",3="Retired (Previous Version)",4="Incomplete"}>
<cfset excludedAuditFields = "Status,AutoAssmt_ID,Record_Mod_By">
<cfset displayColumnLabels = {
	"Assmt_ID"="Assessment ID","AutoAssmt_ID"="Auto Assessment ID","Patient_ID"="Patient ID","Admit_ID"="Admit ID",
	"Status"="Status","F26"="Assessment Type","F27"="Skill","F176"="Completion Date","F177"="Cert Start","F178"="Cert End",
	"F25"="Completed","Record_Creation_Date"="Record Created","Record_Created_By"="Created By","Record_Mod_Date"="Last Modified","Record_Mod_By"="Modified By"
}>

<cfif assmtId EQ 0 OR NOT isNumeric(assmtId)>
	<div class="portlet box blue-chambray">
		<div class="portlet-title">
			<div class="caption"><i class="fa fa-history"></i> Audit Trail - pAssessments</div>
			<div class="actions">
				<a class="btn default btn-sm" href="index.cfm?page=patient&Id=#session.cs.enc_patientid#&cat=Patient">
					<i class="fa fa-arrow-left"></i> Back to Chart
				</a>
			</div>
		</div>
		<div class="portlet-body">
			<div class="alert alert-warning">
				<strong>Select an assessment</strong> to view its audit trail. <a href="index.cfm?page=patient&Id=#session.cs.enc_patientid#&cat=Patient">Go to Chart</a>
			</div>
		</div>
	</div>
<cfelse>
	<cfquery name="GetAuditHistory" datasource="#Application.DataSrc#">
		SELECT a.*,
			CASE 
				WHEN a.Status = 3 THEN 'Retired (Previous Version)'
				WHEN a.Status = 0 THEN 'Active'
				WHEN a.Status = 1 THEN 'Inactive'
				WHEN a.Status = 2 THEN 'Deleted'
				WHEN a.Status = 4 THEN 'Incomplete'
				ELSE CONCAT('Status ', a.Status)
			END AS StatusLabel,
			CASE 
				WHEN IFNULL(a.Record_Mod_By,0) < 50 THEN COALESCE(NULLIF(TRIM(su.Full_Name),''), su.Username, CONCAT('SuperUser ', IFNULL(a.Record_Mod_By,0)))
				ELSE CONCAT(COALESCE(e.Emp_Last,''), ', ', COALESCE(e.Emp_First,''))
			END AS ModifiedByName,
			CASE WHEN IFNULL(a.Record_Mod_By,0) >= 50 THEN e.Emp_Email ELSE NULL END AS ModifiedByEmail
		FROM #Request.prefix_db_agency#.pAssessments a
		LEFT JOIN #Request.prefix_db_lookup#.pEmployee e ON e.Emp_ID = a.Record_Mod_By AND IFNULL(a.Record_Mod_By,0) >= 50
		LEFT JOIN #Request.prefix_db_lookup#.SuperUsers su ON su.User_ID = a.Record_Mod_By AND IFNULL(a.Record_Mod_By,0) < 50
		WHERE a.Assmt_ID = <cfqueryparam value="#assmtId#" CFSQLType="CF_SQL_INTEGER">
		AND a.Patient_ID = <cfqueryparam value="#session.cs.patientid#" CFSQLType="CF_SQL_INTEGER">
		ORDER BY a.AutoAssmt_ID DESC, a.Record_Mod_Date DESC
	</cfquery>

	<div class="portlet box blue-chambray">
		<div class="portlet-title">
			<div class="caption">
				<i class="fa fa-history"></i> Audit Trail - pAssessments
				<cfif GetAuditHistory.recordcount GT 0>
					<cfoutput> &ndash; Assessment ID #GetAuditHistory.Assmt_ID#</cfoutput>
				</cfif>
			</div>
			<div class="actions">
				<cfoutput>
					<a class="btn default btn-sm" href="index.cfm?page=patient&Id=#session.cs.enc_patientid#&cat=Patient<cfif encAdmitId NEQ 0>&admitid=#encAdmitId#</cfif>">
						<i class="fa fa-arrow-left"></i> Back to Chart
					</a>
				</cfoutput>
			</div>
		</div>
		<div class="portlet-body">
			<p class="text-muted">
				<strong>Note:</strong> For pAssessments, Status 3 indicates a retired (previous version) record. Most recent edits are shown first.
			</p>
			<cfif GetAuditHistory.recordcount EQ 0>
				<div class="alert alert-info">
					<strong>No audit history found</strong> for this assessment.
				</div>
			<cfelse>
				<cfset totalEdits = GetAuditHistory.recordcount - 1>
				<cfif totalEdits GT 0>
					<cfoutput>
						<div class="alert alert-success margin-bottom-15">
							<h5 style="margin-top:0;"><i class="fa fa-list"></i> <strong>Complete Change History</strong> &ndash; #totalEdits# edit(s) on this assessment (most recent first)</h5>
							<p class="margin-bottom-0">All changes are listed below.</p>
						</div>
					</cfoutput>
				</cfif>

				<cfoutput query="GetAuditHistory">
					<cfset isCurrent = (Status NEQ 3)>
					<cfset isCreationRecord = (GetAuditHistory.currentRow EQ GetAuditHistory.recordcount)>
					<cfset showChanges = false>
					<cfset changeTitle = "">
					<cfset olderRow = 0>
					<cfset newerRow = 0>
					<cfset oldAutoAssmtID = "">
					<cfset newAutoAssmtID = "">
					<cfset changeRows = []>

					<cfif GetAuditHistory.currentRow EQ 1 AND GetAuditHistory.recordcount GT 1>
						<cfset showChanges = true>
						<cfset changeTitle = "What Data Was Modified (Edit 1 of #totalEdits# &ndash; most recent):">
						<cfset olderRow = 2>
						<cfset newerRow = 1>
					<cfelseif GetAuditHistory.currentRow GT 1 AND GetAuditHistory.currentRow LT GetAuditHistory.recordcount>
						<cfset showChanges = true>
						<cfset editNum = GetAuditHistory.currentRow>
						<cfset changeTitle = "What Data Was Modified (Edit " & editNum & " of " & totalEdits & "):">
						<cfset olderRow = GetAuditHistory.currentRow + 1>
						<cfset newerRow = GetAuditHistory.currentRow>
					</cfif>

					<cfif showChanges AND olderRow GT 0 AND newerRow GT 0 AND olderRow LTE GetAuditHistory.recordcount>
						<cfset rowForOld = olderRow>
						<cfset rowForNew = newerRow>
						<cfset oldAutoAssmtID = structKeyExists(GetAuditHistory, "AutoAssmt_ID") ? GetAuditHistory["AutoAssmt_ID"][rowForOld] : "">
						<cfset newAutoAssmtID = structKeyExists(GetAuditHistory, "AutoAssmt_ID") ? GetAuditHistory["AutoAssmt_ID"][rowForNew] : "">
						<cfloop list="#auditColumns#" index="fld">
							<cfif listFindNoCase(excludedAuditFields, fld)>
								<cfcontinue>
							</cfif>
							<cfif structKeyExists(GetAuditHistory, fld)>
								<cfset oldVal = GetAuditHistory[fld][rowForOld]>
								<cfset newVal = GetAuditHistory[fld][rowForNew]>
								<cfif NOT isSimpleValue(oldVal)><cfset oldVal = ""></cfif>
								<cfif NOT isSimpleValue(newVal)><cfset newVal = ""></cfif>
								<cfset oldVal = trim(oldVal)>
								<cfset newVal = trim(newVal)>
								<cfif isDate(oldVal)><cfset oldVal = dateFormat(oldVal,"mm/dd/yyyy") & " " & timeFormat(oldVal,"HH:mm:ss")></cfif>
								<cfif isDate(newVal)><cfset newVal = dateFormat(newVal,"mm/dd/yyyy") & " " & timeFormat(newVal,"HH:mm:ss")></cfif>
								<cfif oldVal NEQ newVal>
									<cfif fld EQ "Status">
										<cfif structKeyExists(statusLabels, oldVal)><cfset oldVal = statusLabels[oldVal] & " (#oldVal#)"></cfif>
										<cfif structKeyExists(statusLabels, newVal)><cfset newVal = statusLabels[newVal] & " (#newVal#)"></cfif>
									</cfif>
									<cfset fldLabel = structKeyExists(displayColumnLabels, fld) ? displayColumnLabels[fld] : fld>
									<cfset arrayAppend(changeRows, {field=fldLabel, old=oldVal, new=newVal})>
								</cfif>
							</cfif>
						</cfloop>
					</cfif>

					<cfif isCurrent OR isCreationRecord OR arrayLen(changeRows) GT 0>
						<div class="panel panel-<cfif isCurrent>success<cfelse>default</cfif> margin-bottom-15">
							<div class="panel-heading">
								<h4 class="panel-title">
									<cfif isCurrent>
										<span class="label label-success">Current</span> (most recent)
									<cfelse>
										<span class="label label-default">Revision #GetAuditHistory.currentRow# of #GetAuditHistory.recordcount#</span>
									</cfif>
									<cfif isCreationRecord AND structKeyExists(GetAuditHistory, "AutoAssmt_ID")>
										&nbsp;<span class="label label-info">#GetAuditHistory.AutoAssmt_ID# = record created</span>
									</cfif>
									&nbsp;&ndash;&nbsp;#StatusLabel#
								</h4>
							</div>
							<div class="panel-body">
								<div class="well well-sm margin-bottom-15" style="background:##f9f9f9;">
									<h5 style="margin-top:0; margin-bottom:10px;"><i class="fa fa-user"></i> <strong>Who Modified:</strong></h5>
									<cfif Record_Mod_By GT 0>
										<cfif len(trim(ModifiedByName)) GT 0 AND ModifiedByName NEQ ", ">
											#HTMLEditFormat(ModifiedByName)#
											<cfif len(trim(ModifiedByEmail)) GT 0> (#HTMLEditFormat(ModifiedByEmail)#)</cfif>
										<cfelse>
											User ID #Record_Mod_By#
										</cfif>
									<cfelse>
										System / Unknown
									</cfif>
									<br><br>
									<h5 style="margin:0 0 5px 0;"><i class="fa fa-clock-o"></i> <strong>When Modified:</strong></h5>
									<cfif isDate(Record_Creation_Date)>
										#DateFormat(Record_Creation_Date, "mm/dd/yyyy")# at #TimeFormat(Record_Creation_Date, "HH:mm:ss")#
									<cfelse>
										N/A
									</cfif>
								</div>

								<cfif arrayLen(changeRows) GT 0>
									<cfset versionPair = "#oldAutoAssmtID# → #newAutoAssmtID#">
									<div class="alert alert-info margin-top-10">
										<h5 style="margin-top:0;"><i class="fa fa-edit"></i> <strong>#changeTitle#</strong> <span class="text-muted">(#versionPair#)</span></h5>
										<table class="table table-bordered table-condensed table-striped" style="margin-bottom:0;">
											<thead>
												<tr class="info">
													<th>Field</th>
													<th>Previous Value</th>
													<th>New Value</th>
												</tr>
											</thead>
											<tbody>
												<cfloop array="#changeRows#" index="row">
													<tr>
														<td class="bold">#HTMLEditFormat(row.field)#</td>
														<td>#HTMLEditFormat(row.old)#</td>
														<td><strong>#HTMLEditFormat(row.new)#</strong></td>
													</tr>
												</cfloop>
											</tbody>
										</table>
									</div>
								</cfif>
							</div>
						</div>
					</cfif>
				</cfoutput>
			</cfif>
		</div>
	</div>
</cfif>
