<cfabort>
<cfparam name="url.Agency_ID" default="0">
<cfparam name="url.redirect" default="">
<cfparam name="url.delete" default="">
        <cfif CGI.SERVER_NAME EQ "127.0.0.1" || CGI.SERVER_NAME EQ "localhost">
                <cfset Application.DEV = true />
                <cfset application.downloadpath="http://localhost/">
                <cfset application.webdatapath="D:/MHCB_bitbucket/secure-mhcb/datafiles/">
                <cfset application.datapath="D:/MHCB_bitbucket/secure-mhcb/datafiles/">
                <cfset application.telephonypath="D:/MHCB_bitbucket/secure-mhcb/exportdata/">
                <cfset application.secure="http://localhost/">
                <cfset application.siteURL="http://localhost/">
                <cfset application.rootfolder="http://localhost/">
                <cfset Application.ServerName = "LOCAL IT TEAM ">
        <cfelseif CGI.SERVER_NAME EQ "52.23.186.30" || CGI.SERVER_NAME EQ "dev.myhomecarebiz.com">
                <cfset Application.DEV = true />
                <cfset application.downloadpath="http://dev.myhomecarebiz.com/">
                <cfset application.webdatapath="#application.downloadpath#/datafiles/">
                <cfset application.datapath="/var/www/datafiles/">
                <cfset application.telephonypath="/var/www/exportdata/">
                <cfset application.secure="http://dev.myhomecarebiz.com/">
                <cfset application.siteURL="http://dev.myhomecarebiz.com/">
                <cfset application.rootfolder="http://dev.myhomecarebiz.com/">
                <cfset Application.ServerName = "DEV Server ">
        <cfelseif CGI.SERVER_NAME EQ "98.87.35.139" || CGI.SERVER_NAME EQ "devsecure.myhomecarebiz.com">
                <cfset Application.DEV = true />
                <cfset application.downloadpath="https://devsecure.myhomecarebiz.com/">
                <cfset application.webdatapath="#application.downloadpath#/datafiles/">
                <cfset application.datapath="/var/www/datafiles/">
                <cfset application.telephonypath="/var/www/exportdata/">
                <cfset application.secure="https://devsecure.myhomecarebiz.com/">
                <cfset application.siteURL="https://devsecure.myhomecarebiz.com/">
                <cfset application.rootfolder="https://devsecure.myhomecarebiz.com/">
                <cfset Application.ServerName = "DEV Secure Server ">
                
        <cfelseif CGI.SERVER_NAME EQ "54.175.136.41" || CGI.SERVER_NAME EQ "stagesecure.myhomecarebiz.com" >
                <cfset Application.DEV = true />
                <cfset application.downloadpath="https://stagesecure.myhomecarebiz.com/">
                <cfset application.webdatapath="#application.downloadpath#/datafiles/">
                <cfset application.datapath="/var/www/datafiles/">
                <cfset application.telephonypath="/var/www/exportdata/">
                <cfset application.secure="https://stagesecure.myhomecarebiz.com/">
                <cfset application.siteURL="https://stagesecure.myhomecarebiz.com/">
                <cfset application.rootfolder="https://stagesecure.myhomecarebiz.com/">
                <cfset Application.ServerName = "Stage Server">
            <!---Amazon Live Server--->
        <cfelse>
                <cfset Application.DEV = false />
                <cfset application.downloadpath="https://secure.myhomecarebiz.com">
                <cfset application.webdatapath="#application.downloadpath#/datafiles/">
                <cfset application.datapath="/var/www/datafiles/">
                <cfset application.telephonypath="/var/www/exportdata/">
                <cfset application.secure="https://secure.myhomecarebiz.com/">
                <cfset application.siteURL="https://secure.myhomecarebiz.com/">
                <cfset application.rootfolder="https://secure.myhomecarebiz.com/">
                <cfset Application.ServerName = "#cgi.server_NAME#">
                <cfset Application.GoogleMapsAPIKey = "AIzaSyAXWgATrPBtb7em-iICftXhJT-e6a4BroQ"/>
                   <!---<cfinclude template="/Application_error_settings.cfm" />--->
        </cfif>
<cfset currentDate = CreateODBCDate(Now())>
<cfset currentTimestamp = Now()>
<cfset encryptKey = "54kczhzgHTj4a8n+SRZPyg==">
 
<cfquery name="Agencylist" datasource="#Application.DataSrc#">
    SELECT agency_id, Agency_Login, Agency_Name
    FROM #Request.prefix_db_lookup#.Agency
    WHERE status = 'active'
    <cfif url.Agency_ID NEQ 0>
        AND Agency_ID = <cfqueryparam value="#url.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
    </cfif>
    ORDER BY agency_id
</cfquery>

<cfloop query="Agencylist">
    <cfset Request.prefix_db_agency = 'agency_' & Agencylist.Agency_ID>

    <cftry>

    <!--- Delete Email_Daily_QA records if URL delete parameter is provided --->
    <cfif url.delete NEQ "">
        <cfquery name="deleteEmailDailyQA" datasource="#Application.DataSrc#">
            DELETE FROM #Request.prefix_db_agency#.Email_Daily_QA
             </cfquery>
    <cfelse>
        <!--- Update old records status to 1 before inserting new records --->
        <cfquery name="updateOldEmailDailyQA" datasource="#Application.DataSrc#">
            UPDATE #Request.prefix_db_agency#.Email_Daily_QA
            SET status = 1
            WHERE status = 0
        </cfquery>
    </cfif>

    <!--- Incomplete assessments --->
    <cfquery name="getIncompleteAssessments" datasource="#Application.DataSrc#">
        SELECT
             count(pEmployee.Emp_ID) as ecount,
             pEmployee.Emp_ID as empIdValue,
             (SELECT Admit_ID
             FROM #Request.prefix_db_agency#.pAdmit
             WHERE Patient_ID = pAssessments.Patient_ID AND Status = 0
             ORDER BY M0030_START_CARE_DT DESC
             LIMIT 1) AS latest_admit,
             FROM #Request.prefix_db_agency#.pAssessments
        JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID
            AND pAdmit.Status = 0
            AND pAdmit.Drafts = 0
        JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID
            AND pPatients.Status IN (0)
        LEFT JOIN #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID = pAssessments.Assmt_ID
            AND assessment_assign.F26 = pAssessments.F26
        LEFT JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = assessment_assign.Emp_ID
            AND pEmployee.Status = 0
        WHERE pAssessments.Status = 0
          AND (pAssessments.F25 IS NULL OR pAssessments.F25 = '0')
          AND pAssessments.F176 < <cfqueryparam value="#DateFormat(now(),'yyyy-mm-dd')#" cfsqltype="CF_SQL_DATE">
        group by Emp_ID
    </cfquery>

    <cfloop query="getIncompleteAssessments">        
        <cfquery name="insertIncompleteAssessments" datasource="#Application.DataSrc#">
            INSERT INTO #Request.prefix_db_agency#.Dash_emp_count
            (Daily_QA_Date, Emp_ID, Emp_Count, Header, Created_Date, status)
            VALUES (
                <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                <cfqueryparam value="#getIncompleteAssessments.ecount#" cfsqltype="CF_SQL_INTEGER">,
                <cfqueryparam value="incomplete assessment" cfsqltype="CF_SQL_VARCHAR">,
                <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
            )
        </cfquery>
    </cfloop>

    <!--- Orphan symptoms Field (matching Orphan_Symptoms_Field.cfm getsymp_recon query logic) --->
    <!--- This query matches what Orphan_Symptoms_Field.cfm expects to see in Email_Daily_QA --->
    <cfquery name="getOrphanSymptomsField" datasource="#Application.DataSrc#">
        SELECT
         count(pEmployee.Emp_ID) as ecount,
            pEmployee.Emp_ID AS AssignedEmpID,
            (SELECT Admit_ID 
             FROM #Request.prefix_db_agency#.pAdmit 
             WHERE Patient_ID = pAssessments.Patient_ID AND Status = 0
             ORDER BY M0030_START_CARE_DT DESC 
             LIMIT 1) AS latest_admit
        FROM #Request.prefix_db_agency#.pAssessments pAssessments
        JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID AND pAdmit.Status = 0
        JOIN #Request.prefix_db_agency#.pPatients pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID AND pPatients.Status = 0
        LEFT OUTER JOIN #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID = pAssessments.Assmt_ID
            AND assessment_assign.F26 = pAssessments.F26
        JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = assessment_assign.Emp_ID
            AND pEmployee.Status = 0
        JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pAssessments.Status = 0
        AND (pAssessments.F26 LIKE '1%' OR pAssessments.F26 LIKE '4%')
        AND pAssessments.F25 = 1
        AND pAssessments.Orphan_Field IN (0,2)
        AND pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        GROUP BY AssignedEmpID
    </cfquery>

    <!--- Orphan symptoms QA - matches Orphan_Symptoms_QA.cfm GetAssessments query exactly --->
    <!--- Process Orphan Symptoms Field (matching Orphan_Symptoms_Field.cfm) --->
     <cfloop query="getOrphanSymptomsField">        
        <cfquery name="getOrphanSymptomsField" datasource="#Application.DataSrc#">
            INSERT INTO #Request.prefix_db_agency#.Dash_emp_count
            (Daily_QA_Date, Emp_ID, Emp_Count, Header, Created_Date, status)
            VALUES (
                <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                <cfqueryparam value="#AssignedEmpID#" cfsqltype="CF_SQL_INTEGER">,
                <cfqueryparam value="#getOrphanSymptomsField.ecount#" cfsqltype="CF_SQL_INTEGER">,
                <cfqueryparam value="Incomplete Orphan Symptoms" cfsqltype="CF_SQL_VARCHAR">,
                <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
            )
        </cfquery>
        </cfloop>

    <!--- Missed visit needs documentation --->
    <cfquery name="getMissedVisitNeedsDocumentation" datasource="#Application.DataSrc#">
   Select
       count(pEmployee.Emp_ID) as ecount,
            pEmployee.Emp_ID AS AssignedEmpID,
            FROM agency_1150.pSchedules pSchedules
        JOIN agency_1150.pPatients pPatients ON pPatients.Patient_ID = pSchedules.Patient_ID
             AND pPatients.Status IN (0)
        JOIN hhapowerpath.pEmployee pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
            AND pEmployee.Status = 0
        WHERE pSchedules.Status = 0
          AND pSchedules.Missed > 0
          AND pSchedules.Notes IS NULL
        GROUP BY AssignedEmpID
    </cfquery>

    <cfloop query="getMissedVisitNeedsDocumentation">
    <cfquery name="getMissedVisitNeedsDocumentation" datasource="#Application.DataSrc#">
            INSERT INTO #Request.prefix_db_agency#.Dash_emp_count
            (Daily_QA_Date, Emp_ID, Emp_Count, Header, Created_Date, status)
            VALUES (
                <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                <cfqueryparam value="#getMissedVisitNeedsDocumentation.ecount#" cfsqltype="CF_SQL_INTEGER">,
                <cfqueryparam value="Missed Visits Need Documentation" cfsqltype="CF_SQL_VARCHAR">,
                <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
            )
        </cfquery>
    </cfloop>

        <!--- Late progress notes - uses exact query from pending_visitsnew.cfm --->
    <cfquery name="getLateProgressNotes" datasource="#Application.DataSrc#">
        SELECT pPatients.Patient_ID, pPatients.Pt_Last AS PatientLast, pPatients.Pt_First AS PatientFirst, 
        pAssessments.F26, pSchedules.Assmt_ID, pSchedules.Schedule_ID, pSchedules.Visit_Date, pSchedules.Visit_Type, pSchedules.Skill,
        pSchedules.Emp_ID, pCareplan.Description, pEmployee.Emp_Last, pEmployee.Emp_First, pSchedules.pgnotesdraft,
        (SELECT pAss.F25 FROM #Request.prefix_db_agency#.pAssessments pAss
            WHERE pAss.Patient_ID = pPatients.Patient_ID 
            AND (LEFT(pSchedules.Visit_Type,1) = LEFT(pAss.F26,1)
             OR (pAssessments.F26 LIKE pSchedules.Visit_Type)) AND pAss.F176 = pSchedules.Visit_Date
            AND pAss.Status = 0 LIMIT 0,1)
        AS assessments_completeds,
        (SELECT pAss.F25 FROM #Request.prefix_db_agency#.pAssessments pAss
            WHERE pAss.Patient_ID = pAssessments.Patient_ID
            AND pAss.Admit_ID = pAssessments.Admit_ID
            AND pAss.F26 = (CASE 
                WHEN (pSchedules.Visit_Type = "1 - SOC - SN") THEN '1 - Start of care - further visits planned'
                WHEN (pSchedules.Visit_Type = "1 - SOC - PT") THEN '1 - Start of care - further visits planned - Physical Therapy'
                WHEN (pSchedules.Visit_Type = "1 - SOC - OT") THEN '1 - Start of care - further visits planned - Occupational Therapy'
                WHEN (pSchedules.Visit_Type = "3 - ROC - SN" || pSchedules.Visit_Type = "3 - ROC - PT") THEN '3 - Resumption of care (after inpatient stay)'
                WHEN (pSchedules.Visit_Type = "PT Eval") THEN 'PT Adult Evaluation'
                WHEN (pSchedules.Visit_Type = "OT Eval") THEN 'OT Adult Evaluation'
                WHEN (pSchedules.Visit_Type = "ST Eval") THEN 'ST Adult Evaluation'
                WHEN (pSchedules.Visit_Type = "SN Eval") THEN 'SN Adult Evaluation'
                WHEN (pSchedules.Visit_Type = "MSW Eval") THEN 'MSW Evaluation'
                WHEN (pSchedules.Visit_Type = "PT FU Eval") THEN 'PT Followup'
                WHEN (pSchedules.Visit_Type = "OT FU Eval") THEN 'OT Followup'
                WHEN (pSchedules.Visit_Type = "ST FU Eval") THEN 'ST Followup'
                WHEN (pSchedules.Visit_Type = "MSW FU Eval") THEN 'MSW Followup'
                WHEN (pSchedules.Visit_Type = "SN FU Eval") THEN 'SN Followup'
                WHEN (pSchedules.Visit_Type = "Hospice Comprehensive") THEN 'Hospice Comprehensive'
                WHEN (pSchedules.Visit_Type = "SN Hospice") THEN 'SN Hospice'
                WHEN (pSchedules.Visit_Type = "Chaplain Comprehensive Evaluation") THEN 'Chaplain Comprehensive Evaluation'
                WHEN (pSchedules.Visit_Type = "Hospice Discharge") THEN 'Hospice Discharge'
                WHEN (pSchedules.Visit_Type = "4 - Recertification") THEN '4 - Recertification (follow-up) reassessment'
                WHEN (pSchedules.Visit_Type = "4 - Recertification PT") THEN '4 - Recertification (follow-up) reassessment - PT'
                WHEN (pSchedules.Visit_Type = "4 - Recertification OT") THEN '4 - Recertification (follow-up) reassessment - OT'
                WHEN (pSchedules.Visit_Type = "5 - Other follow-up") THEN '5 - Other follow-up'
                WHEN (pSchedules.Visit_Type = "6 - Transfer no discharge") THEN '6 - Transferred to an inpatient facility - patient not discharged from agency'
                WHEN (pSchedules.Visit_Type = "7 - Transfer discharged") THEN '7 - Transferred to an inpatient facility - patient discharged from agency'
                WHEN (pSchedules.Visit_Type = "8 - Death") THEN '8 - Death at home'
                WHEN (pSchedules.Visit_Type = "9 - Discharge from agency") THEN '9 - Discharge from agency'
                ELSE 0
            END)
            AND pAss.Status = 0 AND pSchedules.Visit_Date = pAss.F176
            ORDER BY F25 ASC LIMIT 0,1) AS assessments_completed 
        FROM #Request.prefix_db_agency#.pSchedules
        LEFT JOIN #Request.prefix_db_agency#.pAssessments 
        ON (pSchedules.Assmt_ID = pAssessments.Assmt_ID OR pSchedules.Assmt_ID = 0) AND pAssessments.Patient_ID = pSchedules.Patient_ID AND pAssessments.Status = 0
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAdmit ON (pAdmit.Admit_ID = pAssessments.Admit_ID) AND pSchedules.Patient_ID = pAdmit.Patient_ID AND pAdmit.Status = 0
        JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pSchedules.Patient_ID
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.pSched_Procedure ON pSched_Procedure.Schedule_ID = pSchedules.Schedule_ID AND pSched_Procedure.Status = 0
        LEFT OUTER JOIN #Request.prefix_db_agency#.pCareplan ON pCareplan.Careplan_ID = pSched_Procedure.Careplan_ID AND pCareplan.Status = 0
        WHERE pPatients.Status = 0
          AND pSchedules.Status = 0
          AND pSchedules.Missed = 0 
          AND pSchedules.Visit_Date < <cfqueryparam value="#DateFormat(now(),'yyyy-mm-dd')#" cfsqltype="CF_SQL_DATE">
          AND pSchedules.pgnotesdraft != 2 
          AND (LEFT(pSchedules.Visit_Type,1) NOT IN (6) OR pSchedules.Visit_Type IS NULL)
        GROUP BY pSchedules.Schedule_ID
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <cfset visittypes = "3,4,5,6,7,8,9,FU Eval">

    <cfloop query="getLateProgressNotes">
        <cfset visitDateValue = currentDate>
        <cfif IsDate(getLateProgressNotes.Visit_Date)>
            <cfset visitDateValue = CreateODBCDate(getLateProgressNotes.Visit_Date)>
        </cfif>

        <cfset assmtIdValue = getLateProgressNotes.Assmt_ID>
        <cfset assmtIdNull = NOT IsNumeric(assmtIdValue)>

        <cfset empIdValue = getLateProgressNotes.Emp_ID>
        <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
            <cfset empIdValue = 0>
        </cfif>

        <cfset ptLastValue = Trim(getLateProgressNotes.PatientLast)>
        <cfset ptFirstValue = Trim(getLateProgressNotes.PatientFirst)>
        <cfset empLastValue = Trim(getLateProgressNotes.Emp_Last)>
        <cfset empFirstValue = Trim(getLateProgressNotes.Emp_First)>

        <cfset ptLastNull = NOT Len(ptLastValue)>
        <cfset ptFirstNull = NOT Len(ptFirstValue)>
        <cfset empFirstNull = NOT Len(empFirstValue)>
        <cfset empLastNull = NOT Len(empLastValue)>

        <cfset encPatientId = encrypt("#getLateProgressNotes.Patient_ID#", encryptKey, "AES", "Hex")>
        <cfset encAssmtId = "">
        <cfif IsNumeric(assmtIdValue)>
            <cfset encAssmtId = encrypt("#assmtIdValue#", encryptKey, "AES", "Hex")>
        </cfif>
        <cfset encScheduleId = encrypt("#getLateProgressNotes.Schedule_ID#", encryptKey, "AES", "Hex")>

        <cfset visitLink = Application.secure & "patientadmin_new/index.cfm?page=patient&ID=" & encPatientId & "&cat=patientedit_visit&restrict=1&formonly=1">
        <cfif Len(encAssmtId)>
            <cfset visitLink = visitLink & "&AID=" & encAssmtId>
        </cfif>
        <cfset visitLink = visitLink & "&SID=" & encScheduleId & "&frm=bill">

        <cfset patientDisplay = "">
        <cfif Len(ptLastValue)>
            <cfset patientDisplay = ptLastValue>
        </cfif>
        <cfif Len(ptFirstValue)>
            <cfif Len(patientDisplay)>
                <cfset patientDisplay = patientDisplay & ", ">
            </cfif>
            <cfset patientDisplay = patientDisplay & ptFirstValue>
        </cfif>

        <!--- Match exact filtering logic from pending_visitsnew.cfm lines 162-175 to get ALL records --->
        <cfset visitType = Trim(getLateProgressNotes.Visit_Type)>
        <cfset visitLength = Len(visitType)>
        <cfset rightVisitType = "">
        <cfset leftVisitType = "">
        <cfif visitLength GT 0>
            <cfset rightVisitType = Trim(Right(visitType, 7))>
            <cfset leftVisitType = Trim(Left(visitType,1))>
        </cfif>

        <!--- Use ListFindNoCase (equivalent to listContains in pending_visitsnew.cfm) --->
        <cfset rightInList = ListFindNoCase(visittypes, rightVisitType)>
        <cfset leftInList = ListFindNoCase(visittypes, leftVisitType)>
        <cfset assessmentsCompleted = getLateProgressNotes.assessments_completed>

        <!--- Match exact logic from pending_visitsnew.cfm lines 162-175 --->
        <cfset shouldInsert = False>
        <cfif ((rightInList GT 0 OR leftInList GT 0) AND assessmentsCompleted NEQ 1)
             OR ((rightInList GT 0 OR leftInList GT 0) AND getLateProgressNotes.pgnotesdraft LT 2)
             OR ((rightInList EQ 0 AND leftInList EQ 0) AND visitLength GT 0 AND assessmentsCompleted NEQ 1)
             OR (visitLength EQ 0 AND getLateProgressNotes.pgnotesdraft LT 2)>
            <cfset shouldInsert = True>
        </cfif>

        <cfif shouldInsert>
            <cfset visitDateDisplay = "">
            <cfif IsDate(getLateProgressNotes.Visit_Date)>
                <cfset visitDateDisplay = " (Visit Date: " & DateFormat(getLateProgressNotes.Visit_Date, "mm/dd/yyyy") & ")">
            </cfif>
            
            <!--- Determine the issue type (matches pending_visitsnew.cfm line 189-194) --->
            <cfset issueType = "">
            <cfif ((rightInList GT 0 OR leftInList GT 0) AND getLateProgressNotes.pgnotesdraft LT 2)>
                <cfset issueType = "Late progress note">
            <cfelseif assessmentsCompleted NEQ 1 AND visitLength GT 0>
                <cfset issueType = "OASIS/Evaluation not completed">
            <cfelseif visitLength EQ 0 AND getLateProgressNotes.pgnotesdraft LT 2>
                <cfset issueType = "Late progress note">
            <cfelse>
                <cfset issueType = "Pending visit">
            </cfif>
            
            <cfset descriptions = issueType & (Len(patientDisplay) ? " for " & patientDisplay : "") & visitDateDisplay & ". <a href='" & visitLink & "'>Open patient visit</a>">

            <cfquery name="insertLateProgressNotes" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#assmtIdValue#" cfsqltype="CF_SQL_INTEGER" null="#assmtIdNull#">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getLateProgressNotes.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#ptLastValue#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#ptFirstValue#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#empFirstValue#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#empLastValue#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="late progress note" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#descriptions#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Incomplete careplan - matches missings_careplans.cfm --->
    <cfquery name="getIncompleteCareplans" datasource="#Application.DataSrc#">
        SELECT
            parent_oasis.F26 AS parent_assessment,
            parent_oasis.F176 AS parent_Assessment_Completed_M0090,
            pAssessments.Assmt_ID,
            pAssessments.Patient_ID,
            pAssessments.F26 AS Assessment_Reason_M0100,
            pAssessments.F27,
            pAssessments.F25 AS admission_status,
            pAssessments.F177 AS Certification_Start,
            pAssessments.F178 AS Certification_End,
            pAssessments.F176 AS Assessment_Completed_M0090,
            pPatients.Pt_First,
            pPatients.Pt_Last,
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            (SELECT COUNT(*) FROM #Request.prefix_db_agency#.pCareplan
                WHERE pCareplan.Assmt_ID = pAssessments.Assmt_ID
                AND pCareplan.Status = 0 AND pCareplan.Skill = pAssessments.F27) AS careplancount,
            (SELECT COUNT(*) FROM #Request.prefix_db_agency#.pCareplan
                WHERE pCareplan.Assmt_ID = assessment_assign.Parent_Assmt_ID
                AND pCareplan.Status = 0 AND pCareplan.Skill = pAssessments.F27) AS notcreatedcareplan,
            (SELECT COUNT(*) FROM #Request.prefix_db_agency#.pCareplan
                WHERE pCareplan.Assmt_ID = assessment_assign.Parent_Assmt_ID
                AND pCareplan.Status = 0 AND pCareplan.Skill = pAssessments.F27
                AND pCareplan.Type IN ('discharge_plan','patient_goal')
                AND pCareplan.Description IN ('add patient-stated goal','add discharge plan')) AS ptgoalsnotadded,
            (SELECT COUNT(*) FROM #Request.prefix_db_agency#.pWoundsVitals
                WHERE Assmt_ID = pAssessments.Assmt_ID
                AND Status = 0
                AND VitalOrWound = 'vital'
                AND (Description != 'weight' OR Description != 'Weight')
                AND (Param_Lo IS NULL OR Param_Hi IS NULL OR Param_Lo = '' OR Param_Hi = '')) AS required_vital,
            (SELECT COUNT(*) FROM #Request.prefix_db_agency#.pCareplan
                WHERE pCareplan.Assmt_ID = assessment_assign.Parent_Assmt_ID
                AND pCareplan.Status = 0 AND pCareplan.Skill = pAssessments.F27
                AND pCareplan.Type IN ('standing_order')) AS standingorders_count,
            (SELECT COUNT(*) FROM #Request.prefix_db_agency#.pPtmeds
                WHERE pPtmeds.In_Home = 2 AND pPtmeds.Status = 0 AND pPatients.Patient_ID = pPtmeds.Patient_ID) AS incomplete_meds,
            (SELECT COUNT(Communication.Comm_ID) FROM #Request.prefix_db_agency#.Communication
                JOIN #Request.prefix_db_agency#.CommunicationSubjects ON CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
                WHERE Communication.Status = 0
                AND Communication.Patient_ID = pPatients.Patient_ID AND pAdmit.M0030_START_CARE_DT < Communication.Comm_Date
                AND CommunicationSubjects.Subject LIKE "Discharge Summary - PT%") AS PTdischargecount,
            (SELECT COUNT(Communication.Comm_ID) FROM #Request.prefix_db_agency#.Communication
                JOIN #Request.prefix_db_agency#.CommunicationSubjects ON CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
                WHERE Communication.Status = 0
                AND Communication.Patient_ID = pPatients.Patient_ID AND pAdmit.M0030_START_CARE_DT < Communication.Comm_Date
                AND CommunicationSubjects.Subject LIKE "Discharge Summary - OT%") AS OTdischargecount,
            (SELECT COUNT(Communication.Comm_ID) FROM #Request.prefix_db_agency#.Communication
                JOIN #Request.prefix_db_agency#.CommunicationSubjects ON CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
                WHERE Communication.Status = 0
                AND Communication.Patient_ID = pPatients.Patient_ID AND pAdmit.M0030_START_CARE_DT < Communication.Comm_Date
                AND CommunicationSubjects.Subject LIKE "Discharge Summary - ST%") AS STdischargecount,
            (SELECT COUNT(Communication.Comm_ID) FROM #Request.prefix_db_agency#.Communication
                JOIN #Request.prefix_db_agency#.CommunicationSubjects ON CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
                WHERE Communication.Status = 0
                AND Communication.Patient_ID = pPatients.Patient_ID AND pAdmit.M0030_START_CARE_DT < Communication.Comm_Date
                AND CommunicationSubjects.Subject LIKE "Discharge Summary - SN%") AS SNdischargecount
        FROM #Request.prefix_db_agency#.pAssessments pAssessments
        JOIN #Request.prefix_db_agency#.pPatients pPatients ON pAssessments.Patient_ID = pPatients.Patient_ID
        JOIN #Request.prefix_db_agency#.pAdmit pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID AND pAdmit.Status = 0
        LEFT OUTER JOIN #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID = pAssessments.Assmt_ID
            AND assessment_assign.F26 = pAssessments.F26
        JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = assessment_assign.Emp_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAssessments parent_oasis ON parent_oasis.Assmt_ID = assessment_assign.Parent_Assmt_ID
            AND parent_oasis.Status = 0
        WHERE pPatients.Status = 0
          AND pAssessments.Status = 0
          AND pAssessments.F25 = 1
          AND (pAssessments.F26 LIKE '1%' OR pAssessments.F26 LIKE '4%'
               OR pAssessments.F26 LIKE 'PT Adult%' OR pAssessments.F26 LIKE 'OT Adult%'
               OR pAssessments.F26 LIKE 'ST Adult%' OR pAssessments.F26 LIKE 'SN Adult%')
          AND pAssessments.Admit_ID NOT IN (
                SELECT pas.Admit_ID FROM #Request.prefix_db_agency#.pAssessments pas
                WHERE (pas.F26 LIKE '9%' OR pas.F26 LIKE '7%' OR pas.F26 LIKE '8%')
                  AND pas.Status = 0 AND pas.F25 = 1
          )
        GROUP BY pAssessments.Assmt_ID
    </cfquery>

    <cfloop query="getIncompleteCareplans">
        <!--- Match filtering logic from missings_careplans.cfm lines 174-186 --->
        <cfset shouldInsert = False>
        <cfif ((LEFT(getIncompleteCareplans.Assessment_Reason_M0100,1) EQ '1' OR LEFT(getIncompleteCareplans.Assessment_Reason_M0100,1) EQ '4')
             AND (getIncompleteCareplans.ptgoalsnotadded GT 0 OR getIncompleteCareplans.notcreatedcareplan EQ 0
             OR getIncompleteCareplans.required_vital GT 0 OR getIncompleteCareplans.standingorders_count EQ 0))
             OR getIncompleteCareplans.incomplete_meds GT 0
             OR (LEFT(getIncompleteCareplans.Assessment_Reason_M0100,2) EQ 'PT' AND getIncompleteCareplans.PTdischargecount EQ 0
             AND (getIncompleteCareplans.ptgoalsnotadded GT 0 OR getIncompleteCareplans.notcreatedcareplan EQ 0))
             OR (LEFT(getIncompleteCareplans.Assessment_Reason_M0100,2) EQ 'OT' AND getIncompleteCareplans.OTdischargecount EQ 0
             AND (getIncompleteCareplans.ptgoalsnotadded GT 0 OR getIncompleteCareplans.notcreatedcareplan EQ 0))
             OR (LEFT(getIncompleteCareplans.Assessment_Reason_M0100,2) EQ 'ST' AND getIncompleteCareplans.STdischargecount EQ 0
             AND (getIncompleteCareplans.ptgoalsnotadded GT 0 OR getIncompleteCareplans.notcreatedcareplan EQ 0))
             OR (LEFT(getIncompleteCareplans.Assessment_Reason_M0100,2) EQ 'SN' AND getIncompleteCareplans.SNdischargecount EQ 0
             AND (getIncompleteCareplans.ptgoalsnotadded GT 0 OR getIncompleteCareplans.notcreatedcareplan EQ 0))>
            <cfset shouldInsert = True>
        </cfif>

        <cfif shouldInsert>
            <cfset empIdValue = getIncompleteCareplans.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>

            <cfset assmtIdValue = getIncompleteCareplans.Assmt_ID>
            <cfset assmtIdNull = NOT IsNumeric(assmtIdValue)>

            <cfset ptLastValue = Trim(getIncompleteCareplans.Pt_Last)>
            <cfset ptFirstValue = Trim(getIncompleteCareplans.Pt_First)>
            <cfset empLastValue = Trim(getIncompleteCareplans.Emp_Last)>
            <cfset empFirstValue = Trim(getIncompleteCareplans.Emp_First)>

            <cfset ptLastNull = NOT Len(ptLastValue)>
            <cfset ptFirstNull = NOT Len(ptFirstValue)>
            <cfset empFirstNull = NOT Len(empFirstValue)>
            <cfset empLastNull = NOT Len(empLastValue)>

            <cfset encPatientId = encrypt("#getIncompleteCareplans.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset encAssmtId = "">
            <cfif IsNumeric(assmtIdValue)>
                <cfset encAssmtId = encrypt("#assmtIdValue#", encryptKey, "AES", "Hex")>
            </cfif>

            <cfset assessmentLink = Application.secure & "patientadmin_new/index.cfm?page=patient&cat=Patient&id=" & encPatientId & "&restrict=1&formonly=1">
            <cfif Len(encAssmtId)>
                <cfset assessmentLink = assessmentLink & "&assid=" & encAssmtId>
            </cfif>
            <cfset assessmentLink = assessmentLink & "&from=missingnotes">

            <cfset patientDisplay = "">
            <cfif Len(ptLastValue)>
                <cfset patientDisplay = ptLastValue>
            </cfif>
            <cfif Len(ptFirstValue)>
                <cfif Len(patientDisplay)>
                    <cfset patientDisplay = patientDisplay & ", ">
                </cfif>
                <cfset patientDisplay = patientDisplay & ptFirstValue>
            </cfif>

            <!--- Determine reason (matches missings_careplans.cfm lines 222-234) --->
            <cfset reasonText = "">
            <cfif getIncompleteCareplans.notcreatedcareplan EQ 0>
                <cfset reasonText = "Careplan not created">
            <cfelseif getIncompleteCareplans.ptgoalsnotadded GT 0>
                <cfset reasonText = "Patient goal OR discharge plan not added">
            <cfelseif getIncompleteCareplans.incomplete_meds GT 0>
                <cfset reasonText = "#getIncompleteCareplans.incomplete_meds# Meds status still pending in careplan">
            <cfelseif getIncompleteCareplans.required_vital GT 0>
                <cfset reasonText = "Incomplete Vital Sign">
            <cfelseif getIncompleteCareplans.standingorders_count EQ 0>
                <cfset reasonText = "Standing orders required">
            <cfelse>
                <cfset reasonText = "Missing careplan">
            </cfif>

            <cfset description = "Incomplete careplan: " & HTMLEditFormat(reasonText)>
            <cfif Len(patientDisplay)>
                <cfset description = description & " for " & HTMLEditFormat(patientDisplay)>
            </cfif>
            <cfset description = description & ". <a href='" & assessmentLink & "'>Open assessment</a>">

            <cfquery name="insertIncompleteCareplans" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#assmtIdValue#" cfsqltype="CF_SQL_INTEGER" null="#assmtIdNull#">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getIncompleteCareplans.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#ptLastValue#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#ptFirstValue#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#empFirstValue#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#empLastValue#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="incomplete careplan" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- VBP Inconsistencies (matches VBP_consist.cfm) --->
    <cfquery name="getVBPInconsistencies" datasource="#Application.DataSrc#">
        SELECT
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pAssessments.Assmt_ID,
            pAssessments.F26,
            pAssessments.F176,
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            pVBP_Inconsist.Message,
            (SELECT count(Order_ID) FROM #Request.prefix_db_agency#.pCMS4857
                WHERE pCMS4857.Assmt_ID = pAssessments.Assmt_ID AND pCMS4857.Form_Type = 'Form 485'
                AND pCMS4857.Status = 0) AS count_485
        FROM #Request.prefix_db_agency#.pVBP_Inconsist
        JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pVBP_Inconsist.Assmt_ID
        JOIN #Request.prefix_db_agency#.pPatients ON pAssessments.Patient_ID = pPatients.Patient_ID
        JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID = pAssessments.Assmt_ID
            AND assessment_assign.F26 = pAssessments.F26
        JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = assessment_assign.Emp_ID
        WHERE pPatients.Status < 2
          AND pAdmit.Status = 0
          AND pAssessments.Status = 0
          AND pAssessments.F178 >= <cfqueryparam value="#now()#" cfsqltype="CF_SQL_TIMESTAMP">
        GROUP BY pVBP_Inconsist.Assmt_ID
        ORDER BY pVBP_Inconsist.Assmt_ID, pPatients.Pt_Last, pPatients.Patient_ID
    </cfquery>

    <cfloop query="getVBPInconsistencies">
        <!--- Only include if count_485 = 0 (matches VBP_consist.cfm line 89) --->
        <cfif getVBPInconsistencies.count_485 EQ 0>
            <cfset empIdValue = getVBPInconsistencies.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>

            <cfset assmtIdValue = getVBPInconsistencies.Assmt_ID>
            <cfset assmtIdNull = NOT IsNumeric(assmtIdValue)>

            <cfset ptLastValue = Trim(getVBPInconsistencies.Pt_Last)>
            <cfset ptFirstValue = Trim(getVBPInconsistencies.Pt_First)>
            <cfset empLastValue = Trim(getVBPInconsistencies.Emp_Last)>
            <cfset empFirstValue = Trim(getVBPInconsistencies.Emp_First)>

            <cfset ptLastNull = NOT Len(ptLastValue)>
            <cfset ptFirstNull = NOT Len(ptFirstValue)>
            <cfset empFirstNull = NOT Len(empFirstValue)>
            <cfset empLastNull = NOT Len(empLastValue)>

            <cfset encPatientId = encrypt("#getVBPInconsistencies.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset encAssmtId = encrypt("#assmtIdValue#", encryptKey, "AES", "Hex")>

            <cfset vbpLink = Application.secure & "patientadmin_new/index.cfm?page=patient&cat=VBPanalysisnew&id=" & encPatientId & "&restrict=1&formonly=1&assid=" & encAssmtId>

            <cfset patientDisplay = "">
            <cfif Len(ptLastValue)>
                <cfset patientDisplay = ptLastValue>
            </cfif>
            <cfif Len(ptFirstValue)>
                <cfif Len(patientDisplay)>
                    <cfset patientDisplay = patientDisplay & ", ">
                </cfif>
                <cfset patientDisplay = patientDisplay & ptFirstValue>
            </cfif>

            <cfset messageValue = Trim(getVBPInconsistencies.Message)>
            <cfif NOT Len(messageValue)>
                <cfset messageValue = "VBP Inconsistency">
            </cfif>

            <cfset description = "VBP Inconsistency: " & HTMLEditFormat(messageValue)>
            <cfif Len(patientDisplay)>
                <cfset description = description & " for " & HTMLEditFormat(patientDisplay)>
            </cfif>
            <cfif IsDate(getVBPInconsistencies.F176)>
                <cfset description = description & " (Assessment: " & HTMLEditFormat(getVBPInconsistencies.F26) & ", Completed: " & DateFormat(getVBPInconsistencies.F176, "mm/dd/yyyy") & ")">
            </cfif>
            <cfset description = description & ". <a href='" & vbpLink & "'>Open VBP analysis</a>">

            <cfquery name="insertVBPInconsistencies" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#assmtIdValue#" cfsqltype="CF_SQL_INTEGER" null="#assmtIdNull#">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getVBPInconsistencies.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#ptLastValue#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#ptFirstValue#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#empFirstValue#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#empLastValue#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="VBP Inconsistencies" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Missing OASIS - matches missing_oasis.cfm --->
    <!--- Query 1: Missing SOC/Recert assessments - matches GetList query from missing_oasis.cfm lines 17-60 --->
    <cfquery name="getMissingOASISList" datasource="#Application.DataSrc#">
        SELECT pPatients.Patient_ID, pPatients.Pt_Last AS PatientLast, pPatients.Pt_First AS PatientFirst,
        pAdmit.*,
        (SELECT count(*) FROM #Request.prefix_db_agency#.pAssessments
            WHERE pAdmit.Admit_ID = pAssessments.Admit_ID
            AND pAssessments.Status = 0 AND Left(pAssessments.F26,1) = '1') AS SOC_count,
        (SELECT count(*) FROM #Request.prefix_db_agency#.pAssessments
            WHERE pAdmit.Admit_ID = pAssessments.Admit_ID
            AND pAssessments.Status = 0 AND Left(pAssessments.F26,1) = '4') AS Recert_count,
        (SELECT count(Communication.Comm_ID) FROM #Request.prefix_db_agency#.Communication
            JOIN #Request.prefix_db_agency#.CommunicationSubjects ON CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
            WHERE Communication.Status = 0
            AND Communication.Patient_ID = pPatients.Patient_ID AND pAdmit.M0030_START_CARE_DT < Communication.Comm_Date
            AND (CommunicationSubjects.Subject like "Discharge Summary%"
            OR CommunicationSubjects.Subject like '%Agency Transfer%')) AS communicationsubject_count,
        (SELECT F178 FROM #Request.prefix_db_agency#.pAssessments
            WHERE pAdmit.Admit_ID = pAssessments.Admit_ID
            AND pAssessments.Status = 0 AND Left(pAssessments.F26,1) IN ('4','1')
            ORDER BY F178 DESC LIMIT 0,1) AS Certification_End,
        pEmployee.Emp_ID,
        pEmployee.Emp_First,
        pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pAdmit
        JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAdmit.Patient_ID
        JOIN #Request.prefix_db_agency#.pAssessments ON pAdmit.Admit_ID = pAssessments.Admit_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID = pAssessments.Assmt_ID
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
        WHERE pPatients.Status = 0
          And pAdmit.Status = 0
          AND pAdmit.Admit_ID NOT IN (
                SELECT pAssessments.Admit_ID FROM #Request.prefix_db_agency#.pAssessments
                WHERE (pAssessments.F26 like '9%' OR pAssessments.F26 like '7%' OR pAssessments.F26 like '8%')
                  AND pAssessments.Status = 0
          )
        GROUP BY pAdmit.Admit_ID
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <cfloop query="getMissingOASISList">
        <cfset diffdays = "">
        <cfif IsDate(getMissingOASISList.Certification_End)>
            <cfset diffdays = DateDiff("d", getMissingOASISList.Certification_End, now())>
        </cfif>

        <!--- Match logic from missing_oasis.cfm line 259 --->
        <cfif diffdays GTE 0 AND getMissingOASISList.communicationsubject_count EQ 0>
            <cfif getMissingOASISList.SOC_count EQ 0 OR getMissingOASISList.Recert_count EQ 0>
                <cfset empIdValue = getMissingOASISList.Emp_ID>
                <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                    <cfset empIdValue = 0>
                </cfif>

                <cfset ptLastValue = Trim(getMissingOASISList.PatientLast)>
                <cfset ptFirstValue = Trim(getMissingOASISList.PatientFirst)>
                <cfset empLastValue = Trim(getMissingOASISList.Emp_Last)>
                <cfset empFirstValue = Trim(getMissingOASISList.Emp_First)>

                <cfset ptLastNull = NOT Len(ptLastValue)>
                <cfset ptFirstNull = NOT Len(ptFirstValue)>
                <cfset empFirstNull = NOT Len(empFirstValue)>
                <cfset empLastNull = NOT Len(empLastValue)>

                <cfset encPatientId = encrypt("#getMissingOASISList.Patient_ID#", encryptKey, "AES", "Hex")>
                <cfset encAdmitId = encrypt("#getMissingOASISList.Admit_ID#", encryptKey, "AES", "Hex")>

                <cfset assessmentLink = Application.secure & "patientadmin_new/index.cfm?a=1&new=yes&page=patient&ID=" & encPatientId & "&admitid=" & encAdmitId & "&cat=AssessmentFormWizard">

                <cfset patientDisplay = "">
                <cfif Len(ptLastValue)>
                    <cfset patientDisplay = ptLastValue>
                </cfif>
                <cfif Len(ptFirstValue)>
                    <cfif Len(patientDisplay)>
                        <cfset patientDisplay = patientDisplay & ", ">
                    </cfif>
                    <cfset patientDisplay = patientDisplay & ptFirstValue>
                </cfif>

                <cfset missingType = "">
                <cfif getMissingOASISList.SOC_count EQ 0>
                    <cfset missingType = "SOC">
                </cfif>
                <cfif getMissingOASISList.Recert_count EQ 0>
                    <cfif Len(missingType)>
                        <cfset missingType = missingType & " and Recertification">
                    <cfelse>
                        <cfset missingType = "Recertification">
                    </cfif>
                </cfif>

                <cfset description = "Missing OASIS: " & missingType>
                <cfif Len(patientDisplay)>
                    <cfset description = description & " for " & HTMLEditFormat(patientDisplay)>
                </cfif>
                <cfif IsDate(getMissingOASISList.Certification_End)>
                    <cfset description = description & " (Cert End: " & DateFormat(getMissingOASISList.Certification_End, "mm/dd/yyyy") & ")">
                </cfif>
                <cfset description = description & ". <a href='" & assessmentLink & "'>Create assessment</a>">

                <!--- Check if record already exists for this patient/admit combination to prevent duplicates --->
                <cfquery name="checkExistingOASIS" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS recordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Patient_ID = <cfqueryparam value="#getMissingOASISList.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                      AND Header = <cfqueryparam value="Missing OASIS" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND Description LIKE <cfqueryparam value="%#HTMLEditFormat(patientDisplay)#%" cfsqltype="CF_SQL_VARCHAR">
                      AND Description LIKE <cfqueryparam value="%#HTMLEditFormat(missingType)#%" cfsqltype="CF_SQL_VARCHAR">
                      AND status = 0
                </cfquery>

                <cfif checkExistingOASIS.recordCount EQ 0>
                    <cfquery name="insertMissingOASIS" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getMissingOASISList.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getMissingOASISList.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getMissingOASISList.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#empFirstValue#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#empLastValue#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="Missing OASIS" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Query 2: Missing followup assessments (PT, OT, ST, MSW) and recertifications - EXACT copy from missing_oasis.cfm lines 63-197 --->
    <cfquery name="getdischarge" datasource="#Application.DataSrc#">
		SELECT  pPatients.Patient_ID as pat_id, pPatients.Pt_Last AS PatientLast, pPatients.Pt_First AS PatientFirst, 

		 	CASE WHEN LEFT(pAssessments.F26,1) = '4' AND   DATEDIFF(pAssessments.F178, now()) <= 1 THEN 1 
		 	  ELSE 0 
		 	END AS Recert_need , 
		 	 (SELECT  count(*) FROM #Request.prefix_db_agency#.pAssessments ass
              WHERE LEFT(ass.F26,1) = '4'
               AND DATEDIFF(ass.F178, now()) >= 1
               AND ass.Patient_ID = pAssessments.Patient_ID )
             	 AS Recert_exisiting,
     		CASE WHEN (pAssessments.F26 = 'PT Adult Evaluation' OR pAssessments.F26 = 'PT Followup')
     		AND   DATE_ADD(pAssessments.F176, INTERVAL 30 DAY) < now() THEN 1 
		 	  ELSE 0 
		 	END AS PT_need ,

		 	 (SELECT  count(*) FROM #Request.prefix_db_agency#.pAssessments ass
              WHERE ass.F26 = 'PT Followup'
              AND ass.Patient_ID = pAssessments.Patient_ID
             AND ass.Admit_ID = pAssessments.Admit_ID)
             AS PT_Followup,

		 	(SELECT  count(*)
			FROM   #Request.prefix_db_agency#.Communication, #Request.prefix_db_agency#.CommunicationSubjects
			WHERE  Communication.Patient_ID = pPatients.Patient_ID
			AND    CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
			AND   CommunicationSubjects.Subject IN ('Discharge Summary - PT')
			AND   Communication.Comm_record_deleted <> 1
			AND  Communication.Status = 0 ) AS PT_summary,

			CASE WHEN (pAssessments.F26 = 'OT Adult Evaluation' OR pAssessments.F26 = 'OT Followup') 
			AND   DATE_ADD(pAssessments.F176, INTERVAL 30 DAY) < now() THEN 1 
		 	  ELSE 0 
		 	END AS OT_need , 
		 	 (SELECT  count(*) FROM #Request.prefix_db_agency#.pAssessments ass
              WHERE ass.F26 = 'OT Followup'
              AND ass.Patient_ID = pAssessments.Patient_ID
             AND ass.Admit_ID = pAssessments.Admit_ID)
             AS OT_Followup,
		 	(SELECT  count(*)
			FROM   #Request.prefix_db_agency#.Communication, #Request.prefix_db_agency#.CommunicationSubjects
			WHERE  Communication.Patient_ID = pPatients.Patient_ID
			AND    CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
			AND   CommunicationSubjects.Subject IN ('Discharge Summary - OT')
			AND   Communication.Comm_record_deleted <> 1
			AND  Communication.Status = 0 ) AS OT_summary,

			CASE WHEN (pAssessments.F26 = 'ST Adult Evaluation' OR pAssessments.F26 = 'ST Followup') 
			AND   DATE_ADD(pAssessments.F176, INTERVAL 30 DAY) < now() THEN 1 
		 	  ELSE 0 
		 	END AS ST_need , 
		 	 (SELECT  count(*) FROM #Request.prefix_db_agency#.pAssessments ass
              WHERE ass.F26 = 'ST Followup'
              AND ass.Patient_ID = pAssessments.Patient_ID
             AND ass.Admit_ID = pAssessments.Admit_ID)
             AS ST_Followup,
		 	(SELECT  count(*)
			FROM   #Request.prefix_db_agency#.Communication, #Request.prefix_db_agency#.CommunicationSubjects
			WHERE  Communication.Patient_ID = pPatients.Patient_ID
			AND    CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
			AND   CommunicationSubjects.Subject IN ('Discharge Summary - ST')
			AND   Communication.Comm_record_deleted <> 1
			AND  Communication.Status = 0 ) AS ST_summary,

			CASE WHEN (pAssessments.F26 = 'MSW Evaluation' OR pAssessments.F26 = 'MSW Followup')
			 AND    DATE_ADD(pAssessments.F176, INTERVAL 30 DAY) < now()THEN 1 
		 	  ELSE 0 
		 	END AS MSW_need , 
		 	 (SELECT  count(*) FROM #Request.prefix_db_agency#.pAssessments ass
              WHERE ass.F26 = 'MSW Followup'
              AND ass.Patient_ID = pAssessments.Patient_ID
             AND ass.Admit_ID = pAssessments.Admit_ID)
             AS MSW_Followup,
		 	(SELECT  count(*)
			FROM   #Request.prefix_db_agency#.Communication, #Request.prefix_db_agency#.CommunicationSubjects
			WHERE  Communication.Patient_ID = pPatients.Patient_ID
			AND    CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
			AND   CommunicationSubjects.Subject IN ('Discharge Summary - MSW')
			AND   Communication.Comm_record_deleted <> 1
			AND  Communication.Status = 0 ) AS MSW_summary,

			(SELECT  count(Communication.Comm_ID) FROM #Request.prefix_db_agency#.Communication
            JOIN #Request.prefix_db_agency#.CommunicationSubjects  
             ON CommunicationSubjects.CommSub_ID = Communication.CommSub_ID  
            WHERE Communication.Status = 0 
            AND Communication.Patient_ID = pPatients.Patient_ID AND pAdmit.M0030_START_CARE_DT < Communication.Comm_Date
            AND (CommunicationSubjects.Subject  like pAssessments.F27 OR CommunicationSubjects.Subject like "Discharge Summary%" 
            OR CommunicationSubjects.Subject like '%Agency Transfer%')) AS communicationsubject_count,


			(SELECT  count(*)  
			FROM   #Request.prefix_db_agency#.pAssessments pa 
			WHERE  pa.Patient_ID = pAssessments.Patient_ID and pAdmit.Admit_ID =  pa.Admit_ID
			AND  pa.Status = 0  AND LEFT(pa.F26,1) IN ('7','8','9')) AS dischargeoasis_count,

			(SELECT count(*) FROM #Request.prefix_db_agency#.pAuths pa 
			WHERE pa.Patient_ID = pAssessments.Patient_ID 
			AND pa.Skill = 'PT'  AND pa.Assmt_ID = 0
			AND  pa.Status = 0 ) AS pt_noauth,
			(SELECT count(*) FROM #Request.prefix_db_agency#.pAuths pa 
			WHERE pa.Patient_ID = pAssessments.Patient_ID 
			AND pa.Skill = 'OT'  AND pa.Assmt_ID = 0
			AND  pa.Status = 0 ) AS ot_noauth,
			(SELECT count(*) FROM #Request.prefix_db_agency#.pAuths pa 
			WHERE pa.Patient_ID = pAssessments.Patient_ID 
			AND pa.Skill = 'ST'  AND pa.Assmt_ID = 0
			AND  pa.Status = 0 ) AS st_noauth,
			(SELECT count(*) FROM #Request.prefix_db_agency#.pAuths pa 
			WHERE pa.Patient_ID = pAssessments.Patient_ID 
			AND pa.Skill = 'MSW'  AND pa.Assmt_ID = 0
			AND  pa.Status = 0 ) AS msw_noauth,

			 pAssessments.* 

		FROM #Request.prefix_db_agency#.pAssessments
		JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID
		JOIN #Request.prefix_db_agency#.pPatients ON  pPatients.Patient_ID = pAdmit.Patient_ID
		LEFT OUTER JOIN  #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID =  pAssessments.Assmt_ID
		LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
		LEFT OUTER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
		WHERE   pAdmit.Status  = 0
	    AND pPatients.status = 0
	  	AND pAssessments.status = 0
	  	<!--- AND (pAssessments.F25 = 0 OR pAssessments.F25 IS NULL) --->
	  	AND (employee_auth.r_Admit_Pend = 3 OR assessment_assign.Emp_ID IS NULL)
	  	AND  pAdmit.Admit_ID NOT IN (SELECT  pAssessments.Admit_ID FROM #Request.prefix_db_agency#.pAssessments  
	        WHERE  (pAssessments.F26 like '9%' OR pAssessments.F26 like '7%' OR pAssessments.F26 like '8%')
	         AND  pAssessments.Status =0)
	 	GROUP BY pAssessments.Assmt_ID
	  	ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC, pAssessments.F178 DESC, pAssessments.F176 DESC
	</cfquery>
	
	<!--- Filter getdischarge using needOASIS logic - EXACT copy from missing_oasis.cfm lines 198-208 --->
	<cfquery name="needOASIS" dbtype="query">
		SELECT * FROM getdischarge 
		WHERE dischargeoasis_count = 0
		AND  (Recert_need = 1
		OR  (PT_need = 1 AND PT_summary= 0 AND pt_noauth = 0 AND PT_Followup = 0) 
		 OR (OT_need = 1 AND OT_summary= 0  AND ot_noauth = 0 AND OT_Followup = 0) 
		 OR (ST_need = 1 AND ST_summary= 0  AND st_noauth = 0 AND ST_Followup = 0) 
		 OR (MSW_need = 1 AND MSW_summary= 0  AND msw_noauth = 0 AND MSW_Followup = 0))
		AND communicationsubject_count = 0
	</cfquery>

    <cfloop query="needOASIS">
        <!--- Additional check from missing_oasis.cfm line 277 --->
        <cfif ((LEFT(needOASIS.F26,1) EQ '4' AND needOASIS.Recert_exisiting EQ 0) OR LEFT(needOASIS.F26,1) NEQ '4')>
            <cfset assmtIdValue = needOASIS.Assmt_ID>
            <cfset assmtIdNull = NOT IsNumeric(assmtIdValue)>

                <!--- Get employee info from assessment_assign --->
                <cfquery name="getEmployeeInfo" datasource="#Application.DataSrc#">
                    SELECT assessment_assign.Emp_ID, pEmployee.Emp_First, pEmployee.Emp_Last
                    FROM #Request.prefix_db_agency#.assessment_assign
                    LEFT JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
                    WHERE assessment_assign.Assmt_ID = <cfqueryparam value="#needOASIS.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">
                    LIMIT 0,1
                </cfquery>

                <cfset empIdValue = 0>
                <cfset empFirstValue = "">
                <cfset empLastValue = "">
                <cfif getEmployeeInfo.recordCount GT 0>
                    <cfset empIdValue = getEmployeeInfo.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfset empFirstValue = Trim(getEmployeeInfo.Emp_First)>
                    <cfset empLastValue = Trim(getEmployeeInfo.Emp_Last)>
                </cfif>

                <cfset ptLastValue = Trim(needOASIS.PatientLast)>
                <cfset ptFirstValue = Trim(needOASIS.PatientFirst)>

                <cfset ptLastNull = NOT Len(ptLastValue)>
                <cfset ptFirstNull = NOT Len(ptFirstValue)>
                <cfset empFirstNull = NOT Len(empFirstValue)>
                <cfset empLastNull = NOT Len(empLastValue)>

                <cfset encPatientId = encrypt("#needOASIS.pat_id#", encryptKey, "AES", "Hex")>
                <cfset encAdmitId = encrypt("#needOASIS.Admit_ID#", encryptKey, "AES", "Hex")>

                <cfset assessmentLink = Application.secure & "patientadmin_new/index.cfm?a=1&new=yes&page=patient&ID=" & encPatientId & "&admitid=" & encAdmitId & "&cat=AssessmentFormWizard">

                <cfset patientDisplay = "">
                <cfif Len(ptLastValue)>
                    <cfset patientDisplay = ptLastValue>
                </cfif>
                <cfif Len(ptFirstValue)>
                    <cfif Len(patientDisplay)>
                        <cfset patientDisplay = patientDisplay & ", ">
                    </cfif>
                    <cfset patientDisplay = patientDisplay & ptFirstValue>
                </cfif>

                <!--- Determine assessment reason (matches missing_oasis.cfm lines 280-284) --->
                <cfset assessmentReason = needOASIS.F26>
                <cfif assessmentReason CONTAINS 'Adult Evaluation' OR assessmentReason CONTAINS 'Followup'>
                    <cfset assessmentReason = REReplace(assessmentReason, "Adult Evaluation", "Followup", "ALL")>
                <cfelse>
                    <cfset assessmentReason = REReplace(assessmentReason, "Evaluation", "Followup", "ALL")>
                </cfif>

                <!--- Determine what's missing --->
                <cfset missingType = "">
                <cfif needOASIS.Recert_need EQ 1>
                    <cfset missingType = "Recertification">
                <cfelseif needOASIS.PT_need EQ 1 AND needOASIS.PT_summary EQ 0>
                    <cfset missingType = "PT Followup">
                <cfelseif needOASIS.OT_need EQ 1 AND needOASIS.OT_summary EQ 0>
                    <cfset missingType = "OT Followup">
                <cfelseif needOASIS.ST_need EQ 1 AND needOASIS.ST_summary EQ 0>
                    <cfset missingType = "ST Followup">
                <cfelseif needOASIS.MSW_need EQ 1 AND needOASIS.MSW_summary EQ 0>
                    <cfset missingType = "MSW Followup">
                <cfelse>
                    <cfset missingType = assessmentReason>
                </cfif>

                <cfset description = "Missing OASIS: " & HTMLEditFormat(missingType)>
                <cfif Len(patientDisplay)>
                    <cfset description = description & " for " & HTMLEditFormat(patientDisplay)>
                </cfif>
                <cfif IsDate(needOASIS.F176)>
                    <cfset description = description & " (Completed: " & DateFormat(needOASIS.F176, "mm/dd/yyyy") & ")">
                </cfif>
                <cfif LEFT(needOASIS.F26,1) EQ '4' AND IsDate(needOASIS.F178)>
                    <cfset description = description & " (Cert End: " & DateFormat(needOASIS.F178, "mm/dd/yyyy") & ")">
                </cfif>
                <cfset description = description & ". <a href='" & assessmentLink & "'>Create assessment</a>">

                <!--- Check if record already exists for this patient/assmt/missing type combination to prevent duplicates --->
                <cfquery name="checkExistingOASISDischarge" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Patient_ID = <cfqueryparam value="#needOASIS.pat_id#" cfsqltype="CF_SQL_INTEGER">
                      AND Header = <cfqueryparam value="Missing OASIS" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      <cfif IsNumeric(assmtIdValue)>
                      AND Assmt_ID = <cfqueryparam value="#assmtIdValue#" cfsqltype="CF_SQL_INTEGER">
                      </cfif>
                      AND Description LIKE <cfqueryparam value="%#HTMLEditFormat(missingType)#%" cfsqltype="CF_SQL_VARCHAR">
                      AND status = 0
                </cfquery>

                <cfif checkExistingOASISDischarge.totalrecordCount EQ 0>
                    <cfquery name="insertMissingOASISDischarge" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#assmtIdValue#" cfsqltype="CF_SQL_INTEGER" null="#assmtIdNull#">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#needOASIS.pat_id#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#needOASIS.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#needOASIS.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#empFirstValue#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#empLastValue#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="Missing OASIS" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
        </cfif>
    </cfloop>

    <!--- Missing OASIS/Evaluation - For employees with r_Admit_Pend = 3 --->
    <!--- Get employees with r_Admit_Pend = 3 --->
    <cfquery name="getEmployeesR3" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            employee_auth.eaRole
        FROM #Request.prefix_db_lookup#.pEmployee pEmployee
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
          AND employee_auth.r_Admit_Pend = 3
    </cfquery>

    <!--- Get all missing OASIS/Evaluations with patient info - using EXACT queries from missing_oasis.cfm --->
    <!--- Query 1: GetList query - EXACT copy from missing_oasis.cfm lines 17-60 --->
    <cfquery name="GetList" datasource="#Application.DataSrc#">
	SELECT pPatients.Patient_ID, pPatients.Pt_Last AS PatientLast, pPatients.Pt_First AS PatientFirst, 
	pAdmit.*, 
	(SELECT count(*)  FROM  #Request.prefix_db_agency#.pAssessments
	WHERE  pAdmit.Admit_ID =  pAssessments.Admit_ID 
	AND pAssessments.Status = 0  AND Left(pAssessments.F26,1) = '1') AS  SOC_count,
	(SELECT count(*) FROM  #Request.prefix_db_agency#.pAssessments
	WHERE  pAdmit.Admit_ID =  pAssessments.Admit_ID 
	AND pAssessments.Status = 0  AND Left(pAssessments.F26,1) = '4') AS  Recert_count ,

	  (SELECT  count(Communication.Comm_ID) FROM #Request.prefix_db_agency#.Communication
            JOIN #Request.prefix_db_agency#.CommunicationSubjects  
             ON CommunicationSubjects.CommSub_ID = Communication.CommSub_ID  
            WHERE Communication.Status = 0 
            AND Communication.Patient_ID = pPatients.Patient_ID AND pAdmit.M0030_START_CARE_DT < Communication.Comm_Date
            AND (CommunicationSubjects.Subject like "Discharge Summary%" 
            	OR CommunicationSubjects.Subject like '%Agency Transfer%')) AS communicationsubject_count,



	(SELECT  F178 FROM  #Request.prefix_db_agency#.pAssessments
	WHERE  pAdmit.Admit_ID =  pAssessments.Admit_ID 
	AND pAssessments.Status = 0  AND Left(pAssessments.F26,1) IN ('4','1')  ORDER BY F178 DESC LIMIT 0,1) AS  Certification_End 

	FROM   #Request.prefix_db_agency#.pAdmit
	JOIN #Request.prefix_db_agency#.pPatients ON  pPatients.Patient_ID = pAdmit.Patient_ID
	JOIN #Request.prefix_db_agency#.pAssessments ON pAdmit.Admit_ID =  pAssessments.Admit_ID 
	LEFT OUTER JOIN  #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID =  pAssessments.Assmt_ID
	LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
	LEFT OUTER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
	WHERE pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
	  AND pPatients.Status  = 0
	And pAdmit.Status  = 0
	AND (employee_auth.r_Admit_Pend = 3 OR assessment_assign.Emp_ID IS NULL)
	AND  pAdmit.Admit_ID NOT IN (SELECT  pAssessments.Admit_ID FROM #Request.prefix_db_agency#.pAssessments  
	        WHERE  (pAssessments.F26 like '9%' OR pAssessments.F26 like '7%' OR pAssessments.F26 like '8%')
	         AND  pAssessments.Status =0)
	GROUP BY pAdmit.Admit_ID
	ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC 
	</cfquery>

    <!--- Get patients from GetList that match display conditions (missing_oasis.cfm lines 254-274) --->
    <!--- Filter in CFML since query-of-query doesn't support DATEDIFF with dates --->
    <cfset getMissingOASISPatientsFromGetList = QueryNew("Patient_ID,Pt_Last,Pt_First", "Integer,Varchar,Varchar")>
    <cfloop query="GetList">
        <cfset diffdays = "">
        <cfif GetList.Certification_End NEQ "">
            <cfset diffdays = DateDiff("d", GetList.Certification_End, now())>
        </cfif>
        <cfif diffdays GTE 0 AND GetList.communicationsubject_count EQ 0 AND (GetList.SOC_count EQ 0 OR GetList.Recert_count EQ 0)>
            <cfset QueryAddRow(getMissingOASISPatientsFromGetList)>
            <cfset QuerySetCell(getMissingOASISPatientsFromGetList, "Patient_ID", GetList.Patient_ID)>
            <cfset QuerySetCell(getMissingOASISPatientsFromGetList, "Pt_Last", GetList.PatientLast)>
            <cfset QuerySetCell(getMissingOASISPatientsFromGetList, "Pt_First", GetList.PatientFirst)>
        </cfif>
    </cfloop>
    <!--- Get patients from needOASIS query (already filtered) with additional check from line 277 --->
    <!--- Filter in CFML since query-of-query has limited function support --->
    <cfset getMissingOASISPatientsFromNeedOASIS = QueryNew("Patient_ID,Pt_Last,Pt_First", "Integer,Varchar,Varchar")>
    <cfloop query="needOASIS" group="pat_id">
        <!--- Additional check from missing_oasis.cfm line 277 --->
        <cfif ((LEFT(needOASIS.F26,1) EQ '4' AND needOASIS.Recert_exisiting EQ 0) OR LEFT(needOASIS.F26,1) NEQ '4')>
            <cfset QueryAddRow(getMissingOASISPatientsFromNeedOASIS)>
            <cfset QuerySetCell(getMissingOASISPatientsFromNeedOASIS, "Patient_ID", needOASIS.pat_id)>
            <cfset QuerySetCell(getMissingOASISPatientsFromNeedOASIS, "Pt_Last", needOASIS.PatientLast)>
            <cfset QuerySetCell(getMissingOASISPatientsFromNeedOASIS, "Pt_First", needOASIS.PatientFirst)>
        </cfif>
    </cfloop>
    <!--- Combine both result sets --->
    <cfset getMissingOASISPatients = QueryNew("Patient_ID,Pt_Last,Pt_First", "Integer,Varchar,Varchar")>
    <cfset existingPatientIDs = "">
    <cfloop query="getMissingOASISPatientsFromGetList">
        <cfset QueryAddRow(getMissingOASISPatients)>
        <cfset QuerySetCell(getMissingOASISPatients, "Patient_ID", getMissingOASISPatientsFromGetList.Patient_ID)>
        <cfset QuerySetCell(getMissingOASISPatients, "Pt_Last", getMissingOASISPatientsFromGetList.Pt_Last)>
        <cfset QuerySetCell(getMissingOASISPatients, "Pt_First", getMissingOASISPatientsFromGetList.Pt_First)>
        <cfset existingPatientIDs = ListAppend(existingPatientIDs, getMissingOASISPatientsFromGetList.Patient_ID)>
    </cfloop>
    <cfloop query="getMissingOASISPatientsFromNeedOASIS">
        <!--- Check if patient already exists to avoid duplicates --->
        <cfif NOT ListFind(existingPatientIDs, getMissingOASISPatientsFromNeedOASIS.Patient_ID)>
            <cfset QueryAddRow(getMissingOASISPatients)>
            <cfset QuerySetCell(getMissingOASISPatients, "Patient_ID", getMissingOASISPatientsFromNeedOASIS.Patient_ID)>
            <cfset QuerySetCell(getMissingOASISPatients, "Pt_Last", getMissingOASISPatientsFromNeedOASIS.Pt_Last)>
            <cfset QuerySetCell(getMissingOASISPatients, "Pt_First", getMissingOASISPatientsFromNeedOASIS.Pt_First)>
            <cfset existingPatientIDs = ListAppend(existingPatientIDs, getMissingOASISPatientsFromNeedOASIS.Patient_ID)>
        </cfif>
    </cfloop>

    <!--- Insert record for each employee with r_Admit_Pend = 3, for each patient with missing OASIS --->
    <cfloop query="getEmployeesR3">
        <cfloop query="getMissingOASISPatients">
            <cfset header = "missing OASIS/Evaluation">
            <cfset reportLink = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=missing_oasis">
            <cfset description = "<a href='" & reportLink & "'>View missing OASIS/Evaluation report</a>">

            <!--- Check if record already exists for this employee/patient combination to prevent duplicates --->
            <cfquery name="checkExistingMissingOASISR3" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE  Patient_ID = <cfqueryparam value="#getMissingOASISPatients.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND Header = <cfqueryparam value="missing OASIS/Evaluation" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND status = 0
            </cfquery>

            <cfif checkExistingMissingOASISR3.totalrecordCount EQ 0>
                <cfset empFirstNull = NOT Len(Trim(getEmployeesR3.Emp_First))>
                <cfset empLastNull = NOT Len(Trim(getEmployeesR3.Emp_Last))>
                <cfset ptFirstNull = NOT Len(Trim(getMissingOASISPatients.Pt_First))>
                <cfset ptLastNull = NOT Len(Trim(getMissingOASISPatients.Pt_Last))>
                <cfquery name="insertMissingOASISR3" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#getEmployeesR3.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissingOASISPatients.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissingOASISPatients.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                        <cfqueryparam value="#getMissingOASISPatients.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                        <cfqueryparam value="#getEmployeesR3.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                        <cfqueryparam value="#getEmployeesR3.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                        <cfqueryparam value="#header#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfloop>
    </cfloop>

    <!--- Missing authorization - matches missing_auths.cfm exactly --->
    <cfquery name="getMissingAuthPatients" datasource="#Application.DataSrc#">
        SELECT pPatients.Patient_ID, pPatients.Pt_Last AS PatientLast, pPatients.Pt_First AS PatientFirst,
        (SELECT count(pAssessments.Assmt_ID)  FROM  #Request.prefix_db_agency#.pAssessments 
        WHERE  pPatients.Patient_ID =  pAssessments.Patient_ID  
        AND pAssessments.Status = 0 
        AND pAdmit.Admit_ID = pAssessments.Admit_ID 
        AND pAssessments.F26 = '1 - Start of care - further visits planned' ) AS  SOC_count,
        (SELECT count(pAuths.Auth_ID)  FROM  #Request.prefix_db_agency#.pAuths
            JOIN #Request.prefix_db_agency#.pAssessments ON  pAssessments.Assmt_ID =  pAuths.Assmt_ID  AND pAssessments.Status = 0 
            WHERE pPatients.Patient_ID =  pAssessments.Patient_ID  
            AND pAdmit.Admit_ID = pAssessments.Admit_ID 
            AND pAssessments.F26 = '1 - Start of care - further visits planned' AND pAuths.Skill = 'SN'
            AND pAuths.Status = 0 ) AS  SOCauth_count,
        (SELECT count(pAssessments.Assmt_ID)  FROM  #Request.prefix_db_agency#.pAssessments 
        WHERE  pPatients.Patient_ID =  pAssessments.Patient_ID  
        AND pAssessments.Status = 0
        AND pAssessments.F26 = '1 - Start of care - further visits planned - Physical Therapy' ) AS  SOCPT_count,
        (SELECT count(pAuths.Auth_ID)  FROM  #Request.prefix_db_agency#.pAuths
            JOIN #Request.prefix_db_agency#.pAssessments ON  pAssessments.Assmt_ID =  pAuths.Assmt_ID  AND pAssessments.Status = 0 
            WHERE pPatients.Patient_ID =  pAssessments.Patient_ID  
            AND pAssessments.F26 = '1 - Start of care - further visits planned - Physical Therapy' AND pAuths.Skill = 'PT'
            AND pAuths.Status = 0 ) AS  SOCPTauth_count,
        (SELECT count(pAssessments.Assmt_ID)  FROM  #Request.prefix_db_agency#.pAssessments 
        WHERE  pPatients.Patient_ID =  pAssessments.Patient_ID  
        AND pAssessments.Status = 0
        AND LEFT(pAssessments.F26,1) = '4' ) AS  Recert_count,
        (SELECT count(pAuths.Auth_ID)  FROM  #Request.prefix_db_agency#.pAuths
            JOIN #Request.prefix_db_agency#.pAssessments ON  pAssessments.Assmt_ID =  pAuths.Assmt_ID  AND pAssessments.Status = 0 
            WHERE pPatients.Patient_ID =  pAssessments.Patient_ID  
            AND LEFT(pAssessments.F26,1) = '4' 
            AND pAuths.Status = 0 ) AS  Recertauth_count,
        (SELECT count(pAssessments.Assmt_ID)  FROM  #Request.prefix_db_agency#.pAssessments 
        WHERE  pPatients.Patient_ID =  pAssessments.Patient_ID  
        AND pAssessments.Status = 0
        AND pAssessments.F26 = 'PT Adult Evaluation' ) AS  PTAdult_count,
        (SELECT count(pAuths.Auth_ID)  FROM  #Request.prefix_db_agency#.pAuths
            JOIN #Request.prefix_db_agency#.pAssessments ON  pAssessments.Assmt_ID =  pAuths.Assmt_ID  AND pAssessments.Status = 0 
            WHERE pPatients.Patient_ID =  pAssessments.Patient_ID  
            AND pAuths.Skill = 'PT'
            AND pAuths.Status = 0 ) AS  PTAdultauth_count,
        (SELECT count(pAssessments.Assmt_ID)  FROM  #Request.prefix_db_agency#.pAssessments 
        WHERE  pPatients.Patient_ID =  pAssessments.Patient_ID  
        AND pAssessments.Status = 0
        AND pAssessments.F26 = 'OT Adult Evaluation' ) AS  OTAdult_count,
        (SELECT count(pAuths.Auth_ID)  FROM  #Request.prefix_db_agency#.pAuths
            JOIN #Request.prefix_db_agency#.pAssessments ON  pAssessments.Assmt_ID =  pAuths.Assmt_ID  AND pAssessments.Status = 0 
            WHERE pPatients.Patient_ID =  pAssessments.Patient_ID  
            AND pAuths.Skill = 'OT'
            AND pAuths.Status = 0 ) AS  OTAdultauth_count,
        (SELECT count(pAssessments.Assmt_ID)  FROM  #Request.prefix_db_agency#.pAssessments 
        WHERE  pPatients.Patient_ID =  pAssessments.Patient_ID  
        AND pAssessments.Status = 0
        AND pAssessments.F26 = 'SN Adult Evaluation' ) AS  SNAdult_count,
        (SELECT count(pAuths.Auth_ID)  FROM  #Request.prefix_db_agency#.pAuths
            JOIN #Request.prefix_db_agency#.pAssessments ON  pAssessments.Assmt_ID =  pAuths.Assmt_ID  AND pAssessments.Status = 0 
            WHERE pPatients.Patient_ID =  pAssessments.Patient_ID  
            AND pAuths.Skill = 'SN'
            AND pAuths.Status = 0 ) AS  SNAdultauth_count,
        (SELECT count(*)
        FROM  #Request.prefix_db_agency#.Communication, #Request.prefix_db_agency#.CommunicationSubjects
        WHERE Communication.Patient_ID = pPatients.Patient_ID
        AND CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
        AND (CommunicationSubjects.Subject like "Discharge Summary - SN%"
         OR CommunicationSubjects.Subject like  'Agency Transfer/Discharge Summary')
        AND Communication.Comm_record_deleted <> 1
        AND Communication.Status = 0 ) AS comm_SNdischarge,
        (SELECT count(*)
        FROM  #Request.prefix_db_agency#.Communication, #Request.prefix_db_agency#.CommunicationSubjects
        WHERE Communication.Patient_ID = pPatients.Patient_ID
        AND CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
        AND (CommunicationSubjects.Subject like "Discharge Summary - PT%"
        OR CommunicationSubjects.Subject like  'Agency Transfer/Discharge Summary')
        AND Communication.Comm_record_deleted <> 1
        AND Communication.Status = 0 ) AS comm_PTdischarge,
        (SELECT count(*)
        FROM  #Request.prefix_db_agency#.Communication, #Request.prefix_db_agency#.CommunicationSubjects
        WHERE Communication.Patient_ID = pPatients.Patient_ID
        AND CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
        AND (CommunicationSubjects.Subject like "Discharge Summary - OT%"
        OR  CommunicationSubjects.Subject like  'Agency Transfer/Discharge Summary')
        AND Communication.Comm_record_deleted <> 1
        AND Communication.Status = 0 ) AS comm_OTdischarge  
        FROM    #Request.prefix_db_agency#.pPatients 
        JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Patient_ID = pPatients.Patient_ID AND pAdmit.Status = 0 AND pAdmit.drafts = 0
        WHERE pPatients.Status  = 0
        AND pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        GROUP BY pPatients.Patient_ID
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC 
    </cfquery>

    <!--- For each patient with missing authorization, get assigned employees and create entries --->
    <cfloop query="getMissingAuthPatients">
        <!--- Check if this patient has missing authorization (matching missing_auths.cfm conditions exactly) --->
        <cfif (getMissingAuthPatients.SOC_count GT 0 AND getMissingAuthPatients.SOCauth_count EQ 0 AND getMissingAuthPatients.comm_SNdischarge EQ 0)
           OR (getMissingAuthPatients.Recert_count GT 0 AND getMissingAuthPatients.Recertauth_count EQ 0)
           OR (getMissingAuthPatients.PTAdult_count GT 0 AND getMissingAuthPatients.PTAdultauth_count EQ 0 AND getMissingAuthPatients.comm_PTdischarge EQ 0)
           OR (getMissingAuthPatients.OTAdult_count GT 0 AND getMissingAuthPatients.OTAdultauth_count EQ 0 AND getMissingAuthPatients.comm_OTdischarge EQ 0)
           OR (getMissingAuthPatients.SNAdult_count GT 0 AND getMissingAuthPatients.SNAdultauth_count EQ 0 AND getMissingAuthPatients.comm_SNdischarge EQ 0)>
            
            <!--- Get employees assigned to this patient's assessments --->
            <cfquery name="getEmployeesForMissingAuth" datasource="#Application.DataSrc#">
                SELECT DISTINCT
                    pEmployee.Emp_ID,
                    pEmployee.Emp_First,
                    pEmployee.Emp_Last
                FROM #Request.prefix_db_agency#.pAssessments pAssessments
                JOIN #Request.prefix_db_agency#.pAdmit pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID AND pAdmit.Status = 0
                JOIN #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID = pAssessments.Assmt_ID
                    AND assessment_assign.F26 = pAssessments.F26
                JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = assessment_assign.Emp_ID
                    AND pEmployee.Status = 0
                WHERE pAssessments.Patient_ID = <cfqueryparam value="#getMissingAuthPatients.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                AND pAssessments.Status = 0
                AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
            </cfquery>

            <!--- If no employees found, skip this patient --->
            <cfif getEmployeesForMissingAuth.recordCount GT 0>
                <cfloop query="getEmployeesForMissingAuth">
                    <cfset header = "missing authorization">
                    <cfset reportLink = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=missing_auths">
                    <cfset description = "<a href='" & reportLink & "'>View missing authorization report for " & HTMLEditFormat(getMissingAuthPatients.PatientLast & ", " & getMissingAuthPatients.PatientFirst) & "</a>">

                    <!--- Check if record already exists for this employee/patient combination to prevent duplicates --->
                    <cfquery name="checkExistingMissingAuth" datasource="#Application.DataSrc#">
                        SELECT COUNT(*) AS totalrecordCount
                        FROM #Request.prefix_db_agency#.Email_Daily_QA
                        WHERE  Patient_ID = <cfqueryparam value="#getMissingAuthPatients.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                          AND Header = <cfqueryparam value="missing authorization" cfsqltype="CF_SQL_VARCHAR">
                          AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                          AND status = 0
                    </cfquery>

                    <cfif checkExistingMissingAuth.totalrecordCount EQ 0>
                        <cfset empFirstNull = NOT Len(Trim(getEmployeesForMissingAuth.Emp_First))>
                        <cfset empLastNull = NOT Len(Trim(getEmployeesForMissingAuth.Emp_Last))>
                        <cfset ptFirstNull = NOT Len(Trim(getMissingAuthPatients.PatientFirst))>
                        <cfset ptLastNull = NOT Len(Trim(getMissingAuthPatients.PatientLast))>
                        <cfquery name="insertMissingAuth" datasource="#Application.DataSrc#">
                            INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                            (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                            VALUES (
                                <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                                <cfqueryparam value="#getEmployeesForMissingAuth.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                                <cfqueryparam value="#getMissingAuthPatients.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                                <cfqueryparam value="#getMissingAuthPatients.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                                <cfqueryparam value="#getMissingAuthPatients.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                                <cfqueryparam value="#getEmployeesForMissingAuth.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                                <cfqueryparam value="#getEmployeesForMissingAuth.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                                <cfqueryparam value="#header#" cfsqltype="CF_SQL_VARCHAR">,
                                <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                                <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                                <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                            )
                        </cfquery>
                    </cfif>
                </cfloop>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Scheduling needed - For employees with r_Sched_Assmt = 3 --->
    <!--- Get patients with scheduling needed assigned to employees with r_Sched_Assmt = 3 --->
    <!--- Query 1: getauths - Insert auths WITH OASIS/Eval (matching scheduling_require.cfm lines 224-239) --->
    <cfquery name="getSchedulingNeededPatients1" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pSchedule_require.Patient_ID,
            pSchedule_require.PatientLast,
            pSchedule_require.PatientFirst,
            assessment_assign.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pSchedule_require 
        INNER JOIN #Request.prefix_db_agency#.assessment_assign ON pSchedule_require.Assmt_ID = assessment_assign.Assmt_ID
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE ((pSchedule_require.SOC_SN = 0 AND pSchedule_require.authSkill = 'SN' AND pSchedule_require.service = '1 - SOC - SN')
            OR (pSchedule_require.SOC_PT = 0 AND pSchedule_require.authSkill = 'PT' AND pSchedule_require.service = '1 - SOC - PT') 
            OR (pSchedule_require.SOC_OT = 0 AND pSchedule_require.authSkill = 'OT' AND pSchedule_require.service = '1 - SOC - OT') 
            OR (pSchedule_require.ROC_SN = 0 AND pSchedule_require.authSkill = 'SN' AND pSchedule_require.service = '3 - ROC - SN') 
            OR (pSchedule_require.ROC_PT = 0 AND pSchedule_require.authSkill = 'PT' AND pSchedule_require.service = '3 - ROC - PT')
            OR (pSchedule_require.SN_Eval = 0 AND pSchedule_require.authSkill = 'SN' AND pSchedule_require.service = 'SN Eval') 
            OR (pSchedule_require.PT_Eval = 0 AND pSchedule_require.authSkill = 'PT' AND pSchedule_require.service = 'PT Eval') 
            OR (pSchedule_require.OT_Eval = 0 AND pSchedule_require.authSkill = 'OT' AND pSchedule_require.service = 'OT Eval') 
            OR (pSchedule_require.ST_Eval = 0 AND pSchedule_require.authSkill = 'ST' AND pSchedule_require.service = 'ST Eval') 
            OR (pSchedule_require.MSW_Eval = 0 AND pSchedule_require.authSkill = 'MSW' AND pSchedule_require.service = 'MSW Eval')
            OR (pSchedule_require.authassmt_id = 0 AND pSchedule_require.schedule_count = 0))
        AND pSchedule_require.service != '0'
        AND pSchedule_require.query_type = 'Insert auths WITH OASIS/Eval'
        AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pEmployee.Status = 0
        AND employee_auth.r_Sched_Assmt = 3
        GROUP BY pSchedule_require.Patient_ID, pSchedule_require.PatientLast, pSchedule_require.PatientFirst, 
                 assessment_assign.Emp_ID, pEmployee.Emp_First, pEmployee.Emp_Last
    </cfquery>

    <!--- Query 2: getmissedvisits - Missed visits (matching scheduling_require.cfm lines 284-305) --->
    <cfquery name="getSchedulingNeededPatients2" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pSchedule_require.Patient_ID,
            pSchedule_require.PatientLast,
            pSchedule_require.PatientFirst,
            assessment_assign.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pSchedule_require 
        INNER JOIN #Request.prefix_db_agency#.assessment_assign ON pSchedule_require.Assmt_ID = assessment_assign.Assmt_ID
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE ((pSchedule_require.Recert_visits = 0 OR pSchedule_require.PTfollow_visits = 0 OR pSchedule_require.OTfollow_visits = 0 OR pSchedule_require.Resump_visits = 0)
            AND pSchedule_require.query_type = 'Insert auths WITH OASIS/Eval')
        AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pEmployee.Status = 0
        AND employee_auth.r_Sched_Assmt = 3
        GROUP BY pSchedule_require.Patient_ID, pSchedule_require.PatientLast, pSchedule_require.PatientFirst, 
                 assessment_assign.Emp_ID, pEmployee.Emp_First, pEmployee.Emp_Last
        
        UNION
        
        SELECT DISTINCT
            pSchedule_require.Patient_ID,
            pSchedule_require.PatientLast,
            pSchedule_require.PatientFirst,
            assessment_assign.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pSchedule_require 
        INNER JOIN #Request.prefix_db_agency#.assessment_assign ON pSchedule_require.Assmt_ID = assessment_assign.Assmt_ID
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pSchedule_require.transfer_visits = 0 
            AND pSchedule_require.death_visits = 0 
            AND pSchedule_require.discharge_visits = 0
            AND pSchedule_require.Resump_visits = 0 
            AND pSchedule_require.query_type = 'Missed ResumptionCare'
        AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pEmployee.Status = 0
        AND employee_auth.r_Sched_Assmt = 3
        GROUP BY pSchedule_require.Patient_ID, pSchedule_require.PatientLast, pSchedule_require.PatientFirst, 
                 assessment_assign.Emp_ID, pEmployee.Emp_First, pEmployee.Emp_Last
    </cfquery>

    <!--- Query 3: Getauth_noassList - Insert auths WITHOUT OASIS/Eval (matching scheduling_require.cfm lines 308-319) --->
    <cfquery name="getSchedulingNeededPatients3" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pSchedule_require.Patient_ID,
            pSchedule_require.PatientLast,
            pSchedule_require.PatientFirst,
            assessment_assign.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pSchedule_require 
        INNER JOIN #Request.prefix_db_agency#.assessment_assign ON pSchedule_require.Assmt_ID = assessment_assign.Assmt_ID
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pSchedule_require.dischargeoasis_count = 0
        AND ((pSchedule_require.total_recertifications > 0 AND pSchedule_require.recertification_count = 0)  
            OR (pSchedule_require.PT_need = 1 AND pSchedule_require.PT_summary = 0 AND pSchedule_require.pt_noauth = 0) 
            OR (pSchedule_require.OT_need = 1 AND pSchedule_require.OT_summary = 0 AND pSchedule_require.ot_noauth = 0) 
            OR (pSchedule_require.ST_need = 1 AND pSchedule_require.ST_summary = 0 AND pSchedule_require.st_noauth = 0) 
            OR (pSchedule_require.MSW_need = 1 AND pSchedule_require.MSW_summary = 0 AND pSchedule_require.msw_noauth = 0) 
            OR pSchedule_require.schedule_count = 0)
        AND pSchedule_require.query_type = 'Insert auths WITHOUT OASIS/Eval'
        AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pEmployee.Status = 0
        AND employee_auth.r_Sched_Assmt = 3
        GROUP BY pSchedule_require.Patient_ID, pSchedule_require.PatientLast, pSchedule_require.PatientFirst, 
                 assessment_assign.Emp_ID, pEmployee.Emp_First, pEmployee.Emp_Last
    </cfquery>

    <!--- Query 4: getROC_scheduling - ROC scheduling (matching scheduling_require.cfm lines 276-282) --->
    <cfquery name="getSchedulingNeededPatients4" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pSchedule_require.Patient_ID,
            pSchedule_require.PatientLast,
            pSchedule_require.PatientFirst,
            assessment_assign.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pSchedule_require 
        INNER JOIN #Request.prefix_db_agency#.assessment_assign ON pSchedule_require.Assmt_ID = assessment_assign.Assmt_ID
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pSchedule_require.transfer_visits = 0 
            AND pSchedule_require.death_visits = 0 
            AND pSchedule_require.discharge_visits = 0
            AND pSchedule_require.F26 = '3 - Resumption of care (after inpatient stay)'
            AND pSchedule_require.schedule_count = 0
        AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pEmployee.Status = 0
        AND employee_auth.r_Sched_Assmt = 3
        GROUP BY pSchedule_require.Patient_ID, pSchedule_require.PatientLast, pSchedule_require.PatientFirst, 
                 assessment_assign.Emp_ID, pEmployee.Emp_First, pEmployee.Emp_Last
    </cfquery>

    <!--- Query 5: getAIIntakeSchedulingNeeded - AI Intake patients (matching scheduling_require.cfm lines 242-274) --->
    <cfquery name="getSchedulingNeededPatients5" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pPatients.Patient_ID,
            pPatients.Pt_Last AS PatientLast,
            pPatients.Pt_First AS PatientFirst,
            pAdmit.Case_Manager AS Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pPatients
        JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Patient_ID = pPatients.Patient_ID
        LEFT JOIN #Request.prefix_db_agency#.pSchedules ON pSchedules.Patient_ID = pPatients.Patient_ID 
            AND pSchedules.Status = 0
            AND pSchedules.Missed = '0'
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON pAdmit.Case_Manager = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pPatients.Status = 0
        AND pAdmit.Status = 0
        AND pAdmit.drafts = 0
        AND pSchedules.Schedule_ID IS NULL
        AND EXISTS (
            SELECT 1 FROM #Request.prefix_db_agency#.patients_ai
            WHERE patients_ai.Patient_ID = pPatients.Patient_ID
            AND patients_ai.status = 0
        )
        AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pEmployee.Status = 0
        AND employee_auth.r_Sched_Assmt = 3
        GROUP BY pPatients.Patient_ID, pPatients.Pt_Last, pPatients.Pt_First, 
                 pAdmit.Case_Manager, pEmployee.Emp_First, pEmployee.Emp_Last
    </cfquery>

    <!--- Combine all scheduling needed patients --->
    <cfset getSchedulingNeededPatients = QueryNew("Patient_ID,PatientLast,PatientFirst,Emp_ID,Emp_First,Emp_Last", "Integer,Varchar,Varchar,Integer,Varchar,Varchar")>
    <cfset existingPatientEmpCombos = "">
    <cfloop query="getSchedulingNeededPatients1">
        <cfset comboKey = getSchedulingNeededPatients1.Patient_ID & "_" & getSchedulingNeededPatients1.Emp_ID>
        <cfif NOT ListFind(existingPatientEmpCombos, comboKey)>
            <cfset QueryAddRow(getSchedulingNeededPatients)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Patient_ID", getSchedulingNeededPatients1.Patient_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientLast", getSchedulingNeededPatients1.PatientLast)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientFirst", getSchedulingNeededPatients1.PatientFirst)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_ID", getSchedulingNeededPatients1.Emp_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_First", getSchedulingNeededPatients1.Emp_First)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_Last", getSchedulingNeededPatients1.Emp_Last)>
            <cfset existingPatientEmpCombos = ListAppend(existingPatientEmpCombos, comboKey)>
        </cfif>
    </cfloop>
    <cfloop query="getSchedulingNeededPatients2">
        <cfset comboKey = getSchedulingNeededPatients2.Patient_ID & "_" & getSchedulingNeededPatients2.Emp_ID>
        <cfif NOT ListFind(existingPatientEmpCombos, comboKey)>
            <cfset QueryAddRow(getSchedulingNeededPatients)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Patient_ID", getSchedulingNeededPatients2.Patient_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientLast", getSchedulingNeededPatients2.PatientLast)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientFirst", getSchedulingNeededPatients2.PatientFirst)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_ID", getSchedulingNeededPatients2.Emp_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_First", getSchedulingNeededPatients2.Emp_First)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_Last", getSchedulingNeededPatients2.Emp_Last)>
            <cfset existingPatientEmpCombos = ListAppend(existingPatientEmpCombos, comboKey)>
        </cfif>
    </cfloop>
    <cfloop query="getSchedulingNeededPatients3">
        <cfset comboKey = getSchedulingNeededPatients3.Patient_ID & "_" & getSchedulingNeededPatients3.Emp_ID>
        <cfif NOT ListFind(existingPatientEmpCombos, comboKey)>
            <cfset QueryAddRow(getSchedulingNeededPatients)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Patient_ID", getSchedulingNeededPatients3.Patient_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientLast", getSchedulingNeededPatients3.PatientLast)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientFirst", getSchedulingNeededPatients3.PatientFirst)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_ID", getSchedulingNeededPatients3.Emp_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_First", getSchedulingNeededPatients3.Emp_First)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_Last", getSchedulingNeededPatients3.Emp_Last)>
            <cfset existingPatientEmpCombos = ListAppend(existingPatientEmpCombos, comboKey)>
        </cfif>
    </cfloop>
    <cfloop query="getSchedulingNeededPatients4">
        <cfset comboKey = getSchedulingNeededPatients4.Patient_ID & "_" & getSchedulingNeededPatients4.Emp_ID>
        <cfif NOT ListFind(existingPatientEmpCombos, comboKey)>
            <cfset QueryAddRow(getSchedulingNeededPatients)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Patient_ID", getSchedulingNeededPatients4.Patient_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientLast", getSchedulingNeededPatients4.PatientLast)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientFirst", getSchedulingNeededPatients4.PatientFirst)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_ID", getSchedulingNeededPatients4.Emp_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_First", getSchedulingNeededPatients4.Emp_First)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_Last", getSchedulingNeededPatients4.Emp_Last)>
            <cfset existingPatientEmpCombos = ListAppend(existingPatientEmpCombos, comboKey)>
        </cfif>
    </cfloop>
    <cfloop query="getSchedulingNeededPatients5">
        <cfset comboKey = getSchedulingNeededPatients5.Patient_ID & "_" & getSchedulingNeededPatients5.Emp_ID>
        <cfif NOT ListFind(existingPatientEmpCombos, comboKey)>
            <cfset QueryAddRow(getSchedulingNeededPatients)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Patient_ID", getSchedulingNeededPatients5.Patient_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientLast", getSchedulingNeededPatients5.PatientLast)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "PatientFirst", getSchedulingNeededPatients5.PatientFirst)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_ID", getSchedulingNeededPatients5.Emp_ID)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_First", getSchedulingNeededPatients5.Emp_First)>
            <cfset QuerySetCell(getSchedulingNeededPatients, "Emp_Last", getSchedulingNeededPatients5.Emp_Last)>
            <cfset existingPatientEmpCombos = ListAppend(existingPatientEmpCombos, comboKey)>
        </cfif>
    </cfloop>

    <!--- Insert record for each patient-employee combination --->
    <cfloop query="getSchedulingNeededPatients">
        <cfset header = "scheduling needed">
        <cfset reportLink = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=scheduling_require">
        <cfset description = "<a href='" & reportLink & "'>View scheduling needed report for " & HTMLEditFormat(getSchedulingNeededPatients.PatientLast & ", " & getSchedulingNeededPatients.PatientFirst) & "</a>">

        <!--- Check if record already exists for this employee/patient combination to prevent duplicates --->
        <cfquery name="checkExistingSchedulingNeeded" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE  Patient_ID = <cfqueryparam value="#getSchedulingNeededPatients.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
              AND Header = <cfqueryparam value="scheduling needed" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingSchedulingNeeded.totalrecordCount EQ 0>
            <cfset empFirstNull = NOT Len(Trim(getSchedulingNeededPatients.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getSchedulingNeededPatients.Emp_Last))>
            <cfset ptFirstNull = NOT Len(Trim(getSchedulingNeededPatients.PatientFirst))>
            <cfset ptLastNull = NOT Len(Trim(getSchedulingNeededPatients.PatientLast))>
            <cfquery name="insertSchedulingNeeded" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#getSchedulingNeededPatients.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getSchedulingNeededPatients.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getSchedulingNeededPatients.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#getSchedulingNeededPatients.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#getSchedulingNeededPatients.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#getSchedulingNeededPatients.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="#header#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Authorizations required - Find Clinical Managers from pAdmit where r_Auth = 1 --->
    <cfquery name="getAuthorizationsRequired" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            employee_auth.eaRole,
            employee_auth.r_Auth
        FROM #Request.prefix_db_agency#.pAdmit pAdmit
        INNER JOIN #Request.prefix_db_lookup#.pEmployee pEmployee ON pAdmit.Case_manager = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pAdmit.Status = 0
          AND pAdmit.Case_manager > 0
          AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
          AND employee_auth.r_Auth = 1
    </cfquery>

    <cfloop query="getAuthorizationsRequired">
        <cfset description = "Authorizations required for " & HTMLEditFormat(getAuthorizationsRequired.Emp_First & " " & getAuthorizationsRequired.Emp_Last)>
        <cfif Len(Trim(getAuthorizationsRequired.eaRole))>
            <cfset description = description & " (" & HTMLEditFormat(getAuthorizationsRequired.eaRole) & ")">
        </cfif>

        <!--- Check if record already exists for this employee to prevent duplicates --->
        <cfquery name="checkExistingAuthRequired" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE Emp_ID = <cfqueryparam value="#getAuthorizationsRequired.Emp_ID#" cfsqltype="CF_SQL_INTEGER">
              AND Header = <cfqueryparam value="Authorizations required" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingAuthRequired.totalrecordCount EQ 0>
            <cfquery name="insertAuthorizationsRequired" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#getAuthorizationsRequired.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="" cfsqltype="CF_SQL_INTEGER" null="yes">,
                    <cfqueryparam value="" cfsqltype="CF_SQL_VARCHAR" null="yes">,
                    <cfqueryparam value="" cfsqltype="CF_SQL_VARCHAR" null="yes">,
                    <cfqueryparam value="#getAuthorizationsRequired.Emp_First#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#getAuthorizationsRequired.Emp_Last#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="Authorizations required" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Authorizations required - Find users where r_Auth = 3 and pull ALL expiring authorizations --->
    <cfquery name="getExpiringAuthorizationsForR3" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            employee_auth.eaRole,
            employee_auth.r_Auth,
            pAuths.AutoAuth_ID,
            pAuths.Patient_ID,
            pAuths.Date_End,
            pAuths.Date_Start,
            pAuths.Skill,
            pPatients.Pt_First,
            pPatients.Pt_Last,
            pPayer.Pay_Name,
            pRevenue_Code.Visit_Type,
            pRevenue_Code.Rev_Code
        FROM #Request.prefix_db_agency#.pAdmit pAdmit
        INNER JOIN #Request.prefix_db_lookup#.pEmployee pEmployee ON pAdmit.Case_manager = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        INNER JOIN #Request.prefix_db_agency#.pAuths ON pAdmit.Patient_ID = pAuths.Patient_ID
        INNER JOIN #Request.prefix_db_agency#.pPatients ON pAuths.Patient_ID = pPatients.Patient_ID
        INNER JOIN #Request.prefix_db_agency#.pRevenue_Code ON pRevenue_Code.Rev_CodeID = pAuths.Rev_ID
        INNER JOIN #Request.prefix_db_agency#.pPtPayer ON pPtPayer.PtPayer_ID = pAuths.PtPayer_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.pPayer ON pPayer.Pay_ID = pPtPayer.Payer_ID
        WHERE pAdmit.Status = 0
          AND pAdmit.Case_manager > 0
          AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
          AND employee_auth.r_Auth = 3
          AND pAuths.STATUS = 0
          AND pRevenue_Code.Status = 0
          AND pPtPayer.Status = 0
          AND pPayer.Status = 0
          AND pPatients.Status = 0
          AND pAuths.Date_End >= NOW()
        GROUP BY pAuths.AutoAuth_ID
        ORDER BY pAuths.Date_End ASC
    </cfquery>

    <cfloop query="getExpiringAuthorizationsForR3">
        <cfset todaydate = DateFormat(Now(), "yyyy-mm-dd")>
        <cfset diffdays = DateDiff("d", todaydate, getExpiringAuthorizationsForR3.Date_End)>
        <cfset description = "Expiring authorization for " & HTMLEditFormat(getExpiringAuthorizationsForR3.Pt_First & " " & getExpiringAuthorizationsForR3.Pt_Last)>
        <cfif Len(Trim(getExpiringAuthorizationsForR3.Pay_Name))>
            <cfset description = description & " - " & HTMLEditFormat(getExpiringAuthorizationsForR3.Pay_Name)>
        </cfif>
        <cfif Len(Trim(getExpiringAuthorizationsForR3.Skill))>
            <cfset description = description & " (" & HTMLEditFormat(getExpiringAuthorizationsForR3.Skill) & ")">
        </cfif>
        <cfset description = description & " - Expires: " & DateFormat(getExpiringAuthorizationsForR3.Date_End, "mm/dd/yyyy") & " (" & diffdays & " days)">
        <cfif Len(Trim(getExpiringAuthorizationsForR3.eaRole))>
            <cfset description = description & " - Manager: " & HTMLEditFormat(getExpiringAuthorizationsForR3.Emp_First & " " & getExpiringAuthorizationsForR3.Emp_Last) & " (" & HTMLEditFormat(getExpiringAuthorizationsForR3.eaRole) & ")">
        </cfif>

        <!--- Check if record already exists for this authorization to prevent duplicates --->
        <cfquery name="checkExistingExpiringAuth" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE  Patient_ID = <cfqueryparam value="#getExpiringAuthorizationsForR3.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
              AND Header = <cfqueryparam value="Authorizations required" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND Description LIKE <cfqueryparam value="%Expiring authorization for%#HTMLEditFormat(getExpiringAuthorizationsForR3.Pt_First & " " & getExpiringAuthorizationsForR3.Pt_Last)#%" cfsqltype="CF_SQL_VARCHAR">
              AND status = 0
        </cfquery>

        <cfif checkExistingExpiringAuth.totalrecordCount EQ 0>
            <cfquery name="insertExpiringAuthorizationsForR3" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#getExpiringAuthorizationsForR3.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getExpiringAuthorizationsForR3.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getExpiringAuthorizationsForR3.Pt_Last#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#getExpiringAuthorizationsForR3.Pt_First#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#getExpiringAuthorizationsForR3.Emp_First#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#getExpiringAuthorizationsForR3.Emp_Last#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="Authorizations required" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Frequency Non-Compliance - Find patients with frequency non-compliance where employee r_Visit_Freq = 1 --->
    <cfscript>
        // Get today's date
        today = now();
        // Find the day of the week (1 = Sunday, 2 = Monday, ..., 7 = Saturday)
        dayOfWeek = dayOfWeek(today);
        // Calculate the difference in days from Sunday
        daysSinceSunday = dayOfWeek - 1;
        // Calculate the start of the week (Sunday)
        startOfWeek = dateAdd("d", -daysSinceSunday, today);
    </cfscript>

    <cfquery name="getFrequencyNonCompliance" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            employee_auth.eaRole,
            employee_auth.r_Visit_Freq,
            pAuths_weeks.Auths_weeks_ID,
            pAuths_weeks.Auth_ID,
            pAuths_weeks.Week_No,
            pAuths_weeks.Week_Start,
            pAuths_weeks.Week_End,
            pAuths_weeks.Total_visits,
            pPatients.Patient_ID,
            pPatients.Pt_First,
            pPatients.Pt_Last,
            pAuths.Skill,
            pAssessments.F26,
            pAssessments.Assmt_ID,
            (SELECT count(DISTINCT Schedule_ID) 
             FROM #Request.prefix_db_agency#.pSchedules
             WHERE pSchedules.Status = 0 
               AND pSchedules.Auth_ID = pAuths.Auth_ID
               AND pAuths.Skill = pSchedules.Skill 
               AND Visit_Date <= pAuths_weeks.Week_End 
               AND Visit_Date >= pAuths_weeks.Week_Start
               AND Missed = 0) AS Visit_Count
        FROM #Request.prefix_db_agency#.pAuths_weeks
        INNER JOIN #Request.prefix_db_agency#.pAuths ON pAuths_weeks.Auth_ID = pAuths.Auth_ID AND pAuths.Status = 0
        INNER JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pAuths.Assmt_ID AND pAssessments.Status = 0
        INNER JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID
        INNER JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON pAdmit.Case_manager = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        INNER JOIN #Request.prefix_db_agency#.pPtPayer ON pPtPayer.PtPayer_ID = pAuths.PtPayer_ID AND pPtPayer.status = 0
        INNER JOIN #Request.prefix_db_agency#.pPayer ON pPtPayer.Payer_ID = pPayer.Pay_ID AND pPayer.status = 0 AND LEFT(pPayer.M0150,1) IN ('1','2')
        WHERE pPatients.Status < 1
          AND pAdmit.Status = 0
          AND pAdmit.drafts = 0
          AND pAdmit.Case_manager > 0
          AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
          AND employee_auth.r_Visit_Freq = 1
          AND pAuths.Visitfreq_Placeholder = 0
          AND pAuths_weeks.Status = 0
          AND (pAuths_weeks.Total_visits > 0 OR pAuths.prn_visits > 0)
          AND pAuths_weeks.Week_Start <= <cfqueryparam value="#DateFormat(startOfWeek, 'yyyy-mm-dd')#" cfsqltype="CF_SQL_DATE">
          AND pAssessments.Admit_ID NOT IN (
              SELECT pAssessments.Admit_ID 
              FROM #Request.prefix_db_agency#.pAssessments  
              WHERE (pAssessments.F26 LIKE '9%' OR pAssessments.F26 LIKE '7%' OR pAssessments.F26 LIKE '8%')
                AND pAssessments.F176 <= <cfqueryparam value="#Now()#" cfsqltype="CF_SQL_TIMESTAMP">
                AND pAssessments.Status = 0
          )
        GROUP BY pAuths_weeks.Auths_weeks_ID
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <cfloop query="getFrequencyNonCompliance">
        <cfset missing = getFrequencyNonCompliance.Total_visits - getFrequencyNonCompliance.Visit_Count>
        <cfif missing GT 0>
            <cfset description = "Frequency non-compliance for " & HTMLEditFormat(getFrequencyNonCompliance.Pt_First & " " & getFrequencyNonCompliance.Pt_Last)>
            <cfif Len(Trim(getFrequencyNonCompliance.Skill))>
                <cfset description = description & " - " & HTMLEditFormat(getFrequencyNonCompliance.Skill)>
            </cfif>
            <cfset description = description & " - Week " & getFrequencyNonCompliance.Week_No & " (" & DateFormat(getFrequencyNonCompliance.Week_Start, "mm/dd/yyyy") & " to " & DateFormat(getFrequencyNonCompliance.Week_End, "mm/dd/yyyy") & ")">
            <cfset description = description & " - Ordered: " & getFrequencyNonCompliance.Total_visits & ", Scheduled: " & getFrequencyNonCompliance.Visit_Count & ", Missing: " & missing>
            <cfif Len(Trim(getFrequencyNonCompliance.eaRole))>
                <cfset description = description & " - Manager: " & HTMLEditFormat(getFrequencyNonCompliance.Emp_First & " " & getFrequencyNonCompliance.Emp_Last) & " (" & HTMLEditFormat(getFrequencyNonCompliance.eaRole) & ")">
            </cfif>

            <!--- Check if record already exists for this authorization week to prevent duplicates --->
            <cfquery name="checkExistingFreqNonComp" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE  Patient_ID = <cfqueryparam value="#getFrequencyNonCompliance.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND Header = <cfqueryparam value="Frequency Non-Compliance" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND Description LIKE <cfqueryparam value="%Week #getFrequencyNonCompliance.Week_No#%#HTMLEditFormat(getFrequencyNonCompliance.Pt_First & " " & getFrequencyNonCompliance.Pt_Last)#%" cfsqltype="CF_SQL_VARCHAR">
                  AND status = 0
            </cfquery>

            <cfif checkExistingFreqNonComp.totalrecordCount EQ 0>
                <cfquery name="insertFrequencyNonCompliance" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#getFrequencyNonCompliance.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getFrequencyNonCompliance.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getFrequencyNonCompliance.Pt_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getFrequencyNonCompliance.Pt_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getFrequencyNonCompliance.Emp_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getFrequencyNonCompliance.Emp_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="Frequency Non-Compliance" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Frequency Non-Compliance - For employees with r_Visit_Freq = 3 --->
    <!--- First, collect all patients that need frequency non-compliance entries --->
    <!--- Query 1: nonvisit_compliance - Weekly entries (matching visits_non_compliancenew.cfm lines 34-80) --->
    <cfquery name="getFrequencyNonComplianceWeekly" datasource="#Application.DataSrc#">
        SELECT 
            pAuths_weeks.*,
            pPatients.Patient_ID, 
            pPatients.Pt_Last AS PatientLast,
            pPatients.Pt_First AS PatientFirst,
            pAuths.Skill,
            pAssessments.F26,  
            pAssessments.Assmt_ID,
            pAuths_weeks.Total_visits as totalvisit,
            assessment_assign.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            (SELECT count(DISTINCT Schedule_ID) 
             FROM #Request.prefix_db_agency#.pSchedules
             WHERE pSchedules.Status = 0 
               AND pSchedules.Auth_ID = pAuths.Auth_ID
               AND pAuths.Skill = pSchedules.Skill 
               AND Visit_Date <= pAuths_weeks.Week_End 
               AND Visit_Date >= pAuths_weeks.Week_Start
               AND Missed = 0) AS Visit_Count
        FROM #Request.prefix_db_agency#.pAuths_weeks
        JOIN #Request.prefix_db_agency#.pAuths ON pAuths_weeks.Auth_ID = pAuths.Auth_ID AND pAuths.Status = 0
        JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pAuths.Assmt_ID AND pAssessments.Status = 0
        JOIN #Request.prefix_db_agency#.pPtPayer pPtPayer ON pPtPayer.PtPayer_ID = pAuths.PtPayer_ID AND pPtPayer.status = 0
        JOIN #Request.prefix_db_agency#.pPayer pp ON pPtPayer.Payer_ID = pp.Pay_ID AND pp.status = 0 AND LEFT(pp.M0150,1) IN ('1','2')
        JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID
        INNER JOIN #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID = pAssessments.Assmt_ID
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pPatients.Status < 1
          AND Week_Start <= <cfqueryparam value="#DateFormat(startOfWeek, 'yyyy-mm-dd')#" cfsqltype="CF_SQL_DATE">
          AND Week_Start >= '2025-01-01'
          AND pAuths.Visitfreq_Placeholder = 0
          AND pAssessments.Admit_ID NOT IN (
              SELECT pAssessments.Admit_ID 
              FROM #Request.prefix_db_agency#.pAssessments  
              WHERE (pAssessments.F26 LIKE '9%' OR pAssessments.F26 LIKE '7%' OR pAssessments.F26 LIKE '8%')
                AND pAssessments.F176 <= <cfqueryparam value="#Now()#" cfsqltype="CF_SQL_TIMESTAMP">
                AND pAssessments.Status = 0
          )
          AND pAssessments.Admit_ID IN (
              SELECT pAdmit.Admit_ID 
              FROM #Request.prefix_db_agency#.pAdmit 
              WHERE pAdmit.Status = 0 AND pAdmit.drafts = 0
          )
          AND pAuths_weeks.Status = 0
          AND (pAuths_weeks.Total_visits > 0 OR pAuths.prn_visits > 0)
          AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
           AND employee_auth.r_Visit_Freq = 3
        GROUP BY pAuths_weeks.Auths_weeks_ID, pPatients.Patient_ID, pPatients.Pt_Last, pPatients.Pt_First,
                 pAuths.Skill, pAssessments.F26, pAssessments.Assmt_ID, pAuths_weeks.Total_visits,
                 assessment_assign.Emp_ID, pEmployee.Emp_First, pEmployee.Emp_Last
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <!--- Query 2: incomplete_authorizations - Incomplete authorizations (matching visits_non_compliancenew.cfm lines 83-120) --->
    <cfquery name="getFrequencyNonComplianceIncomplete" datasource="#Application.DataSrc#">
        SELECT 
            pPatients.Patient_ID, 
            pPatients.Pt_Last AS PatientLast, 
            pPatients.Pt_First AS PatientFirst, 
            pAuths.Skill, 
            pAuths.Auth_ID, 
            pAuths.Total_Visits as totalvisit,
            pAssessments.F26, 
            pAssessments.Assmt_ID, 
            pAssessments.F177, 
            pAssessments.F178,
            assessment_assign.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            (SELECT count(DISTINCT Schedule_ID) 
             FROM #Request.prefix_db_agency#.pSchedules
             WHERE pSchedules.Status = 0 
               AND pSchedules.Auth_ID = pAuths.Auth_ID
               AND pAuths.Skill = pSchedules.Skill 
               AND Missed = 0) AS Visit_Count
        FROM #Request.prefix_db_agency#.pAuths
        JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pAuths.Assmt_ID AND pAssessments.Status = 0
        JOIN #Request.prefix_db_agency#.pPtPayer pPtPayer ON pPtPayer.PtPayer_ID = pAuths.PtPayer_ID AND pPtPayer.status = 0
        JOIN #Request.prefix_db_agency#.pPayer pp ON pPtPayer.Payer_ID = pp.Pay_ID AND pp.status = 0
        AND LEFT(pp.M0150,1) IN ('1','2')
        JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID
        INNER JOIN #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID = pAssessments.Assmt_ID
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON assessment_assign.Emp_ID = pEmployee.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pPatients.Status < 1
          AND pAuths.Status = 0
          AND pAuths.Visitfreq_Placeholder = 0
          AND pAuths.date_start IS NULL
          AND pAuths.date_end IS NULL
          AND pAuths.Total_Visits = 0
          AND pAssessments.Admit_ID NOT IN (
              SELECT pAssessments.Admit_ID 
              FROM #Request.prefix_db_agency#.pAssessments  
              WHERE (pAssessments.F26 LIKE '9%' OR pAssessments.F26 LIKE '7%' OR pAssessments.F26 LIKE '8%')
                AND pAssessments.F176 <= <cfqueryparam value="#Now()#" cfsqltype="CF_SQL_TIMESTAMP">
                AND pAssessments.Status = 0
          )
          AND pAssessments.Admit_ID IN (
              SELECT pAdmit.Admit_ID 
              FROM #Request.prefix_db_agency#.pAdmit 
              WHERE pAdmit.Status = 0 AND pAdmit.drafts = 0
          )
          AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
          AND employee_auth.r_Visit_Freq = 3 
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <!--- Collect all unique patient-employee combinations first --->
    <cfset allFreqNonCompPatients = QueryNew("Patient_ID,Emp_ID,PatientLast,PatientFirst,Emp_First,Emp_Last,Description", "Integer,Integer,Varchar,Varchar,Varchar,Varchar,Varchar")>
    
    <!--- Process weekly entries --->
    <cfloop query="getFrequencyNonComplianceWeekly">
        <cfset missing = getFrequencyNonComplianceWeekly.totalvisit - getFrequencyNonComplianceWeekly.Visit_Count>
        <cfif missing NEQ 0>
            <cfset reportLink = "index.cfm?page=dashboard&cat&rpt=visits_non_compliancenew">
            <cfset description = HTMLEditFormat(getFrequencyNonComplianceWeekly.PatientFirst & " " & getFrequencyNonComplianceWeekly.PatientLast) & " - " & HTMLEditFormat(getFrequencyNonComplianceWeekly.Skill) & " - Week " & getFrequencyNonComplianceWeekly.Week_No & " (" & DateFormat(getFrequencyNonComplianceWeekly.Week_Start, "mm/dd/yyyy") & " to " & DateFormat(getFrequencyNonComplianceWeekly.Week_End, "mm/dd/yyyy") & ") - Ordered: " & getFrequencyNonComplianceWeekly.totalvisit & ", Scheduled: " & getFrequencyNonComplianceWeekly.Visit_Count & ", Missing: " & missing & " - <a href='" & reportLink & "'>View Report</a>">
            
            <!--- Check if this patient-employee combo already exists in our collection --->
            <cfset found = false>
            <cfloop query="allFreqNonCompPatients">
                <cfif allFreqNonCompPatients.Patient_ID EQ getFrequencyNonComplianceWeekly.Patient_ID 
                      AND allFreqNonCompPatients.Emp_ID EQ getFrequencyNonComplianceWeekly.Emp_ID>
                    <cfset found = true>
                    <cfbreak>
                </cfif>
            </cfloop>
            
            <cfif NOT found>
                <cfset QueryAddRow(allFreqNonCompPatients)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Patient_ID", getFrequencyNonComplianceWeekly.Patient_ID)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Emp_ID", getFrequencyNonComplianceWeekly.Emp_ID)>
                <cfset QuerySetCell(allFreqNonCompPatients, "PatientLast", getFrequencyNonComplianceWeekly.PatientLast)>
                <cfset QuerySetCell(allFreqNonCompPatients, "PatientFirst", getFrequencyNonComplianceWeekly.PatientFirst)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Emp_First", getFrequencyNonComplianceWeekly.Emp_First)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Emp_Last", getFrequencyNonComplianceWeekly.Emp_Last)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Description", description)>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Process incomplete authorizations --->
    <cfloop query="getFrequencyNonComplianceIncomplete">
        <cfset missing = getFrequencyNonComplianceIncomplete.totalvisit - getFrequencyNonComplianceIncomplete.Visit_Count>
        <cfif missing GT 0>
            <cfset reportLink = "index.cfm?page=dashboard&cat&rpt=visits_non_compliancenew">
            <cfset startDate = "">
            <cfset endDate = "">
            <cfif isDefined('getFrequencyNonComplianceIncomplete.F177') AND getFrequencyNonComplianceIncomplete.F177 IS NOT ''>
                <cfset startDate = DateFormat(getFrequencyNonComplianceIncomplete.F177, "mm/dd/yyyy")>
            <cfelse>
                <cfset startDate = "-">
            </cfif>
            <cfif isDefined('getFrequencyNonComplianceIncomplete.F178') AND getFrequencyNonComplianceIncomplete.F178 IS NOT ''>
                <cfset endDate = DateFormat(getFrequencyNonComplianceIncomplete.F178, "mm/dd/yyyy")>
            <cfelse>
                <cfset endDate = "-">
            </cfif>
            <cfset description = HTMLEditFormat(getFrequencyNonComplianceIncomplete.PatientFirst & " " & getFrequencyNonComplianceIncomplete.PatientLast) & " - " & HTMLEditFormat(getFrequencyNonComplianceIncomplete.Skill) & " - Start: " & startDate & ", End: " & endDate & " - Ordered: " & getFrequencyNonComplianceIncomplete.totalvisit & ", Scheduled: " & getFrequencyNonComplianceIncomplete.Visit_Count & ", Missing: " & missing & " (Non-Medical/Payer Bypass) - <a href='" & reportLink & "'>View Report</a>">
            
            <!--- Check if this patient-employee combo already exists in our collection --->
            <cfset found = false>
            <cfloop query="allFreqNonCompPatients">
                <cfif allFreqNonCompPatients.Patient_ID EQ getFrequencyNonComplianceIncomplete.Patient_ID 
                      AND allFreqNonCompPatients.Emp_ID EQ getFrequencyNonComplianceIncomplete.Emp_ID>
                    <cfset found = true>
                    <cfbreak>
                </cfif>
            </cfloop>
            
            <cfif NOT found>
                <cfset QueryAddRow(allFreqNonCompPatients)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Patient_ID", getFrequencyNonComplianceIncomplete.Patient_ID)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Emp_ID", getFrequencyNonComplianceIncomplete.Emp_ID)>
                <cfset QuerySetCell(allFreqNonCompPatients, "PatientLast", getFrequencyNonComplianceIncomplete.PatientLast)>
                <cfset QuerySetCell(allFreqNonCompPatients, "PatientFirst", getFrequencyNonComplianceIncomplete.PatientFirst)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Emp_First", getFrequencyNonComplianceIncomplete.Emp_First)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Emp_Last", getFrequencyNonComplianceIncomplete.Emp_Last)>
                <cfset QuerySetCell(allFreqNonCompPatients, "Description", description)>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Get total count for header --->
    <cfset totalFreqNonCompCount = allFreqNonCompPatients.recordCount>
    
    <!--- Insert all records with the same count in header --->
    <cfloop query="allFreqNonCompPatients">
        <!--- Check if record already exists --->
        <cfquery name="checkExistingFreqNonComp" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE  Patient_ID = <cfqueryparam value="#allFreqNonCompPatients.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
              AND Header LIKE <cfqueryparam value="%frequency non-compliance%" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingFreqNonComp.totalrecordCount EQ 0>
            <cfset header = "frequency non-compliance">
            <cfset descript = header & " " &allFreqNonCompPatients.Description />
            <cfquery name="insertFrequencyNonCompliance" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#allFreqNonCompPatients.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#allFreqNonCompPatients.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#allFreqNonCompPatients.PatientLast#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#allFreqNonCompPatients.PatientFirst#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#allFreqNonCompPatients.Emp_First#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#allFreqNonCompPatients.Emp_Last#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#header#" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#descript#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Missing 485 - Find patients with missing 485 forms where employee r_485_Create = 3 --->
    <!--- Query 1: Get485List logic (Orphan_Field = 1, Med_Recon_Field = 1, Left(F26,1) IN ('1','4')) --->
    <cfquery name="getMissing485List" datasource="#Application.DataSrc#">
        SELECT 
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            employee_auth.eaRole,
            employee_auth.r_485_Create,
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pPatients.Status as pStatus,
            pAssessments.Assmt_ID,
            pAssessments.F26,
            pAssessments.F177,
            pAssessments.F178,
            (SELECT count(*) 
             FROM #Request.prefix_db_agency#.pCMS4857 
             WHERE pCMS4857.Assmt_ID = pAssessments.Assmt_ID 
               AND Status = 0 
               AND Form_Type = 'Form 485') AS new485_require
        FROM #Request.prefix_db_agency#.pAssessments
        INNER JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID AND pPatients.Status IN (0,1,4)
        INNER JOIN #Request.prefix_db_agency#.pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID AND pAdmit.status = 0
        INNER JOIN #Request.prefix_db_agency#.pSchedules ON pSchedules.Assmt_ID = pAssessments.Assmt_ID AND pSchedules.status = 0
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pAdmit.Case_Manager
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pAssessments.status = 0
          AND pAssessments.F25 = 1
          AND Left(pAssessments.F26,1) IN ('1','4')
          AND pSchedules.Visit_Date > pAssessments.F177
          AND pAssessments.Orphan_Field IN (1)
          AND pPatients.Med_Recon_Field IN (1)
          AND pAdmit.Case_Manager > 0
          AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
          AND employee_auth.r_485_Create = 3
          AND pAdmit.Admit_ID NOT IN (
              SELECT pAssessments.Admit_ID 
              FROM #Request.prefix_db_agency#.pAssessments  
              WHERE (pAssessments.F26 LIKE '9%' OR pAssessments.F26 LIKE '7%' OR pAssessments.F26 LIKE '8%')
                AND pAssessments.Status = 0 
                AND F176 < <cfqueryparam value="#DateFormat(now(),'yyyy-mm-dd')#" cfsqltype="CF_SQL_DATE">
          )
        GROUP BY pAssessments.Assmt_ID
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <!--- Query 2: Get485EvalList logic (Orphan_Field NOT IN (1), Med_Recon_Field NOT IN (1), F26 like 'PT Adult%' etc.) --->
    <cfquery name="getMissing485EvalList" datasource="#Application.DataSrc#">
        SELECT 
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            employee_auth.eaRole,
            employee_auth.r_485_Create,
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pPatients.Status as pStatus,
            pAssessments.Assmt_ID,
            pAssessments.F26,
            pAssessments.F177,
            pAssessments.F178,
            (SELECT count(*) 
             FROM #Request.prefix_db_agency#.pCMS4857  
             WHERE pCMS4857.Assmt_ID IN (
                 SELECT Assmt_ID 
                 FROM #Request.prefix_db_agency#.pAssessments pass 
                 WHERE pass.Admit_ID = pAdmit.Admit_ID 
                   AND pass.status = 0
             )
               AND Status = 0 
               AND Form_Type = 'Form 485') AS new485_require
        FROM #Request.prefix_db_agency#.pAssessments
        INNER JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID AND pPatients.Status IN (0,1,4)
        INNER JOIN #Request.prefix_db_agency#.pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID AND pAdmit.status = 0
        INNER JOIN #Request.prefix_db_agency#.pSchedules ON pSchedules.Assmt_ID = pAssessments.Assmt_ID AND pSchedules.status = 0
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pAdmit.Case_Manager
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pAssessments.status = 0
          AND pAssessments.F25 = 1
          AND (F26 LIKE 'PT Adult%' OR F26 LIKE 'OT Adult%' OR F26 LIKE 'ST Adult%' OR F26 LIKE 'SN Adult%')
          AND pSchedules.Visit_Date > pAssessments.F177
          AND pAdmit.Admit_ID NOT IN (
              SELECT Admit_ID 
              FROM #Request.prefix_db_agency#.pAssessments 
              WHERE Status = 0 
                AND Left(F26,1) IN ('1','4')
          )
          AND pAssessments.Orphan_Field NOT IN (1)
          AND pPatients.Med_Recon_Field NOT IN (1)
          AND pAdmit.Case_Manager > 0
          AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
          AND employee_auth.r_485_Create = 3
          AND pAdmit.Admit_ID NOT IN (
              SELECT pAssessments.Admit_ID 
              FROM #Request.prefix_db_agency#.pAssessments  
              WHERE (pAssessments.F26 LIKE '9%' OR pAssessments.F26 LIKE '7%' OR pAssessments.F26 LIKE '8%')
                AND pAssessments.Status = 0 
                AND F176 < <cfqueryparam value="#DateFormat(now(),'yyyy-mm-dd')#" cfsqltype="CF_SQL_DATE">
          )
        GROUP BY pAssessments.Assmt_ID
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <!--- Process Get485List results --->
    <cfloop query="getMissing485List">
        <cfif getMissing485List.new485_require EQ 0>
            <cfset diffdays = DateDiff("d", getMissing485List.F177, Now())>
            <cfset description = "Missing 485 for " & HTMLEditFormat(getMissing485List.Pt_First & " " & getMissing485List.Pt_Last)>
            <cfif Len(Trim(getMissing485List.F26))>
                <cfset description = description & " - " & HTMLEditFormat(getMissing485List.F26)>
            </cfif>
            <cfif IsDate(getMissing485List.F177)>
                <cfset description = description & " (" & DateFormat(getMissing485List.F177, "mm/dd/yyyy")>
                <cfif IsDate(getMissing485List.F178)>
                    <cfset description = description & " - " & DateFormat(getMissing485List.F178, "mm/dd/yyyy")>
                </cfif>
                <cfset description = description & ")">
            </cfif>
            <cfset description = description & " - " & diffdays & " days elapsed">
            <cfif getMissing485List.pStatus EQ 1>
                <cfset description = description & " (inactive)">
            </cfif>
            <cfif Len(Trim(getMissing485List.eaRole))>
                <cfset description = description & " - Manager: " & HTMLEditFormat(getMissing485List.Emp_First & " " & getMissing485List.Emp_Last) & " (" & HTMLEditFormat(getMissing485List.eaRole) & ")">
            </cfif>

            <!--- Check if record already exists to prevent duplicates --->
            <cfquery name="checkExistingMissing485" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE  Patient_ID = <cfqueryparam value="#getMissing485List.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND Header = <cfqueryparam value="Missing 485" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND Description LIKE <cfqueryparam value="%#HTMLEditFormat(getMissing485List.Pt_First & " " & getMissing485List.Pt_Last)#%" cfsqltype="CF_SQL_VARCHAR">
                  AND status = 0
            </cfquery>

            <cfif checkExistingMissing485.totalrecordCount EQ 0>
                <cfquery name="insertMissing485" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#getMissing485List.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissing485List.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissing485List.Pt_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485List.Pt_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485List.Emp_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485List.Emp_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="Missing 485" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Process Get485EvalList results --->
    <cfloop query="getMissing485EvalList">
        <cfif getMissing485EvalList.new485_require EQ 0>
            <cfset diffdays = DateDiff("d", getMissing485EvalList.F177, Now())>
            <cfset description = "Missing 485 for " & HTMLEditFormat(getMissing485EvalList.Pt_First & " " & getMissing485EvalList.Pt_Last)>
            <cfif Len(Trim(getMissing485EvalList.F26))>
                <cfset description = description & " - " & HTMLEditFormat(getMissing485EvalList.F26)>
            </cfif>
            <cfif IsDate(getMissing485EvalList.F177)>
                <cfset description = description & " (" & DateFormat(getMissing485EvalList.F177, "mm/dd/yyyy")>
                <cfif IsDate(getMissing485EvalList.F178)>
                    <cfset description = description & " - " & DateFormat(getMissing485EvalList.F178, "mm/dd/yyyy")>
                </cfif>
                <cfset description = description & ")">
            </cfif>
            <cfset description = description & " - " & diffdays & " days elapsed">
            <cfif getMissing485EvalList.pStatus EQ 1>
                <cfset description = description & " (inactive)">
            </cfif>
            <cfif Len(Trim(getMissing485EvalList.eaRole))>
                <cfset description = description & " - Manager: " & HTMLEditFormat(getMissing485EvalList.Emp_First & " " & getMissing485EvalList.Emp_Last) & " (" & HTMLEditFormat(getMissing485EvalList.eaRole) & ")">
            </cfif>

            <!--- Check if record already exists to prevent duplicates --->
            <cfquery name="checkExistingMissing485Eval" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE   Patient_ID = <cfqueryparam value="#getMissing485EvalList.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND Header = <cfqueryparam value="Missing 485" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND Description LIKE <cfqueryparam value="%#HTMLEditFormat(getMissing485EvalList.Pt_First & " " & getMissing485EvalList.Pt_Last)#%" cfsqltype="CF_SQL_VARCHAR">
                  AND status = 0
            </cfquery>

            <cfif checkExistingMissing485Eval.totalrecordCount EQ 0>
                <cfquery name="insertMissing485Eval" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#getMissing485EvalList.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissing485EvalList.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissing485EvalList.Pt_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485EvalList.Pt_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485EvalList.Emp_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485EvalList.Emp_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="Missing 485" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Missing 485 - Find patients with missing 485 forms where employee r_485_Create = 1 --->
    <!--- Query 1: Get485List logic (Orphan_Field = 1, Med_Recon_Field = 1, Left(F26,1) IN ('1','4')) --->
    <cfquery name="getMissing485ListR1" datasource="#Application.DataSrc#">
        SELECT 
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            employee_auth.eaRole,
            employee_auth.r_485_Create,
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pPatients.Status as pStatus,
            pAssessments.Assmt_ID,
            pAssessments.F26,
            pAssessments.F177,
            pAssessments.F178,
            (SELECT count(*) 
             FROM #Request.prefix_db_agency#.pCMS4857 
             WHERE pCMS4857.Assmt_ID = pAssessments.Assmt_ID 
               AND Status = 0 
               AND Form_Type = 'Form 485') AS new485_require
        FROM #Request.prefix_db_agency#.pAssessments
        INNER JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID AND pPatients.Status IN (0,1,4)
        INNER JOIN #Request.prefix_db_agency#.pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID AND pAdmit.status = 0
        INNER JOIN #Request.prefix_db_agency#.pSchedules ON pSchedules.Assmt_ID = pAssessments.Assmt_ID AND pSchedules.status = 0
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pAdmit.Case_Manager
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pAssessments.status = 0
          AND pAssessments.F25 = 1
          AND Left(pAssessments.F26,1) IN ('1','4')
          AND pSchedules.Visit_Date > pAssessments.F177
          AND pAssessments.Orphan_Field IN (1)
          AND pPatients.Med_Recon_Field IN (1)
          AND pAdmit.Case_Manager > 0
          AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
          AND employee_auth.r_485_Create = 1
          AND pAdmit.Admit_ID NOT IN (
              SELECT pAssessments.Admit_ID 
              FROM #Request.prefix_db_agency#.pAssessments  
              WHERE (pAssessments.F26 LIKE '9%' OR pAssessments.F26 LIKE '7%' OR pAssessments.F26 LIKE '8%')
                AND pAssessments.Status = 0 
                AND F176 < <cfqueryparam value="#DateFormat(now(),'yyyy-mm-dd')#" cfsqltype="CF_SQL_DATE">
          )
        GROUP BY pAssessments.Assmt_ID
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <!--- Query 2: Get485EvalList logic (Orphan_Field NOT IN (1), Med_Recon_Field NOT IN (1), F26 like 'PT Adult%' etc.) --->
    <cfquery name="getMissing485EvalListR1" datasource="#Application.DataSrc#">
        SELECT 
            pEmployee.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            employee_auth.eaRole,
            employee_auth.r_485_Create,
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pPatients.Status as pStatus,
            pAssessments.Assmt_ID,
            pAssessments.F26,
            pAssessments.F177,
            pAssessments.F178,
            (SELECT count(*) 
             FROM #Request.prefix_db_agency#.pCMS4857  
             WHERE pCMS4857.Assmt_ID IN (
                 SELECT Assmt_ID 
                 FROM #Request.prefix_db_agency#.pAssessments pass 
                 WHERE pass.Admit_ID = pAdmit.Admit_ID 
                   AND pass.status = 0
             )
               AND Status = 0 
               AND Form_Type = 'Form 485') AS new485_require
        FROM #Request.prefix_db_agency#.pAssessments
        INNER JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID AND pPatients.Status IN (0,1,4)
        INNER JOIN #Request.prefix_db_agency#.pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID AND pAdmit.status = 0
        INNER JOIN #Request.prefix_db_agency#.pSchedules ON pSchedules.Assmt_ID = pAssessments.Assmt_ID AND pSchedules.status = 0
        INNER JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pAdmit.Case_Manager
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
        WHERE pAssessments.status = 0
          AND pAssessments.F25 = 1
          AND (F26 LIKE 'PT Adult%' OR F26 LIKE 'OT Adult%' OR F26 LIKE 'ST Adult%' OR F26 LIKE 'SN Adult%')
          AND pSchedules.Visit_Date > pAssessments.F177
          AND pAdmit.Admit_ID NOT IN (
              SELECT Admit_ID 
              FROM #Request.prefix_db_agency#.pAssessments 
              WHERE Status = 0 
                AND Left(F26,1) IN ('1','4')
          )
          AND pAssessments.Orphan_Field NOT IN (1)
          AND pPatients.Med_Recon_Field NOT IN (1)
          AND pAdmit.Case_Manager > 0
          AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
          AND pEmployee.Status = 0
          AND employee_auth.r_485_Create = 1
          AND pAdmit.Admit_ID NOT IN (
              SELECT pAssessments.Admit_ID 
              FROM #Request.prefix_db_agency#.pAssessments  
              WHERE (pAssessments.F26 LIKE '9%' OR pAssessments.F26 LIKE '7%' OR pAssessments.F26 LIKE '8%')
                AND pAssessments.Status = 0 
                AND F176 < <cfqueryparam value="#DateFormat(now(),'yyyy-mm-dd')#" cfsqltype="CF_SQL_DATE">
          )
        GROUP BY pAssessments.Assmt_ID
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <!--- Process Get485List results for r_485_Create = 1 --->
    <cfloop query="getMissing485ListR1">
        <cfif getMissing485ListR1.new485_require EQ 0>
            <cfset diffdays = DateDiff("d", getMissing485ListR1.F177, Now())>
            <cfset description = "Missing 485 for " & HTMLEditFormat(getMissing485ListR1.Pt_First & " " & getMissing485ListR1.Pt_Last)>
            <cfif Len(Trim(getMissing485ListR1.F26))>
                <cfset description = description & " - " & HTMLEditFormat(getMissing485ListR1.F26)>
            </cfif>
            <cfif IsDate(getMissing485ListR1.F177)>
                <cfset description = description & " (" & DateFormat(getMissing485ListR1.F177, "mm/dd/yyyy")>
                <cfif IsDate(getMissing485ListR1.F178)>
                    <cfset description = description & " - " & DateFormat(getMissing485ListR1.F178, "mm/dd/yyyy")>
                </cfif>
                <cfset description = description & ")">
            </cfif>
            <cfset description = description & " - " & diffdays & " days elapsed">
            <cfif getMissing485ListR1.pStatus EQ 1>
                <cfset description = description & " (inactive)">
            </cfif>
            <cfif Len(Trim(getMissing485ListR1.eaRole))>
                <cfset description = description & " - Manager: " & HTMLEditFormat(getMissing485ListR1.Emp_First & " " & getMissing485ListR1.Emp_Last) & " (" & HTMLEditFormat(getMissing485ListR1.eaRole) & ")">
            </cfif>

            <!--- Check if record already exists to prevent duplicates --->
            <cfquery name="checkExistingMissing485R1" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE  Patient_ID = <cfqueryparam value="#getMissing485ListR1.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND Header = <cfqueryparam value="Missing 485" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND Description LIKE <cfqueryparam value="%#HTMLEditFormat(getMissing485ListR1.Pt_First & " " & getMissing485ListR1.Pt_Last)#%" cfsqltype="CF_SQL_VARCHAR">
                  AND status = 0
            </cfquery>

            <cfif checkExistingMissing485R1.totalrecordCount EQ 0>
                <cfquery name="insertMissing485R1" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#getMissing485ListR1.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissing485ListR1.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissing485ListR1.Pt_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485ListR1.Pt_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485ListR1.Emp_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485ListR1.Emp_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="Missing 485" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Process Get485EvalList results for r_485_Create = 1 --->
    <cfloop query="getMissing485EvalListR1">
        <cfif getMissing485EvalListR1.new485_require EQ 0>
            <cfset diffdays = DateDiff("d", getMissing485EvalListR1.F177, Now())>
            <cfset description = "Missing 485 for " & HTMLEditFormat(getMissing485EvalListR1.Pt_First & " " & getMissing485EvalListR1.Pt_Last)>
            <cfif Len(Trim(getMissing485EvalListR1.F26))>
                <cfset description = description & " - " & HTMLEditFormat(getMissing485EvalListR1.F26)>
            </cfif>
            <cfif IsDate(getMissing485EvalListR1.F177)>
                <cfset description = description & " (" & DateFormat(getMissing485EvalListR1.F177, "mm/dd/yyyy")>
                <cfif IsDate(getMissing485EvalListR1.F178)>
                    <cfset description = description & " - " & DateFormat(getMissing485EvalListR1.F178, "mm/dd/yyyy")>
                </cfif>
                <cfset description = description & ")">
            </cfif>
            <cfset description = description & " - " & diffdays & " days elapsed">
            <cfif getMissing485EvalListR1.pStatus EQ 1>
                <cfset description = description & " (inactive)">
            </cfif>
            <cfif Len(Trim(getMissing485EvalListR1.eaRole))>
                <cfset description = description & " - Manager: " & HTMLEditFormat(getMissing485EvalListR1.Emp_First & " " & getMissing485EvalListR1.Emp_Last) & " (" & HTMLEditFormat(getMissing485EvalListR1.eaRole) & ")">
            </cfif>

            <!--- Check if record already exists to prevent duplicates --->
            <cfquery name="checkExistingMissing485EvalR1" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE  Patient_ID = <cfqueryparam value="#getMissing485EvalListR1.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND Header = <cfqueryparam value="Missing 485" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND Description LIKE <cfqueryparam value="%#HTMLEditFormat(getMissing485EvalListR1.Pt_First & " " & getMissing485EvalListR1.Pt_Last)#%" cfsqltype="CF_SQL_VARCHAR">
                  AND status = 0
            </cfquery>

            <cfif checkExistingMissing485EvalR1.totalrecordCount EQ 0>
                <cfquery name="insertMissing485EvalR1" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#getMissing485EvalListR1.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissing485EvalListR1.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissing485EvalListR1.Pt_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485EvalListR1.Pt_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485EvalListR1.Emp_First#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#getMissing485EvalListR1.Emp_Last#" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="Missing 485" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - Medication Updates Needed (matching incomplete_admissions.cfm) --->
    <!--- First get discharged admissions to exclude --->
    <cfquery name="getDischargedAdmissions" datasource="#Application.DataSrc#">
        SELECT pAssessments.Admit_ID 
        FROM #Request.prefix_db_agency#.pAssessments 
        JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID
        WHERE (pAssessments.F26 LIKE '9%' OR pAssessments.F26 LIKE '7%' OR pAssessments.F26 LIKE '8%')
        AND pAssessments.Status = 0 
        AND pAssessments.F25 = 1
        AND pAdmit.drafts = 0
        AND pAdmit.Status = 0
        GROUP BY pAdmit.Admit_ID
    </cfquery>
    <cfset admit_ids = ValueList(getDischargedAdmissions.Admit_ID)>

    <!--- Medication Updates Needed: Patients with M0% problems (medication-related) matching GetList structure --->
    <cfquery name="getMedicationUpdatesNeeded" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pAdmit.Case_Manager AS Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pPatients pPatients
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Patient_ID = pPatients.Patient_ID 
            AND (pAdmit.Status = 0 OR pAdmit.Status = 4)
            AND pAdmit.drafts = 1
            <cfif Len(admit_ids) GT 0>
                AND pAdmit.Admit_ID NOT IN (#admit_ids#)
            </cfif>
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee ON pAdmit.Case_Manager = pEmployee.Emp_ID
        WHERE pPatients.status = 0
        AND pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND (
            (pAdmit.Admit_ID IS NOT NULL)
            OR NOT EXISTS (
                SELECT 1 FROM #Request.prefix_db_agency#.pAdmit pa 
                WHERE pa.Patient_ID = pPatients.Patient_ID 
                AND (pa.Status = 0 OR pa.Status = 4)
            )
        )
        AND EXISTS (
            SELECT 1 FROM #Request.prefix_db_agency#.pProblem pProblem
            JOIN #Request.prefix_db_agency#.pAssessments pAssessments ON pAssessments.Assmt_ID = pProblem.Assmt_ID
            WHERE pProblem.Status = 0
            AND pProblem.M0_No LIKE 'M0%'
            AND pAssessments.Status = 0
            AND (
                (pAdmit.Admit_ID IS NOT NULL AND pAssessments.Admit_ID = pAdmit.Admit_ID)
                OR (pAdmit.Admit_ID IS NULL AND pAssessments.Patient_ID = pPatients.Patient_ID)
            )
        )
        GROUP BY pPatients.Patient_ID
    </cfquery>

    <cfloop query="getMedicationUpdatesNeeded">
        <cfquery name="checkExistingMedicationUpdates" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE Patient_ID = <cfqueryparam value="#getMedicationUpdatesNeeded.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
              AND Header = <cfqueryparam value="Medication Updates Needed" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingMedicationUpdates.totalrecordCount EQ 0>
            <cfset encPatientId = encrypt("#getMedicationUpdatesNeeded.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=incomplete_admissions">
            <cfset description = "Medication Updates Needed: <a href='" & linkUrl & "'>View incomplete admissions</a>">
            <cfset empIdValue = getMedicationUpdatesNeeded.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>
            <cfset ptLastNull = NOT Len(Trim(getMedicationUpdatesNeeded.Pt_Last))>
            <cfset ptFirstNull = NOT Len(Trim(getMedicationUpdatesNeeded.Pt_First))>
            <cfset empFirstNull = NOT Len(Trim(getMedicationUpdatesNeeded.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getMedicationUpdatesNeeded.Emp_Last))>
            <cfquery name="insertMedicationUpdatesNeeded" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getMedicationUpdatesNeeded.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getMedicationUpdatesNeeded.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#getMedicationUpdatesNeeded.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#getMedicationUpdatesNeeded.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#getMedicationUpdatesNeeded.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="Medication Updates Needed" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - Coding Updates Needed (matching incomplete_admissions.cfm CheckProblemPathway query) --->
    <!--- Coding Updates Needed: Patients with M1% problems (diagnosis) without pathway assignment (Path_ID IS NULL or 0) --->
    <cfquery name="getCodingUpdatesNeeded" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pAdmit.Case_Manager AS Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pPatients pPatients
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Patient_ID = pPatients.Patient_ID 
            AND (pAdmit.Status = 0 OR pAdmit.Status = 4)
            AND pAdmit.drafts = 1
            <cfif Len(admit_ids) GT 0>
                AND pAdmit.Admit_ID NOT IN (#admit_ids#)
            </cfif>
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee ON pAdmit.Case_Manager = pEmployee.Emp_ID
        WHERE pPatients.status = 0
        AND pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND (
            (pAdmit.Admit_ID IS NOT NULL)
            OR NOT EXISTS (
                SELECT 1 FROM #Request.prefix_db_agency#.pAdmit pa 
                WHERE pa.Patient_ID = pPatients.Patient_ID 
                AND (pa.Status = 0 OR pa.Status = 4)
            )
        )
        AND EXISTS (
            SELECT 1 FROM #Request.prefix_db_agency#.pProblem pProblem
            WHERE pProblem.Status = 0
            AND pProblem.M0_No LIKE 'M1%'
            AND (pProblem.Path_ID IS NULL OR pProblem.Path_ID = 0)
            AND (
                (pAdmit.Admit_ID IS NOT NULL AND EXISTS (
                    SELECT 1 FROM #Request.prefix_db_agency#.pAssessments pAssessments
                    WHERE pAssessments.Admit_ID = pAdmit.Admit_ID
                    AND pAssessments.Assmt_ID = pProblem.Assmt_ID
                    AND pAssessments.Status = 0
                ))
                OR (pAdmit.Admit_ID IS NULL AND EXISTS (
                    SELECT 1 FROM #Request.prefix_db_agency#.pAssessments pAssessments
                    WHERE pAssessments.Patient_ID = pPatients.Patient_ID
                    AND pAssessments.Assmt_ID = pProblem.Assmt_ID
                    AND pAssessments.Status = 0
                ))
            )
        )
        GROUP BY pPatients.Patient_ID
    </cfquery>

    <cfloop query="getCodingUpdatesNeeded">
        <cfquery name="checkExistingCodingUpdates" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE Patient_ID = <cfqueryparam value="#getCodingUpdatesNeeded.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
              AND Header = <cfqueryparam value="Coding Updates Needed" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingCodingUpdates.totalrecordCount EQ 0>
            <cfset encPatientId = encrypt("#getCodingUpdatesNeeded.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=incomplete_admissions">
            <cfset description = "Coding Updates Needed: <a href='" & linkUrl & "'>View incomplete admissions</a>">
            <cfset empIdValue = getCodingUpdatesNeeded.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>
            <cfset ptLastNull = NOT Len(Trim(getCodingUpdatesNeeded.Pt_Last))>
            <cfset ptFirstNull = NOT Len(Trim(getCodingUpdatesNeeded.Pt_First))>
            <cfset empFirstNull = NOT Len(Trim(getCodingUpdatesNeeded.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getCodingUpdatesNeeded.Emp_Last))>
            <cfquery name="insertCodingUpdatesNeeded" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getCodingUpdatesNeeded.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getCodingUpdatesNeeded.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#getCodingUpdatesNeeded.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#getCodingUpdatesNeeded.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#getCodingUpdatesNeeded.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="Coding Updates Needed" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - Disabled Goals Need Approval --->
    <!--- Disabled Goals Need Approval - matches disabled_goals.cfm GetA query exactly (single query) --->
    <cfquery name="getDisabledGoals" datasource="#Application.DataSrc#">
        SELECT pAssessments.Assmt_ID, pAssessments.Record_creation_Date, pAssessments.Assmt_ID,
            pAssessments.F27,
            pAssessments.Patient_ID, pAssessments.F25 AS admission_status,
            pAssessments.F26 AS Assessment_Reason_M0100, pAssessments.F177 AS Certification_Start, 
            pAssessments.F178 AS Certification_End, pAssessments.F176 AS Assessment_Completed_M0090,
            pAssessments.F197 AS Transmission_status, pAssessments.F176,
            pPatients.Pt_First, pPatients.Pt_Last, pPatients.Pt_Middle,
            pCareplan.Careplan_ID, pCareplan.Specifics, pCareplan.Description, pCareplan.Notes, pCareplan.Skill, 
            pCareplan.QA_approve as Goals_QA, pCareplan.Date_Create, pCareplan.Order_Date, pCareplan.QA_approve,
            pCareplan.Item_ID, pCareplan.Notes,
            pProblem.Description AS Problem_Description, pProblem.Answer, pProblem.Skill,
            pProblem.Assmt_ID, pProblem.Path_ID,
            pEmployee.Emp_First, pEmployee.Emp_Last, pPayer.Pay_Name  
        FROM #Request.prefix_db_agency#.pAssessments
        JOIN #Request.prefix_db_agency#.pPatients ON pAssessments.Patient_ID = pPatients.Patient_ID AND pPatients.Status IN (0,1,4)
        JOIN #Request.prefix_db_agency#.pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID AND pAdmit.Status = 0 
        JOIN #Request.prefix_db_agency#.pCareplan ON pCareplan.Assmt_ID = pAssessments.Assmt_ID AND pCareplan.Status = 1
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pPathway ON pPathway.Type = 'goal' AND pPathway.Item_ID = pCareplan.Item_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.pProblem ON pProblem.Assmt_ID = pAssessments.Assmt_ID AND pProblem.Status = 0
            AND pPathway.Pathway_ID = pProblem.Path_ID
        JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pCareplan.Created_By
        LEFT OUTER JOIN #Request.prefix_db_agency#.pPtPayer ON pPtPayer.Patient_ID = pPatients.Patient_ID AND pPtPayer.Status = 0
            AND pPtPayer.Payer_Responsibility = 'P - Primary'
        LEFT OUTER JOIN #Request.prefix_db_agency#.pPayer ON pPayer.Pay_ID = pPtPayer.Payer_ID
            AND pPayer.Status = 0
        WHERE pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pAssessments.Status = 0 
        AND pAssessments.F25 = 1
        AND pAssessments.F176 >= '2025-08-20'
        AND pCareplan.Type = 'goal'
        AND pCareplan.QA_approve IN (0) 
        GROUP BY pCareplan.Careplan_ID  
        ORDER BY pPatients.Pt_First ASC 
    </cfquery>

    <!--- Process disabled goals for Field employees (matching disabled_goals.cfm lines 44-49 filter) --->
    <cfloop query="getDisabledGoals">
        <!--- Check if this patient is scheduled to any Field employee --->
        <cfquery name="getFieldEmployeesForDisabledGoal" datasource="#Application.DataSrc#">
            SELECT DISTINCT
                pSchedules.Emp_ID,
                pEmployee.Emp_First,
                pEmployee.Emp_Last
            FROM #Request.prefix_db_agency#.pSchedules
            JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pSchedules.Assmt_ID
            JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
            INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
            WHERE pSchedules.Patient_ID = <cfqueryparam value="#getDisabledGoals.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
            AND pSchedules.Status = 0
            AND pAssessments.Status = 0
            AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
            AND pEmployee.Status = 0
            AND employee_auth.eaRole LIKE '%Field%'
            AND employee_auth.eaRole NOT LIKE '%Project Manager%'
            AND employee_auth.eaRole NOT LIKE '%Quality%'
        </cfquery>

        <cfloop query="getFieldEmployeesForDisabledGoal">
            <cfset encPatientId = encrypt("#getDisabledGoals.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset encAssmtId = encrypt("#getDisabledGoals.Assmt_ID#", encryptKey, "AES", "Hex")>
            <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=disabled_goals">
            <cfset description = "Disabled Goals Need Approval: <a href='" & linkUrl & "'>View disabled goals</a>">
            <cfset ptLastNull = NOT Len(Trim(getDisabledGoals.Pt_Last))>
            <cfset ptFirstNull = NOT Len(Trim(getDisabledGoals.Pt_First))>
            <cfset empFirstNull = NOT Len(Trim(getFieldEmployeesForDisabledGoal.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getFieldEmployeesForDisabledGoal.Emp_Last))>
            <cfset assmtIdValue = getDisabledGoals.Assmt_ID>
            <cfset assmtIdNull = NOT IsNumeric(assmtIdValue)>
            <cfset empIdValue = getFieldEmployeesForDisabledGoal.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>

            <cfquery name="checkExistingDisabledGoalsField" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE Assmt_ID = <cfqueryparam value="#getDisabledGoals.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND Patient_ID = <cfqueryparam value="#getDisabledGoals.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                   AND Header = <cfqueryparam value="Disabled Goals Need Approval" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND status = 0
            </cfquery>

            <cfif checkExistingDisabledGoalsField.totalrecordCount EQ 0>
                <cfquery name="insertDisabledGoalsField" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#assmtIdValue#" cfsqltype="CF_SQL_INTEGER" null="#assmtIdNull#">,
                        <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getDisabledGoals.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getDisabledGoals.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                        <cfqueryparam value="#getDisabledGoals.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                        <cfqueryparam value="#getFieldEmployeesForDisabledGoal.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                        <cfqueryparam value="#getFieldEmployeesForDisabledGoal.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                        <cfqueryparam value="Disabled Goals Need Approval" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfloop>
    </cfloop>

    <!--- Process disabled goals for QA/PM employees (all records) --->
    <cfloop query="getDisabledGoals">
        <!--- Get all QA/PM employees for this agency --->
        <cfquery name="getQAEmployeesForDisabledGoal" datasource="#Application.DataSrc#">
            SELECT DISTINCT
                pEmployee.Emp_ID,
                pEmployee.Emp_First,
                pEmployee.Emp_Last
            FROM #Request.prefix_db_lookup#.pEmployee pEmployee
            INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
            WHERE pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
              AND pEmployee.Status = 0
              AND (employee_auth.eaRole LIKE '%Project Manager%' OR employee_auth.eaRole LIKE '%Clinical Quality Assurance%')
        </cfquery>

        <cfloop query="getQAEmployeesForDisabledGoal">
            <cfset encPatientId = encrypt("#getDisabledGoals.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset encAssmtId = encrypt("#getDisabledGoals.Assmt_ID#", encryptKey, "AES", "Hex")>
            <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=disabled_goals">
            <cfset description = "Disabled Goals Need Approval: <a href='" & linkUrl & "'>View disabled goals</a>">
            <cfset ptLastNull = NOT Len(Trim(getDisabledGoals.Pt_Last))>
            <cfset ptFirstNull = NOT Len(Trim(getDisabledGoals.Pt_First))>
            <cfset empFirstNull = NOT Len(Trim(getQAEmployeesForDisabledGoal.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getQAEmployeesForDisabledGoal.Emp_Last))>
            <cfset assmtIdValue = getDisabledGoals.Assmt_ID>
            <cfset assmtIdNull = NOT IsNumeric(assmtIdValue)>
            <cfset empIdValue = getQAEmployeesForDisabledGoal.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>

            <cfquery name="checkExistingDisabledGoalsQA" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE Assmt_ID = <cfqueryparam value="#getDisabledGoals.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND Patient_ID = <cfqueryparam value="#getDisabledGoals.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                   AND Header = <cfqueryparam value="Disabled Goals Need Approval" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND status = 0
            </cfquery>

            <cfif checkExistingDisabledGoalsQA.totalrecordCount EQ 0>
                <cfquery name="insertDisabledGoalsQA" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#assmtIdValue#" cfsqltype="CF_SQL_INTEGER" null="#assmtIdNull#">,
                        <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getDisabledGoals.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getDisabledGoals.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                        <cfqueryparam value="#getDisabledGoals.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                        <cfqueryparam value="#getQAEmployeesForDisabledGoal.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                        <cfqueryparam value="#getQAEmployeesForDisabledGoal.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                        <cfqueryparam value="Disabled Goals Need Approval" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfloop>
    </cfloop>

    <!--- Dashboard Reports - Discharges to Review - matches discharge_approval.cfm Getdischarges query with pEmployee join --->
    <cfquery name="getDischargesToReview" datasource="#Application.DataSrc#">
        SELECT pAssessments.Assmt_ID, pAssessments.Record_creation_Date, pAssessments.Assmt_ID, pAssessments.F27, pAssessments.QA_Count,
            pAssessments.Patient_ID, pAssessments.F25 AS admission_status, pAssessments.F26 AS Assessment_Reason_M0100, pAssessments.F177 AS Certification_Start, 
            pAssessments.F178 AS Certification_End, pAssessments.F176 AS Assessment_Completed_M0090,
            pAssessments.F197 AS Transmission_status,
            (SELECT count(*) FROM #Request.prefix_db_agency#.pAssessments pass
            WHERE pass.Admit_ID = pAssessments.Admit_ID AND pass.status = 0 AND pass.F25 = 1
            AND LEFT(pass.F26,1) IN (1,9) AND pass.QA_Count != 1) AS completed_oasis,
            (SELECT count(*) FROM #Request.prefix_db_agency#.pAssessments pass
            WHERE pass.Admit_ID = pAssessments.Admit_ID AND pass.status = 0 AND pass.F25 = 1
            AND LEFT(pass.F26,1) IN (9) AND pass.QA_Count != 1 AND pass.F197 IS NULL) AS dicharge_transmitted,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F147 ELSE pAssessments.F118 END AS M1400,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F74 ELSE pAssessments.F77 END AS M1800,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F75 ELSE pAssessments.F78 END AS M1810,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F76 ELSE pAssessments.F79 END AS M1820,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F77 ELSE pAssessments.F80 END AS M1830,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F78 ELSE pAssessments.F81 END AS M1840,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F79 ELSE pAssessments.F82 END AS M1845,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F80 ELSE pAssessments.F83 END AS M1850,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F81 ELSE pAssessments.F84 END AS M1860,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F156 ELSE pAssessments.F163 END AS M1870,
            CASE WHEN LEFT(pAssessments.F26,1) = 1 THEN pAssessments.F204 ELSE pAssessments.F135 END AS M2200,
            pPatients.Pt_First, pPatients.Pt_Last, pPatients.Pt_Middle, pAssessments.*,
            pEmployee.Emp_ID, pEmployee.Emp_First, pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pAssessments
        JOIN #Request.prefix_db_agency#.pPatients ON pAssessments.Patient_ID = pPatients.Patient_ID AND pPatients.Status IN (0,1)
        JOIN #Request.prefix_db_agency#.pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID AND pAdmit.Status = 0 
        JOIN #Request.prefix_db_lookup#.pEmployee ON pAdmit.Case_Manager = pEmployee.Emp_ID
        WHERE pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pAssessments.Status = 0 
        AND pAssessments.F25 = 1
        AND LEFT(pAssessments.F26,1) IN (1,9)
        AND pAssessments.QA_Count != 1
        AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pEmployee.Status = 0
        GROUP BY pAssessments.Assmt_ID  
        ORDER BY pPatients.Pt_First, pPatients.Patient_ID, Assessment_Reason_M0100 ASC 
    </cfquery>

    <!--- Process discharges to review (matching discharge_approval.cfm - filter: completed_oasis GTE 2 AND dicharge_transmitted EQ 1) --->
    <cfloop query="getDischargesToReview">
        <!--- Filter: completed_oasis GTE 2 AND dicharge_transmitted EQ 1 (matching discharge_approval.cfm output filter) --->
        <cfif getDischargesToReview.completed_oasis GTE 2 AND getDischargesToReview.dicharge_transmitted EQ 1>
            <cfquery name="checkExistingDischargesToReview" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE Assmt_ID = <cfqueryparam value="#getDischargesToReview.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">
                   AND Header = <cfqueryparam value="Discharges to Review" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND status = 0
            </cfquery>

            <cfif checkExistingDischargesToReview.totalrecordCount EQ 0>
                <cfset encPatientId = encrypt("#getDischargesToReview.Patient_ID#", encryptKey, "AES", "Hex")>
                <cfset encAssmtId = encrypt("#getDischargesToReview.Assmt_ID#", encryptKey, "AES", "Hex")>
                <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=discharge_approval">
                <cfset description = "Discharges to Review: <a href='" & linkUrl & "'>View discharge approval</a>">
                <cfset ptLastNull = NOT Len(Trim(getDischargesToReview.Pt_Last))>
                <cfset ptFirstNull = NOT Len(Trim(getDischargesToReview.Pt_First))>
                <cfset empFirstNull = NOT Len(Trim(getDischargesToReview.Emp_First))>
                <cfset empLastNull = NOT Len(Trim(getDischargesToReview.Emp_Last))>
                <cfset assmtIdNull = NOT IsNumeric(getDischargesToReview.Assmt_ID)>
                <cfquery name="insertDischargesToReview" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#getDischargesToReview.Assmt_ID#" cfsqltype="CF_SQL_INTEGER" null="#assmtIdNull#">,
                        <cfqueryparam value="#getDischargesToReview.Emp_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getDischargesToReview.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getDischargesToReview.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                        <cfqueryparam value="#getDischargesToReview.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                        <cfqueryparam value="#getDischargesToReview.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                        <cfqueryparam value="#getDischargesToReview.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                        <cfqueryparam value="Discharges to Review" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - Missing Eligibility (matching missing_eligibility.cfm exactly) --->
    <cfquery name="getMissingEligibility" datasource="#Application.DataSrc#">
        SELECT 
            Eligibility.Elig_ID,
            pPayer.Pay_Name,
            Eligibility.Start_Date,
            pPatients.Patient_ID,
            pPatients.Pt_Last AS PatientLast,
            pPatients.Pt_First AS PatientFirst,
            pAdmit.Case_Manager AS Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last,
            (SELECT COUNT(*) 
             FROM #Request.prefix_db_agency#.Eligibility 
             WHERE PtPayer_ID = pPtPayer.PtPayer_ID 
               AND status = 0 
               AND (Expiration_Date >= NOW() OR (Expiration_Date IS NULL AND Start_Date IS NOT NULL))) AS expire_Count
        FROM #Request.prefix_db_agency#.pPtPayer pPtPayer
        JOIN #Request.prefix_db_agency#.pPayer pPayer ON pPtPayer.Payer_ID = pPayer.Pay_ID 
            AND pPayer.Status = 0 
            AND pPayer.Eligibility = 1
        JOIN #Request.prefix_db_agency#.pPatients pPatients ON pPtPayer.Patient_ID = pPatients.Patient_ID 
            AND pPatients.Status < 2
        LEFT OUTER JOIN #Request.prefix_db_agency#.Eligibility ON Eligibility.PtPayer_ID = pPtPayer.PtPayer_ID 
            AND Eligibility.status = 0
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Patient_ID = pPatients.Patient_ID AND pAdmit.Status = 0
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee ON pAdmit.Case_Manager = pEmployee.Emp_ID
        WHERE pPtPayer.status = 0
        AND (Eligibility.Elig_ID IS NULL OR Eligibility.Start_Date IS NULL)
        AND (Eligibility.Notes != 'Automated eligibility' OR Eligibility.Notes IS NULL)
        AND pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC, Eligibility.Elig_ID DESC
    </cfquery>

    <!--- Process results - match filtering logic from missing_eligibility.cfm line 74 --->
    <cfloop query="getMissingEligibility" group="Patient_ID">
        <!--- Match filtering logic from missing_eligibility.cfm line 74: only show if expire_Count EQ 0 OR Elig_ID EQ '' --->
        <cfif (getMissingEligibility.expire_Count EQ 0 OR getMissingEligibility.Elig_ID EQ "" OR NOT Len(Trim(getMissingEligibility.Elig_ID)))>
            <cfquery name="checkExistingMissingEligibility" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE Patient_ID = <cfqueryparam value="#getMissingEligibility.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND Header = <cfqueryparam value="Missing Eligibility" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND status = 0
            </cfquery>

            <cfif checkExistingMissingEligibility.totalrecordCount EQ 0>
                <cfset encPatientId = encrypt("#getMissingEligibility.Patient_ID#", encryptKey, "AES", "Hex")>
                <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=missing_eligibility">
                <cfset description = "Missing Eligibility: <a href='" & linkUrl & "'>View missing eligibility</a>">
                <cfset empIdValue = getMissingEligibility.Emp_ID>
                <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                    <cfset empIdValue = 0>
                </cfif>
                <cfset ptLastNull = NOT Len(Trim(getMissingEligibility.PatientLast))>
                <cfset ptFirstNull = NOT Len(Trim(getMissingEligibility.PatientFirst))>
                <cfset empFirstNull = NOT Len(Trim(getMissingEligibility.Emp_First))>
                <cfset empLastNull = NOT Len(Trim(getMissingEligibility.Emp_Last))>
                <cfquery name="insertMissingEligibility" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissingEligibility.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getMissingEligibility.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                        <cfqueryparam value="#getMissingEligibility.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                        <cfqueryparam value="#getMissingEligibility.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                        <cfqueryparam value="#getMissingEligibility.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                        <cfqueryparam value="Missing Eligibility" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - Pending Admissions (matching incomplete_admissions.cfm GetList query exactly) --->
    <cfquery name="getPendingAdmissions" datasource="#Application.DataSrc#">
        SELECT 
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pAdmit.Case_Manager AS Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pPatients pPatients
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Patient_ID = pPatients.Patient_ID 
            AND (pAdmit.Status = 0 OR pAdmit.Status = 4)
            AND pAdmit.drafts = 1
            <cfif Len(admit_ids) GT 0>
                AND pAdmit.Admit_ID NOT IN (#admit_ids#)
            </cfif>
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee ON pAdmit.Case_Manager = pEmployee.Emp_ID
        WHERE pPatients.status = 0
        AND pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND (
            (pAdmit.Admit_ID IS NOT NULL)
            OR NOT EXISTS (
                SELECT 1 FROM #Request.prefix_db_agency#.pAdmit pa 
                WHERE pa.Patient_ID = pPatients.Patient_ID 
                AND (pa.Status = 0 OR pa.Status = 4)
            )
        )
        GROUP BY pPatients.Patient_ID
        ORDER BY pPatients.Patient_ID ASC, pAdmit.M0030_START_CARE_DT DESC
    </cfquery>

    <cfloop query="getPendingAdmissions">
        <cfquery name="checkExistingPendingAdmissions" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE Patient_ID = <cfqueryparam value="#getPendingAdmissions.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
              AND Header = <cfqueryparam value="Pending Admissions" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingPendingAdmissions.totalrecordCount EQ 0>
            <cfset encPatientId = encrypt("#getPendingAdmissions.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=incomplete_admissions">
            <cfset description = "Pending Admissions: <a href='" & linkUrl & "'>View incomplete admissions</a>">
            <cfset empIdValue = getPendingAdmissions.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>
            <cfset ptLastNull = NOT Len(Trim(getPendingAdmissions.Pt_Last))>
            <cfset ptFirstNull = NOT Len(Trim(getPendingAdmissions.Pt_First))>
            <cfset empFirstNull = NOT Len(Trim(getPendingAdmissions.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getPendingAdmissions.Emp_Last))>
            <cfquery name="insertPendingAdmissions" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getPendingAdmissions.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getPendingAdmissions.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#getPendingAdmissions.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#getPendingAdmissions.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#getPendingAdmissions.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="Pending Admissions" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- New Orders Need 487 - matches 487_requirereport.cfm Get487List query exactly (single query) --->
    <cfquery name="getNewOrdersNeed487" datasource="#Application.DataSrc#">
        SELECT * FROM #Request.prefix_db_agency#.p487require	
        WHERE new485_require > 0
        AND (problemcms_Id > 0 OR ptmedscms_Id > 0 OR careplancms_Id > 0 OR authcms_id > 0) 
        GROUP BY Patient_ID
    </cfquery>

    <!--- Process new orders need 487 for Field employees (matching 487_requirereport.cfm lines 100-105 filter) --->
    <cfloop query="getNewOrdersNeed487">
        <!--- Only process if new485_require NEQ 0 (matching 487_requirereport.cfm output filter line 158) --->
        <cfif getNewOrdersNeed487.new485_require NEQ 0>
            <!--- Check if this patient is scheduled to any Field employee --->
            <cfquery name="getFieldEmployeesForNewOrders487" datasource="#Application.DataSrc#">
                SELECT DISTINCT
                    pSchedules.Emp_ID,
                    pEmployee.Emp_First,
                    pEmployee.Emp_Last
                FROM #Request.prefix_db_agency#.pSchedules
                JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pSchedules.Assmt_ID
                JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
                INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
                WHERE pSchedules.Patient_ID = <cfqueryparam value="#getNewOrdersNeed487.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                AND pSchedules.Status = 0
                AND pAssessments.Status = 0
                AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
                AND pEmployee.Status = 0
                AND employee_auth.eaRole LIKE '%Field%'
                AND employee_auth.eaRole NOT LIKE '%Project Manager%'
                AND employee_auth.eaRole NOT LIKE '%Quality%'
            </cfquery>

            <cfloop query="getFieldEmployeesForNewOrders487">
                <cfquery name="checkExistingNewOrders487Field" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Patient_ID = <cfqueryparam value="#getNewOrdersNeed487.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                      AND Header = <cfqueryparam value="New Orders Need 487" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND status = 0
                </cfquery>

                <cfif checkExistingNewOrders487Field.totalrecordCount EQ 0>
                    <cfset encPatientId = encrypt("#getNewOrdersNeed487.Patient_ID#", encryptKey, "AES", "Hex")>
                    <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=487_requirereport">
                    <cfset description = "New Orders Need 487: <a href='" & linkUrl & "'>View 487 require report</a>">
                    <cfset ptLastNull = NOT Len(Trim(getNewOrdersNeed487.PatientLast))>
                    <cfset ptFirstNull = NOT Len(Trim(getNewOrdersNeed487.PatientFirst))>
                    <cfset empFirstNull = NOT Len(Trim(getFieldEmployeesForNewOrders487.Emp_First))>
                    <cfset empLastNull = NOT Len(Trim(getFieldEmployeesForNewOrders487.Emp_Last))>
                    <cfset empIdValue = getFieldEmployeesForNewOrders487.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfquery name="insertNewOrdersNeed487Field" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getNewOrdersNeed487.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getNewOrdersNeed487.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getNewOrdersNeed487.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#getFieldEmployeesForNewOrders487.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#getFieldEmployeesForNewOrders487.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="New Orders Need 487" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfloop>
        </cfif>
    </cfloop>

    <!--- Process new orders need 487 for QA/PM employees (all records) --->
    <cfloop query="getNewOrdersNeed487">
        <!--- Only process if new485_require NEQ 0 (matching 487_requirereport.cfm output filter line 158) --->
        <cfif getNewOrdersNeed487.new485_require NEQ 0>
            <!--- Get all QA/PM employees for this agency --->
            <cfquery name="getQAEmployeesForNewOrders487" datasource="#Application.DataSrc#">
                SELECT DISTINCT
                    pEmployee.Emp_ID,
                    pEmployee.Emp_First,
                    pEmployee.Emp_Last
                FROM #Request.prefix_db_lookup#.pEmployee pEmployee
                INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
                WHERE pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND pEmployee.Status = 0
                  AND (employee_auth.eaRole LIKE '%Project Manager%' OR employee_auth.eaRole LIKE '%Clinical Quality Assurance%')
            </cfquery>

            <cfloop query="getQAEmployeesForNewOrders487">
                <cfquery name="checkExistingNewOrders487QA" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Patient_ID = <cfqueryparam value="#getNewOrdersNeed487.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                       AND Header = <cfqueryparam value="New Orders Need 487" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND status = 0
                </cfquery>

                <cfif checkExistingNewOrders487QA.totalrecordCount EQ 0>
                    <cfset encPatientId = encrypt("#getNewOrdersNeed487.Patient_ID#", encryptKey, "AES", "Hex")>
                    <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=487_requirereport">
                    <cfset description = "New Orders Need 487: <a href='" & linkUrl & "'>View 487 require report</a>">
                    <cfset ptLastNull = NOT Len(Trim(getNewOrdersNeed487.PatientLast))>
                    <cfset ptFirstNull = NOT Len(Trim(getNewOrdersNeed487.PatientFirst))>
                    <cfset empFirstNull = NOT Len(Trim(getQAEmployeesForNewOrders487.Emp_First))>
                    <cfset empLastNull = NOT Len(Trim(getQAEmployeesForNewOrders487.Emp_Last))>
                    <cfset empIdValue = getQAEmployeesForNewOrders487.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfquery name="insertNewOrdersNeed487QA" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getNewOrdersNeed487.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getNewOrdersNeed487.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getNewOrdersNeed487.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#getQAEmployeesForNewOrders487.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#getQAEmployeesForNewOrders487.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="New Orders Need 487" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfloop>
        </cfif>
    </cfloop>

    <!--- Un-Sent Orders - matches unsent_orders.cfm Visits query with pEmployee join through schedules --->
    <cfquery name="getUnsentOrders" datasource="#Application.DataSrc#">
        SELECT pPatients.Patient_ID, pPatients.Status, pPatients.Pt_Last AS PatientLast, 
            pPatients.Pt_First AS PatientFirst, pCMS4857.Order_ID, pCMS4857.Form_Type, 
            pCMS4857.Date_Sent, pCMS4857.Certification_From, 
            pCMS4857.Certification_To, pCMS4857.MD_Digital_Signature, 
            pCMS4857.Date_Create, DATEDIFF(NOW(), pCMS4857.Date_Create) AS age,
            pCMS4857.Order_description, pCMS4857.Form_Status,
            pPhysicians.Phys_ID, pEmployee.Emp_Last, pEmployee.Emp_First, pEmployee.Emp_ID, pPhysicians.Phys_Last, pPhysicians.Phys_First, 
            pAssessments.Status
        FROM #Request.prefix_db_agency#.pCMS4857
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAssessments ON pCMS4857.Assmt_ID = pAssessments.Assmt_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.pPatients ON pAssessments.Patient_ID = pPatients.Patient_ID 
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pPhysicians ON pCMS4857.Render_Phys_ID = pPhysicians.Phys_ID 
        JOIN #Request.prefix_db_agency#.pSchedules ON pSchedules.Patient_ID = pPatients.Patient_ID 
            AND pSchedules.Assmt_ID = pAssessments.Assmt_ID
            AND pSchedules.Status = 0
        JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
        WHERE pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pCMS4857.Status = 0
        AND (pCMS4857.Form_Status LIKE '%send%')
        AND pPatients.Status < 2
        AND pAssessments.Status = 0
        AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pEmployee.Status = 0
        GROUP BY pCMS4857.Order_ID, pSchedules.Emp_ID
        ORDER BY pPatients.Pt_Last, pCMS4857.Certification_To
    </cfquery>

    <cfloop query="getUnsentOrders">
        <!--- Filter out orders that are already sent (matching unsent_orders.cfm output filter) --->
        <cfif getUnsentOrders.Form_Status NEQ 'Sent via Fax' 
            AND getUnsentOrders.Form_Status NEQ 'Sent for E-Signing' 
            AND getUnsentOrders.Form_Status NEQ 'E-Signed and Received' 
            AND getUnsentOrders.Form_Status NEQ 'Signed & Received via Fax'>
            
            <cfquery name="checkExistingUnsentOrders" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE Patient_ID = <cfqueryparam value="#getUnsentOrders.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                   AND Header = <cfqueryparam value="Un-Sent Orders" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND status = 0
            </cfquery>

            <cfif checkExistingUnsentOrders.totalrecordCount EQ 0>
                <cfset encPatientId = encrypt("#getUnsentOrders.Patient_ID#", encryptKey, "AES", "Hex")>
                <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders">
                <cfset description = "Un-Sent Orders: <a href='" & linkUrl & "'>View unsent orders</a>">
                <cfset ptLastNull = NOT Len(Trim(getUnsentOrders.PatientLast))>
                <cfset ptFirstNull = NOT Len(Trim(getUnsentOrders.PatientFirst))>
                <cfset empFirstNull = NOT Len(Trim(getUnsentOrders.Emp_First))>
                <cfset empLastNull = NOT Len(Trim(getUnsentOrders.Emp_Last))>
                <cfset empIdValue = getUnsentOrders.Emp_ID>
                <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                    <cfset empIdValue = 0>
                </cfif>
                <cfquery name="insertUnsentOrders" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getUnsentOrders.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getUnsentOrders.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                        <cfqueryparam value="#getUnsentOrders.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                        <cfqueryparam value="#getUnsentOrders.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                        <cfqueryparam value="#getUnsentOrders.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                        <cfqueryparam value="Un-Sent Orders" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Un-Signed Orders - matches unsignedorders.cfm Visits query exactly --->
    <!--- For Field employees: join through schedules (matching unsignedorders.cfm lines 45-50) --->
    <cfquery name="getUnsignedOrdersForField" datasource="#Application.DataSrc#">
        SELECT pPatients.Patient_ID, pPatients.Status, pPatients.Pt_Last AS PatientLast, 
            pPatients.Pt_First AS PatientFirst, pCMS4857.Order_ID, pCMS4857.Form_Type, 
            pCMS4857.Date_Sent, pCMS4857.Certification_From, 
            pCMS4857.Certification_To, pCMS4857.MD_Digital_Signature, 
            pCMS4857.Date_Create, DATEDIFF(NOW(), pCMS4857.Date_Sent) AS age,
            pCMS4857.Order_description, pCMS4857.Form_Status,
            pPhysicians.Phys_ID, pPhysicianEmp.Emp_Last, pPhysicianEmp.Emp_First,
            pScheduleEmp.Emp_ID, pScheduleEmp.Emp_First AS Emp_First, pScheduleEmp.Emp_Last AS Emp_Last,
            pAssessments.Status
        FROM #Request.prefix_db_agency#.pCMS4857
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAssessments ON pCMS4857.Assmt_ID = pAssessments.Assmt_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.pPatients ON pAssessments.Patient_ID = pPatients.Patient_ID 
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pPhysicians ON pCMS4857.Render_Phys_ID = pPhysicians.Phys_ID 
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee pPhysicianEmp ON pPhysicians.Emp_ID = pPhysicianEmp.Emp_ID
        JOIN #Request.prefix_db_agency#.pSchedules ON pSchedules.Patient_ID = pPatients.Patient_ID 
            AND pSchedules.Assmt_ID = pAssessments.Assmt_ID
            AND pSchedules.Status = 0
        JOIN #Request.prefix_db_lookup#.pEmployee pScheduleEmp ON pScheduleEmp.Emp_ID = pSchedules.Emp_ID
        INNER JOIN #Request.prefix_db_agency#.employee_auth ON pScheduleEmp.Emp_ID = employee_auth.eaID
        WHERE pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND (pCMS4857.Form_Status <> 'Signed and Received')
        AND pCMS4857.Form_Status <> 'Printed Only'
        AND pCMS4857.Form_Status <> 'E-Signed and Received'
        AND pCMS4857.Form_Status <> 'Signed & Received via Fax'
        AND pCMS4857.Status = 0
        AND pPatients.Status < 2
        AND pAssessments.Status = 0
        AND pScheduleEmp.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pScheduleEmp.Status = 0
        AND employee_auth.eaRole LIKE '%Field%'
        AND employee_auth.eaRole NOT LIKE '%Project Manager%'
        AND employee_auth.eaRole NOT LIKE '%Quality%'
        GROUP BY pCMS4857.Order_ID, pSchedules.Emp_ID
        ORDER BY pPatients.Pt_Last, pCMS4857.Certification_To
    </cfquery>

    <!--- Un-Signed Orders (QA/PM) - matches unsignedorders.cfm Visits query (all orders, no schedule filter) --->
    <cfquery name="getUnsignedOrdersForQA" datasource="#Application.DataSrc#">
        SELECT pPatients.Patient_ID, pPatients.Status, pPatients.Pt_Last AS PatientLast, 
            pPatients.Pt_First AS PatientFirst, pCMS4857.Order_ID, pCMS4857.Form_Type, 
            pCMS4857.Date_Sent, pCMS4857.Certification_From, 
            pCMS4857.Certification_To, pCMS4857.MD_Digital_Signature, 
            pCMS4857.Date_Create, DATEDIFF(NOW(), pCMS4857.Date_Sent) AS age,
            pCMS4857.Order_description, pCMS4857.Form_Status,
            pPhysicians.Phys_ID, pPhysicianEmp.Emp_Last, pPhysicianEmp.Emp_First,
            pQAEmployee.Emp_ID, pQAEmployee.Emp_First AS Emp_First, pQAEmployee.Emp_Last AS Emp_Last,
            pAssessments.Status
        FROM #Request.prefix_db_agency#.pCMS4857
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAssessments ON pCMS4857.Assmt_ID = pAssessments.Assmt_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.pPatients ON pAssessments.Patient_ID = pPatients.Patient_ID 
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pPhysicians ON pCMS4857.Render_Phys_ID = pPhysicians.Phys_ID 
        LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee pPhysicianEmp ON pPhysicians.Emp_ID = pPhysicianEmp.Emp_ID
        CROSS JOIN (
            SELECT DISTINCT
                pEmployee.Emp_ID,
                pEmployee.Emp_First,
                pEmployee.Emp_Last
            FROM #Request.prefix_db_lookup#.pEmployee pEmployee
            INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
            WHERE pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
              AND pEmployee.Status = 0
              AND (employee_auth.eaRole LIKE '%Project Manager%' OR employee_auth.eaRole LIKE '%Clinical Quality Assurance%')
        ) AS pQAEmployee
        WHERE pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND (pCMS4857.Form_Status <> 'Signed and Received')
        AND pCMS4857.Form_Status <> 'Printed Only'
        AND pCMS4857.Form_Status <> 'E-Signed and Received'
        AND pCMS4857.Form_Status <> 'Signed & Received via Fax'
        AND pCMS4857.Status = 0
        AND pPatients.Status < 2
        AND pAssessments.Status = 0
        GROUP BY pCMS4857.Order_ID, pQAEmployee.Emp_ID
        ORDER BY pPatients.Pt_Last, pCMS4857.Certification_To
    </cfquery>

    <!--- Process unsigned orders for Field employees --->
    <cfloop query="getUnsignedOrdersForField">
        <cfquery name="checkExistingUnsignedOrders" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE Patient_ID = <cfqueryparam value="#getUnsignedOrdersForField.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
               AND Header = <cfqueryparam value="Un-Signed Orders" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingUnsignedOrders.totalrecordCount EQ 0>
            <cfset encPatientId = encrypt("#getUnsignedOrdersForField.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=unsignedorders">
            <cfset description = "Un-Signed Orders: <a href='" & linkUrl & "'>View unsigned orders</a>">
            <cfset empIdValue = getUnsignedOrdersForField.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>
            <cfset ptLastNull = NOT Len(Trim(getUnsignedOrdersForField.PatientLast))>
            <cfset ptFirstNull = NOT Len(Trim(getUnsignedOrdersForField.PatientFirst))>
            <cfset empFirstNull = NOT Len(Trim(getUnsignedOrdersForField.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getUnsignedOrdersForField.Emp_Last))>
            <cfquery name="insertUnsignedOrders" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getUnsignedOrdersForField.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getUnsignedOrdersForField.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#getUnsignedOrdersForField.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#getUnsignedOrdersForField.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#getUnsignedOrdersForField.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="Un-Signed Orders" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Process unsigned orders for QA/PM employees --->
    <cfloop query="getUnsignedOrdersForQA">
        <cfquery name="checkExistingUnsignedOrdersQA" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE Patient_ID = <cfqueryparam value="#getUnsignedOrdersForQA.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
               AND Header = <cfqueryparam value="Un-Signed Orders" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingUnsignedOrdersQA.totalrecordCount EQ 0>
            <cfset encPatientId = encrypt("#getUnsignedOrdersForQA.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=unsignedorders">
            <cfset description = "Un-Signed Orders: <a href='" & linkUrl & "'>View unsigned orders</a>">
            <cfset empIdValue = getUnsignedOrdersForQA.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>
            <cfset ptLastNull = NOT Len(Trim(getUnsignedOrdersForQA.PatientLast))>
            <cfset ptFirstNull = NOT Len(Trim(getUnsignedOrdersForQA.PatientFirst))>
            <cfset empFirstNull = NOT Len(Trim(getUnsignedOrdersForQA.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getUnsignedOrdersForQA.Emp_Last))>
            <cfquery name="insertUnsignedOrdersQA" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getUnsignedOrdersForQA.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getUnsignedOrdersForQA.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#getUnsignedOrdersForQA.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#getUnsignedOrdersForQA.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#getUnsignedOrdersForQA.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="Un-Signed Orders" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - Expiring Eligibility - matches expiring_eligibility.cfm GetList query exactly --->
    <cfquery name="getExpiringEligibility" datasource="#Application.DataSrc#">
        SELECT DATE_ADD(Eligibility.Expiration_Date, INTERVAL 10 DAY),
        DATEDIFF(Eligibility.Expiration_Date, now()) AS diff_days,
        pPatients.Patient_ID, 
        pPatients.Pt_Last AS PatientLast, pPatients.Pt_First AS PatientFirst, Eligibility.*, pPayer.Pay_Name    
        FROM #Request.prefix_db_agency#.Eligibility 
        JOIN #Request.prefix_db_agency#.pPtPayer ON Eligibility.PtPayer_ID = pPtPayer.PtPayer_ID AND pPtPayer.Status = 0
        JOIN #Request.prefix_db_agency#.pPayer ON pPtPayer.Payer_ID = pPayer.Pay_ID  AND pPayer.Status = 0 AND pPayer.Eligibility = 1
        JOIN #Request.prefix_db_agency#.pPatients ON pPtPayer.Patient_ID = pPatients.Patient_ID  AND pPatients.Status < 2
        WHERE Eligibility.Status = 0  
        AND  Eligibility.Expiration_Date BETWEEN  Now() AND DATE_ADD(NOW(), INTERVAL 60 DAY)
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC 
    </cfquery>

    <!--- Process expiring eligibility for Scheduling and Project Manager employees (matching expiring_eligibility.cfm access control) --->
    <cfloop query="getExpiringEligibility">
        <!--- Get Scheduling and Project Manager employees for this agency --->
        <cfquery name="getEmployeesForExpiringEligibility" datasource="#Application.DataSrc#">
            SELECT DISTINCT
                pEmployee.Emp_ID,
                pEmployee.Emp_First,
                pEmployee.Emp_Last
            FROM #Request.prefix_db_lookup#.pEmployee pEmployee
            INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
            WHERE pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
              AND pEmployee.Status = 0
              AND (employee_auth.eaRole LIKE '%Scheduling%' OR employee_auth.eaRole LIKE '%Project Manager%')
        </cfquery>

        <cfloop query="getEmployeesForExpiringEligibility">
            <cfquery name="checkExistingExpiringEligibility" datasource="#Application.DataSrc#">
                SELECT COUNT(*) AS totalrecordCount
                FROM #Request.prefix_db_agency#.Email_Daily_QA
                WHERE Patient_ID = <cfqueryparam value="#getExpiringEligibility.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                   AND Header = <cfqueryparam value="Expiring Eligibility" cfsqltype="CF_SQL_VARCHAR">
                  AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                  AND status = 0
            </cfquery>

            <cfif checkExistingExpiringEligibility.totalrecordCount EQ 0>
                <cfset encPatientId = encrypt("#getExpiringEligibility.Patient_ID#", encryptKey, "AES", "Hex")>
                <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=expiring_eligibility">
                <cfset description = "Expiring Eligibility: <a href='" & linkUrl & "'>View expiring eligibility</a>">
                <cfset empIdValue = getEmployeesForExpiringEligibility.Emp_ID>
                <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                    <cfset empIdValue = 0>
                </cfif>
                <cfset ptLastNull = NOT Len(Trim(getExpiringEligibility.PatientLast))>
                <cfset ptFirstNull = NOT Len(Trim(getExpiringEligibility.PatientFirst))>
                <cfset empFirstNull = NOT Len(Trim(getEmployeesForExpiringEligibility.Emp_First))>
                <cfset empLastNull = NOT Len(Trim(getEmployeesForExpiringEligibility.Emp_Last))>
                <cfquery name="insertExpiringEligibility" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                    (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                    VALUES (
                        <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                        <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getExpiringEligibility.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                        <cfqueryparam value="#getExpiringEligibility.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                        <cfqueryparam value="#getExpiringEligibility.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                        <cfqueryparam value="#getEmployeesForExpiringEligibility.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                        <cfqueryparam value="#getEmployeesForExpiringEligibility.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                        <cfqueryparam value="Expiring Eligibility" cfsqltype="CF_SQL_VARCHAR">,
                        <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                        <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                        <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                    )
                </cfquery>
            </cfif>
        </cfloop>
    </cfloop>

    <!--- Dashboard Reports - Expiring Authorizations - matches dash_auth_expire.cfm GetA query exactly --->
    <cfquery name="getExpiringAuthorizations" datasource="#Application.DataSrc#">
        SELECT pAuths.*,
            (SELECT count(*)
             FROM  #Request.prefix_db_agency#.Communication, #Request.prefix_db_agency#.CommunicationSubjects
             WHERE Communication.Patient_ID = pPatients.Patient_ID
             AND CommunicationSubjects.CommSub_ID = Communication.CommSub_ID
             AND (CommunicationSubjects.Subject like CONCAT("Discharge Summary - ",pAuths.Skill)
              OR CommunicationSubjects.Subject like  'Agency Transfer/Discharge Summary')
             AND Communication.Comm_record_deleted <> 1
             AND Communication.Status = 0 ) AS communication_discharge,
            pRevenue_Code.Visit_Type,pRevenue_Code.Rev_Code,pRevenue_Code.HCPCS,pPtPayer.Sub_First,
            pPayer.Pay_Name,pEmployee.Emp_Last,
            pEmployee.Emp_First, CONCAT(pEmployee.Emp_First , ", ", pEmployee.Emp_Last) AS name_by, pPatients.Pt_First,pPatients.Pt_Last 
        FROM  #Request.prefix_db_agency#.pAuths 
        JOIN  #Request.prefix_db_agency#.pRevenue_Code ON pRevenue_Code.Rev_CodeID = pAuths.Rev_ID
        JOIN  #Request.prefix_db_agency#.pPtPayer ON pPtPayer.PtPayer_ID = pAuths.PtPayer_ID
        LEFT OUTER JOIN  #Request.prefix_db_agency#.pPayer ON pPayer.Pay_ID = pPtPayer.Payer_ID
        JOIN  #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pAuths.Patient_ID
        LEFT OUTER JOIN  #Request.prefix_db_lookup#.pEmployee ON pAuths.Created_by = pEmployee.Emp_ID
        WHERE pAuths.STATUS  = 0 
        AND pRevenue_Code.Status = 0
        AND pPtPayer.Status = 0
        AND pPayer.Status = 0
        AND pPatients.Status = 0
        AND pAuths.Date_End BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 20 DAY)  
        GROUP BY pAuths.AutoAuth_ID 
        ORDER BY pAuths.Date_End ASC
    </cfquery>

    <!--- Process expiring authorizations for Field employees (matching dash_auth_expire.cfm lines 55-60 filter) --->
    <cfloop query="getExpiringAuthorizations">
        <!--- Only process if communication_discharge EQ 0 (matching dash_auth_expire.cfm line 155) --->
        <cfif getExpiringAuthorizations.communication_discharge EQ 0>
            <!--- Check if this patient is scheduled to any Field employee --->
            <cfquery name="getFieldEmployeesForExpiringAuth" datasource="#Application.DataSrc#">
                SELECT DISTINCT
                    pSchedules.Emp_ID,
                    pEmployee.Emp_First,
                    pEmployee.Emp_Last
                FROM #Request.prefix_db_agency#.pSchedules
                JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pSchedules.Assmt_ID
                JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
                INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
                WHERE pSchedules.Patient_ID = <cfqueryparam value="#getExpiringAuthorizations.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                AND pSchedules.Status = 0
                AND pAssessments.Status = 0
                AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
                AND pEmployee.Status = 0
                AND employee_auth.eaRole LIKE '%Field%'
                AND employee_auth.eaRole NOT LIKE '%Project Manager%'
                AND employee_auth.eaRole NOT LIKE '%Quality%'
            </cfquery>

            <cfloop query="getFieldEmployeesForExpiringAuth">
                <cfquery name="checkExistingExpiringAuthField" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Patient_ID = <cfqueryparam value="#getExpiringAuthorizations.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                       AND Header = <cfqueryparam value="Expiring Authorizations" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND status = 0
                </cfquery>

                <cfif checkExistingExpiringAuthField.totalrecordCount EQ 0>
                    <cfset encPatientId = encrypt("#getExpiringAuthorizations.Patient_ID#", encryptKey, "AES", "Hex")>
                    <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=dash_auth_expire">
                    <cfset description = "Expiring Authorizations: <a href='" & linkUrl & "'>View expiring authorizations</a>">
                    <cfset empIdValue = getFieldEmployeesForExpiringAuth.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfset ptLastNull = NOT Len(Trim(getExpiringAuthorizations.Pt_Last))>
                    <cfset ptFirstNull = NOT Len(Trim(getExpiringAuthorizations.Pt_First))>
                    <cfset empFirstNull = NOT Len(Trim(getFieldEmployeesForExpiringAuth.Emp_First))>
                    <cfset empLastNull = NOT Len(Trim(getFieldEmployeesForExpiringAuth.Emp_Last))>
                    <cfquery name="insertExpiringAuthField" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringAuthorizations.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringAuthorizations.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getExpiringAuthorizations.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#getFieldEmployeesForExpiringAuth.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#getFieldEmployeesForExpiringAuth.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="Expiring Authorizations" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfloop>
        </cfif>
    </cfloop>

    <!--- Process expiring authorizations for QA/PM employees (all records) --->
    <cfloop query="getExpiringAuthorizations">
        <!--- Only process if communication_discharge EQ 0 (matching dash_auth_expire.cfm line 155) --->
        <cfif getExpiringAuthorizations.communication_discharge EQ 0>
            <!--- Get all QA/PM employees for this agency --->
            <cfquery name="getQAEmployeesForExpiringAuth" datasource="#Application.DataSrc#">
                SELECT DISTINCT
                    pEmployee.Emp_ID,
                    pEmployee.Emp_First,
                    pEmployee.Emp_Last
                FROM #Request.prefix_db_lookup#.pEmployee pEmployee
                INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
                WHERE pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND pEmployee.Status = 0
                  AND (employee_auth.eaRole LIKE '%Project Manager%' OR employee_auth.eaRole LIKE '%Clinical Quality Assurance%')
            </cfquery>

            <cfloop query="getQAEmployeesForExpiringAuth">
                <cfquery name="checkExistingExpiringAuthQA" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Patient_ID = <cfqueryparam value="#getExpiringAuthorizations.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                       AND Header = <cfqueryparam value="Expiring Authorizations" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND status = 0
                </cfquery>

                <cfif checkExistingExpiringAuthQA.totalrecordCount EQ 0>
                    <cfset encPatientId = encrypt("#getExpiringAuthorizations.Patient_ID#", encryptKey, "AES", "Hex")>
                    <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=dash_auth_expire">
                    <cfset description = "Expiring Authorizations: <a href='" & linkUrl & "'>View expiring authorizations</a>">
                    <cfset empIdValue = getQAEmployeesForExpiringAuth.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfset ptLastNull = NOT Len(Trim(getExpiringAuthorizations.Pt_Last))>
                    <cfset ptFirstNull = NOT Len(Trim(getExpiringAuthorizations.Pt_First))>
                    <cfset empFirstNull = NOT Len(Trim(getQAEmployeesForExpiringAuth.Emp_First))>
                    <cfset empLastNull = NOT Len(Trim(getQAEmployeesForExpiringAuth.Emp_Last))>
                    <cfquery name="insertExpiringAuthQA" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringAuthorizations.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringAuthorizations.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getExpiringAuthorizations.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#getQAEmployeesForExpiringAuth.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#getQAEmployeesForExpiringAuth.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="Expiring Authorizations" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfloop>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - Expiring OASIS/Evaluations - matches dash_assess_expire.cfm GetA query exactly --->
    <cfquery name="getExpiringOASIS" datasource="#Application.DataSrc#">
        SELECT pAssessments.Assmt_ID, pAssessments.Record_creation_Date, pAssessments.Assmt_ID, 
        pAssessments.Patient_ID, pAssessments.F25 AS admission_status, pAssessments.F26 AS Assessment_Reason_M0100, pAssessments.F177 AS Certification_Start, 
        pAssessments.F178 AS Certification_End, pAssessments.F176 AS Assessment_Completed_M0090, pAssessments.F197 AS Transmission_status, 
        pPatients.Pt_First, pPatients.Pt_Last, pPatients.Pt_Middle 
        FROM #Request.prefix_db_agency#.pAssessments
        JOIN #Request.prefix_db_agency#.pPatients  ON pAssessments.Patient_ID = pPatients.Patient_ID 
        JOIN  #Request.prefix_db_agency#.pAdmit  ON pAssessments.Admit_ID = pAdmit.Admit_ID  AND pAdmit.Status = 0
        WHERE pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pPatients.Status = 0
        AND pAssessments.Status = 0 
        AND (pAssessments.F26 LIKE '1%' OR pAssessments.F26 LIKE '4%' OR pAssessments.F26 LIKE '3%') 
        AND pAssessments.F178 >= now()
        AND  pAssessments.Admit_ID NOT IN (SELECT  pAssessments.Admit_ID FROM #Request.prefix_db_agency#.pAssessments  
                WHERE  (pAssessments.F26 like '9%' OR pAssessments.F26 like '7%' OR pAssessments.F26 like '8%')
                 AND  pAssessments.Status =0)

        UNION 

        SELECT pAssessments.Assmt_ID, pAssessments.Record_creation_Date, pAssessments.Assmt_ID, 
        pAssessments.Patient_ID, pAssessments.F25 AS admission_status, pAssessments.F26 AS Assessment_Reason_M0100, 
        pAssessments.F177 AS Certification_Start, 
        pAssessments.F178 AS Certification_End, pAssessments.F176 AS Assessment_Completed_M0090, 
        pAssessments.F197 AS Transmission_status, 
        pPatients.Pt_First, pPatients.Pt_Last, pPatients.Pt_Middle 
        FROM #Request.prefix_db_agency#.pAssessments
        JOIN #Request.prefix_db_agency#.pPatients  ON pAssessments.Patient_ID = pPatients.Patient_ID
        JOIN  #Request.prefix_db_agency#.pAdmit  ON pAssessments.Admit_ID = pAdmit.Admit_ID  AND pAdmit.Status = 0
        LEFT OUTER JOIN  #Request.prefix_db_agency#.assessment_assign ON assessment_assign.Assmt_ID =  pAssessments.Assmt_ID
        WHERE pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
        AND pPatients.Status = 0
        AND pAssessments.Status = 0 
        AND (pAssessments.F25 = 0 OR  pAssessments.F25 IS NULL) 
        AND (pAssessments.F26 LIKE '%Eval%' OR pAssessments.F26 LIKE '%Followup%') 
        AND pAssessments.F176 <= now()
        AND  pAssessments.Admit_ID NOT IN (SELECT  pAssessments.Admit_ID FROM #Request.prefix_db_agency#.pAssessments  
                WHERE  (pAssessments.F26 like '9%' OR pAssessments.F26 like '7%' OR pAssessments.F26 like '8%')
                 AND  pAssessments.Status =0)

        GROUP BY pAssessments.Assmt_ID 
    </cfquery>

    <!--- Process expiring OASIS/Evaluations for Field employees (matching dash_assess_expire.cfm lines 43-49 and 79-85 filter) --->
    <cfloop query="getExpiringOASIS">
        <!--- Calculate diffdays to match dashboard filtering logic (lines 202-216) --->
        <cfset todaydate = DateFormat(Now(), "yyyy-mm-dd")>
        <cfset diffdays = 0>
        <cfif getExpiringOASIS.Certification_End NEQ '' AND getExpiringOASIS.Assessment_Reason_M0100 does not contain 'Eval' AND getExpiringOASIS.Assessment_Reason_M0100 does not contain 'Followup'>
            <cfset diffdays = DateDiff("d", todaydate, getExpiringOASIS.Certification_End)>
        <cfelseif getExpiringOASIS.Assessment_Completed_M0090 NEQ ''>
            <cfset expiredate = DateAdd("d", getExpiringOASIS.Assessment_Completed_M0090, 30)>
            <cfset diffdays = DateDiff("d", todaydate, expiredate)>
        </cfif>
        
        <!--- Only process if diffdays <= 10 (matching dash_assess_expire.cfm line 213-214) --->
        <cfif (diffdays LTE 10 AND getExpiringOASIS.Assessment_Reason_M0100 does not contain 'Eval' AND getExpiringOASIS.Assessment_Reason_M0100 does not contain 'Followup') 
              OR (diffdays LTE 10 AND (getExpiringOASIS.Assessment_Reason_M0100 contains 'Eval' OR getExpiringOASIS.Assessment_Reason_M0100 contains 'Followup') AND diffdays GTE 0)>
            <!--- Check if this patient is scheduled to any Field employee --->
            <cfquery name="getFieldEmployeesForExpiringOASIS" datasource="#Application.DataSrc#">
                SELECT DISTINCT
                    pSchedules.Emp_ID,
                    pEmployee.Emp_First,
                    pEmployee.Emp_Last
                FROM #Request.prefix_db_agency#.pSchedules
                JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pSchedules.Assmt_ID
                JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
                INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
                WHERE pSchedules.Patient_ID = <cfqueryparam value="#getExpiringOASIS.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                AND pSchedules.Status = 0
                AND pAssessments.Status = 0
                AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
                AND pEmployee.Status = 0
                AND employee_auth.eaRole LIKE '%Field%'
                AND employee_auth.eaRole NOT LIKE '%Project Manager%'
                AND employee_auth.eaRole NOT LIKE '%Quality%'
                <!--- For Eval/Followup, also check assessment_assign (matching dash_assess_expire.cfm line 84) --->
                <cfif getExpiringOASIS.Assessment_Reason_M0100 contains 'Eval' OR getExpiringOASIS.Assessment_Reason_M0100 contains 'Followup'>
                    AND EXISTS (
                        SELECT 1 FROM #Request.prefix_db_agency#.assessment_assign
                        WHERE assessment_assign.Assmt_ID = <cfqueryparam value="#getExpiringOASIS.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">
                        AND assessment_assign.Emp_ID = pSchedules.Emp_ID
                    )
                </cfif>
            </cfquery>

            <cfloop query="getFieldEmployeesForExpiringOASIS">
                <cfquery name="checkExistingExpiringOASISField" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Patient_ID = <cfqueryparam value="#getExpiringOASIS.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                      AND Assmt_ID = <cfqueryparam value="#getExpiringOASIS.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">
                       AND Header = <cfqueryparam value="Expiring OASIS/Evaluations" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND status = 0
                </cfquery>

                <cfif checkExistingExpiringOASISField.totalrecordCount EQ 0>
                    <cfset encPatientId = encrypt("#getExpiringOASIS.Patient_ID#", encryptKey, "AES", "Hex")>
                    <cfset encAssmtId = encrypt("#getExpiringOASIS.Assmt_ID#", encryptKey, "AES", "Hex")>
                    <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=dash_assess_expire">
                    <cfset description = "Expiring OASIS/Evaluations: <a href='" & linkUrl & "'>View expiring assessments</a>">
                    <cfset empIdValue = getFieldEmployeesForExpiringOASIS.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfset ptLastNull = NOT Len(Trim(getExpiringOASIS.Pt_Last))>
                    <cfset ptFirstNull = NOT Len(Trim(getExpiringOASIS.Pt_First))>
                    <cfset empFirstNull = NOT Len(Trim(getFieldEmployeesForExpiringOASIS.Emp_First))>
                    <cfset empLastNull = NOT Len(Trim(getFieldEmployeesForExpiringOASIS.Emp_Last))>
                    <cfset assmtIdValue = getExpiringOASIS.Assmt_ID>
                    <cfset assmtIdNull = NOT IsNumeric(assmtIdValue)>
                    <cfquery name="insertExpiringOASISField" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#assmtIdValue#" cfsqltype="CF_SQL_INTEGER" null="#assmtIdNull#">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringOASIS.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringOASIS.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getExpiringOASIS.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#getFieldEmployeesForExpiringOASIS.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#getFieldEmployeesForExpiringOASIS.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="Expiring OASIS/Evaluations" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfloop>
        </cfif>
    </cfloop>

    <!--- Process expiring OASIS/Evaluations for QA/PM employees (all records) --->
    <cfloop query="getExpiringOASIS">
        <!--- Calculate diffdays to match dashboard filtering logic (lines 202-216) --->
        <cfset todaydate = DateFormat(Now(), "yyyy-mm-dd")>
        <cfset diffdays = 0>
        <cfif getExpiringOASIS.Certification_End NEQ '' AND getExpiringOASIS.Assessment_Reason_M0100 does not contain 'Eval' AND getExpiringOASIS.Assessment_Reason_M0100 does not contain 'Followup'>
            <cfset diffdays = DateDiff("d", todaydate, getExpiringOASIS.Certification_End)>
        <cfelseif getExpiringOASIS.Assessment_Completed_M0090 NEQ ''>
            <cfset expiredate = DateAdd("d", getExpiringOASIS.Assessment_Completed_M0090, 30)>
            <cfset diffdays = DateDiff("d", todaydate, expiredate)>
        </cfif>
        
        <!--- Only process if diffdays <= 10 (matching dash_assess_expire.cfm line 213-214) --->
        <cfif (diffdays LTE 10 AND getExpiringOASIS.Assessment_Reason_M0100 does not contain 'Eval' AND getExpiringOASIS.Assessment_Reason_M0100 does not contain 'Followup') 
              OR (diffdays LTE 10 AND (getExpiringOASIS.Assessment_Reason_M0100 contains 'Eval' OR getExpiringOASIS.Assessment_Reason_M0100 contains 'Followup') AND diffdays GTE 0)>
            <!--- Get all QA/PM employees for this agency --->
            <cfquery name="getQAEmployeesForExpiringOASIS" datasource="#Application.DataSrc#">
                SELECT DISTINCT
                    pEmployee.Emp_ID,
                    pEmployee.Emp_First,
                    pEmployee.Emp_Last
                FROM #Request.prefix_db_lookup#.pEmployee pEmployee
                INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
                WHERE pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND pEmployee.Status = 0
                  AND (employee_auth.eaRole LIKE '%Project Manager%' OR employee_auth.eaRole LIKE '%Clinical Quality Assurance%')
            </cfquery>

            <cfloop query="getQAEmployeesForExpiringOASIS">
                <cfquery name="checkExistingExpiringOASISQA" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Patient_ID = <cfqueryparam value="#getExpiringOASIS.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                      AND Assmt_ID = <cfqueryparam value="#getExpiringOASIS.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">
                       AND Header = <cfqueryparam value="Expiring OASIS/Evaluations" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND status = 0
                </cfquery>

                <cfif checkExistingExpiringOASISQA.totalrecordCount EQ 0>
                    <cfset encPatientId = encrypt("#getExpiringOASIS.Patient_ID#", encryptKey, "AES", "Hex")>
                    <cfset encAssmtId = encrypt("#getExpiringOASIS.Assmt_ID#", encryptKey, "AES", "Hex")>
                    <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=dash_assess_expire">
                    <cfset description = "Expiring OASIS/Evaluations: <a href='" & linkUrl & "'>View expiring assessments</a>">
                    <cfset empIdValue = getQAEmployeesForExpiringOASIS.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfset ptLastNull = NOT Len(Trim(getExpiringOASIS.Pt_Last))>
                    <cfset ptFirstNull = NOT Len(Trim(getExpiringOASIS.Pt_First))>
                    <cfset empFirstNull = NOT Len(Trim(getQAEmployeesForExpiringOASIS.Emp_First))>
                    <cfset empLastNull = NOT Len(Trim(getQAEmployeesForExpiringOASIS.Emp_Last))>
                    <cfset assmtIdValue = getExpiringOASIS.Assmt_ID>
                    <cfset assmtIdNull = NOT IsNumeric(assmtIdValue)>
                    <cfquery name="insertExpiringOASISQA" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#assmtIdValue#" cfsqltype="CF_SQL_INTEGER" null="#assmtIdNull#">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringOASIS.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringOASIS.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getExpiringOASIS.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#getQAEmployeesForExpiringOASIS.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#getQAEmployeesForExpiringOASIS.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="Expiring OASIS/Evaluations" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfloop>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - Supervision non-Compliance - matches supervision_non_compliance.cfm GetList query exactly --->
    <cfquery name="getSupervisionNonCompliance" datasource="#Application.DataSrc#">
        SELECT pSchedules.*,pPatients.Patient_ID, pPatients.Pt_Last AS PatientLast, pPatients.Pt_First AS PatientFirst, pPatients.Pt_Agy_ID, 
         pAssessments.F26,  pAssessments.Assmt_ID,pAuths.Total_Visits,
            (SELECT  ps.Visit_Date FROM #Request.prefix_db_agency#.pSchedules ps
             WHERE  ps.Assmt_ID = pAssessments.Assmt_ID 
               AND ps.Status = 0 AND ps.Supervision = 1
                AND ps.Visit_Date < now() ORDER BY ps.Visit_Date DESC LIMIT 0,1) AS visits_scheduledold,
            pAuths.Skill,pEmployee.Emp_Last,pEmployee.Emp_First,pEmployee.Skill_1,pEmployee.Skill_2, pEmployee.Skill_3  
        FROM #Request.prefix_db_agency#.pSchedules
        JOIN #Request.prefix_db_agency#.pAuths        ON pSchedules.Auth_ID = pAuths.Auth_ID AND pAuths.Status =0 
        JOIN #Request.prefix_db_agency#.pAssessments  ON pAssessments.Assmt_ID = pAuths.Assmt_ID AND pAssessments.Status =0 
        JOIN #Request.prefix_db_agency#.pPatients     ON pPatients.Patient_ID = pAssessments.Patient_ID  
        JOIN #Request.prefix_db_lookup#.pEmployee     ON pEmployee.Emp_ID = pSchedules.Emp_ID  
        WHERE pPatients.Status  < 2
        AND pSchedules.Supervision = 1 AND pSchedules.status = 0
        GROUP BY pSchedules.Assmt_ID
        ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC
    </cfquery>

    <!--- Process supervision non-compliance (matching supervision_non_compliance.cfm lines 79-102 logic) --->
    <cfloop query="getSupervisionNonCompliance">
        <!--- Only process if visits_scheduledold NEQ '' (matching supervision_non_compliance.cfm line 79) --->
        <cfif getSupervisionNonCompliance.visits_scheduledold NEQ ''>
            <!--- Calculate days based on Skill (matching supervision_non_compliance.cfm lines 84-90) --->
            <cfset days = 14>
            <cfif getSupervisionNonCompliance.Skill EQ 'HHA'>
                <cfset days = 14>
            <cfelseif getSupervisionNonCompliance.Skill EQ 'SN'>
                <cfset days = 14>
            <cfelse>
                <cfset days = 30>
            </cfif>
            
            <!--- Calculate nextsupervison and elapsed_days (matching supervision_non_compliance.cfm lines 91-92) --->
            <cfset nextsupervison = dateAdd('d', days, getSupervisionNonCompliance.visits_scheduledold)>
            <cfset elapsed_days = dateDiff("d", nextsupervison, now())>
            
            <!--- Only process if nextsupervison LT now() (meaning supervision is past due, matching line 100) --->
            <cfif nextsupervison LT now()>
                <cfquery name="checkExistingSupervisionNonCompliance" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Patient_ID = <cfqueryparam value="#getSupervisionNonCompliance.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
                       AND Header = <cfqueryparam value="Supervision non-Compliance" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND status = 0
                </cfquery>

                <cfif checkExistingSupervisionNonCompliance.totalrecordCount EQ 0>
                    <cfset encPatientId = encrypt("#getSupervisionNonCompliance.Patient_ID#", encryptKey, "AES", "Hex")>
                    <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=supervision_non_compliance">
                    <cfset description = "Supervision non-Compliance: <a href='" & linkUrl & "'>View supervision non-compliance</a>">
                    <cfset empIdValue = getSupervisionNonCompliance.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfset ptLastNull = NOT Len(Trim(getSupervisionNonCompliance.PatientLast))>
                    <cfset ptFirstNull = NOT Len(Trim(getSupervisionNonCompliance.PatientFirst))>
                    <cfset empFirstNull = NOT Len(Trim(getSupervisionNonCompliance.Emp_First))>
                    <cfset empLastNull = NOT Len(Trim(getSupervisionNonCompliance.Emp_Last))>
                    <cfquery name="insertSupervisionNonCompliance" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getSupervisionNonCompliance.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getSupervisionNonCompliance.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getSupervisionNonCompliance.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#getSupervisionNonCompliance.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#getSupervisionNonCompliance.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="Supervision non-Compliance" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfif>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - PN to Review --->
    <cfquery name="getPNToReview" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pSchedules.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pSchedules pSchedules
        JOIN #Request.prefix_db_agency#.pPatients pPatients ON pPatients.Patient_ID = pSchedules.Patient_ID
        LEFT OUTER JOIN #Request.prefix_db_agency#.pAssessments pAssessments ON pAssessments.Assmt_ID = pSchedules.Assmt_ID AND pAssessments.Status = 0
        JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
        WHERE pSchedules.Status = 0
        AND pPatients.Status < 2
        AND pEmployee.Status = 0
        AND pSchedules.pgnotesdraft = 2
        AND pSchedules.Missed = 0
        AND pSchedules.Visit_Date <= DATE_FORMAT(NOW(), '%Y-%m-%d')
        AND pSchedules.QA_View IN (0, 2)
        GROUP BY pSchedules.Schedule_ID
    </cfquery>

    <cfloop query="getPNToReview">
        <cfquery name="checkExistingPNToReview" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE Patient_ID = <cfqueryparam value="#getPNToReview.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
              AND Header = <cfqueryparam value="PN to Review" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingPNToReview.totalrecordCount EQ 0>
            <cfset encPatientId = encrypt("#getPNToReview.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=pg_notes_QA_new">
            <cfset description = "PN to Review: <a href='" & linkUrl & "'>View progress notes to review</a>">
            <cfset empIdValue = getPNToReview.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>
            <cfset ptLastNull = NOT Len(Trim(getPNToReview.Pt_Last))>
            <cfset ptFirstNull = NOT Len(Trim(getPNToReview.Pt_First))>
            <cfset empFirstNull = NOT Len(Trim(getPNToReview.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getPNToReview.Emp_Last))>
            <cfquery name="insertPNToReview" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getPNToReview.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getPNToReview.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#getPNToReview.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#getPNToReview.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#getPNToReview.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="PN to Review" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - PN to Approve --->
    <cfquery name="getPNToApprove" datasource="#Application.DataSrc#">
        SELECT DISTINCT
            pPatients.Patient_ID,
            pPatients.Pt_Last,
            pPatients.Pt_First,
            pSchedules.Emp_ID,
            pEmployee.Emp_First,
            pEmployee.Emp_Last
        FROM #Request.prefix_db_agency#.pAssessments pAssessments
        JOIN #Request.prefix_db_agency#.pPatients pPatients ON pPatients.Patient_ID = pAssessments.Patient_ID
        JOIN #Request.prefix_db_agency#.pSchedules pSchedules ON pSchedules.Assmt_ID = pAssessments.Assmt_ID
        JOIN #Request.prefix_db_agency#.pAdmit pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID AND pAdmit.Status = 0
        JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
        WHERE pAssessments.Status = 0
        AND pPatients.Status < 2
        AND pSchedules.Status = 0
        AND pSchedules.Emp_ID != 0
        AND pSchedules.pgnotesdraft != 2
        AND pSchedules.Visit_Date <= NOW()
    </cfquery>

    <cfloop query="getPNToApprove">
        <cfquery name="checkExistingPNToApprove" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS totalrecordCount
            FROM #Request.prefix_db_agency#.Email_Daily_QA
            WHERE Patient_ID = <cfqueryparam value="#getPNToApprove.Patient_ID#" cfsqltype="CF_SQL_INTEGER">
              AND Header = <cfqueryparam value="PN to Approve" cfsqltype="CF_SQL_VARCHAR">
              AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
              AND status = 0
        </cfquery>

        <cfif checkExistingPNToApprove.totalrecordCount EQ 0>
            <cfset encPatientId = encrypt("#getPNToApprove.Patient_ID#", encryptKey, "AES", "Hex")>
            <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=dash_no_notes">
            <cfset description = "PN to Approve: <a href='" & linkUrl & "'>View progress notes to approve</a>">
            <cfset empIdValue = getPNToApprove.Emp_ID>
            <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                <cfset empIdValue = 0>
            </cfif>
            <cfset ptLastNull = NOT Len(Trim(getPNToApprove.Pt_Last))>
            <cfset ptFirstNull = NOT Len(Trim(getPNToApprove.Pt_First))>
            <cfset empFirstNull = NOT Len(Trim(getPNToApprove.Emp_First))>
            <cfset empLastNull = NOT Len(Trim(getPNToApprove.Emp_Last))>
            <cfquery name="insertPNToApprove" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                (Daily_QA_Date, Emp_ID, Patient_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                VALUES (
                    <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                    <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getPNToApprove.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                    <cfqueryparam value="#getPNToApprove.Pt_Last#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                    <cfqueryparam value="#getPNToApprove.Pt_First#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                    <cfqueryparam value="#getPNToApprove.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                    <cfqueryparam value="#getPNToApprove.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                    <cfqueryparam value="PN to Approve" cfsqltype="CF_SQL_VARCHAR">,
                    <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                    <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                    <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                )
            </cfquery>
        </cfif>
    </cfloop>

    <!--- Dashboard Reports - Expiring Visits - matches Expiring_visits.cfm Visits query exactly --->
    <cfquery name="getExpiringVisits" datasource="#Application.DataSrc#">
        SELECT DISTINCT 
         IFNULL(pAssessments.Assmt_ID,0) AS Assmt_ID, pAssessments.F177 AS CertStart,
         pAssessments.F25 AS Admission_Status , pAssessments.F178 AS CertEnd,
         pAssessments.F26 AS Reason,  F197  AS TRANSTATUS, '' AS Assessment_Number, pAssessments.Assmt_ID, 
         pPatients.Patient_ID, pPatients.Pt_Last AS PatientLast, ''AS DOC,
           CASE
    WHEN pAssessments.F177  < '2020-01-01' THEN  "FIRST FINAL"
    WHEN DATEDIFF(pSchedules.Visit_Date,pAssessments.F177) < 30 THEN  "FIRST FINAL"
    WHEN DATEDIFF(pSchedules.Visit_Date,pAssessments.F177) >= 30 THEN  "SECOND FINAL"
    ELSE  ""
    END as claim_type,
         pPatients.Pt_First AS PatientFirst, pPatients.Status AS PatStat,
         pSchedules.Schedule_ID, pSchedules.Visit_Date,
          pSchedules.Missed,pSchedules.Patient_ID,
          pSchedules.PtPayer_ID AS PAYID, pSchedules.Skill AS Visit_Types, 
         CASE 
         	WHEN pSchedules.Followup_visit = 1 THEN pSchedules.Visit_Type
         ELSE 
         	 pSchedules.Skill
         END AS Visit_Type,
		 pAssessments.Admit_ID,
         pSchedules.Progress_Note, pSchedules.Followup_visit, pSchedules.Initial_visit, pSchedules.Total_Units, '' AS SOUT, pSchedules.PtPayer_ID, pSchedules.Nonbillable,pSchedules.Notes, pSchedules.pgnotesdraft,
         pEmployee.Emp_Last, pEmployee.Emp_First,pSchedules.Emp_ID,IFNULL(pPayer.timely_filing,0) AS timely_filing,
         pPayer.Pay_ID AS PPAYID,  pPayer.Pay_Name,pPayer.Output AS Output_Type,pAssessments.F306 
         FROM #Request.prefix_db_agency#.pSchedules
         JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pSchedules.Assmt_ID 
         AND pAssessments.Patient_ID = pSchedules.Patient_ID  AND  pAssessments.status = 0
         JOIN #Request.prefix_db_agency#.pAdmit ON pAssessments.Admit_ID = pAdmit.Admit_ID  AND pAdmit.status = 0
         JOIN #Request.prefix_db_agency#.pAuths  ON pSchedules.Auth_ID = pAuths.Auth_ID  AND  pAuths.status = 0
	     JOIN #Request.prefix_db_agency#.pRevenue_Code ON pRevenue_Code.Rev_CodeID = pAuths.Rev_ID AND pRevenue_Code.status = 0
         JOIN #Request.prefix_db_agency#.pPatients ON  pPatients.Patient_Id = pSchedules.Patient_Id  
         AND   pPatients.Status IN (0,1,4)
         JOIN  #Request.prefix_db_agency#.pPtPayer  ON pSchedules.PtPayer_ID =  pPtPayer.PtPayer_ID AND   pPtPayer.Status  < 2
		 JOIN #Request.prefix_db_agency#.pPayer ON  pPayer.Pay_Id = pPtPayer.Payer_ID AND   pPayer.Status = 0
		 JOIN #Request.prefix_db_lookup#.pEmployee  ON pSchedules.Emp_ID = pEmployee.Emp_ID
	     WHERE   pSchedules.Visit_Date < Now() 
	        AND   pSchedules.Invoice_ID = 0
	        AND   pSchedules.Nonbillable = 0
	        AND   pSchedules.status = 0
	        AND  pSchedules.Missed = 0
	        AND pPatients.Patient_ID IS NOT NULL
	        AND pAssessments.Assmt_ID IS NOT NULL
	       AND pPatients.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
	       GROUP BY pSchedules.Schedule_ID
          Order by PatientLast, PatientFirst, Visit_Date, CertEnd, Reason, Visit_Type
    </cfquery>

    <!--- Process Expiring Visits for Field employees --->
    <cfloop query="getExpiringVisits">
        <!--- Calculate days until expiration (matching dashboard lines 104-105) --->
        <cfset age = DateDiff("d", getExpiringVisits.Visit_Date, now())>
        <cfset until_expiration = getExpiringVisits.timely_filing - age>
        
        <!--- Only process visits that are expiring soon (within 7 days) --->
        <cfif until_expiration LTE 7 AND until_expiration GTE 0>
            <!--- Check if this schedule is assigned to any Field employee --->
            <cfquery name="getFieldEmployeesForExpiringVisits" datasource="#Application.DataSrc#">
                SELECT DISTINCT
                    pSchedules.Emp_ID,
                    pEmployee.Emp_First,
                    pEmployee.Emp_Last
                FROM #Request.prefix_db_agency#.pSchedules
                JOIN #Request.prefix_db_lookup#.pEmployee ON pEmployee.Emp_ID = pSchedules.Emp_ID
                INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
                WHERE pSchedules.Schedule_ID = <cfqueryparam value="#getExpiringVisits.Schedule_ID#" cfsqltype="CF_SQL_INTEGER">
                AND pSchedules.Status = 0
                AND pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
                AND pEmployee.Status = 0
                AND employee_auth.eaRole LIKE '%Field%'
                AND employee_auth.eaRole NOT LIKE '%Project Manager%'
                AND employee_auth.eaRole NOT LIKE '%Quality%'
                AND pSchedules.Emp_ID != 0
            </cfquery>

            <cfloop query="getFieldEmployeesForExpiringVisits">
                <cfquery name="checkExistingExpiringVisitsField" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Schedule_ID = <cfqueryparam value="#getExpiringVisits.Schedule_ID#" cfsqltype="CF_SQL_INTEGER">
                       AND Header = <cfqueryparam value="Expiring Visits" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND status = 0
                </cfquery>

                <cfif checkExistingExpiringVisitsField.totalrecordCount EQ 0>
                    <cfset encPatientId = encrypt("#getExpiringVisits.Patient_ID#", encryptKey, "AES", "Hex")>
                    <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=Expiring_visits">
                    <cfset description = "Expiring Visits: Visit for " & getExpiringVisits.PatientLast & ", " & getExpiringVisits.PatientFirst & " expires in " & until_expiration & " days. <a href='" & linkUrl & "'>View expiring visits</a>">
                    <cfset empIdValue = getFieldEmployeesForExpiringVisits.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfset ptLastNull = NOT Len(Trim(getExpiringVisits.PatientLast))>
                    <cfset ptFirstNull = NOT Len(Trim(getExpiringVisits.PatientFirst))>
                    <cfset empFirstNull = NOT Len(Trim(getFieldEmployeesForExpiringVisits.Emp_First))>
                    <cfset empLastNull = NOT Len(Trim(getFieldEmployeesForExpiringVisits.Emp_Last))>
                    <cfquery name="insertExpiringVisitsField" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Schedule_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#getExpiringVisits.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringVisits.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringVisits.Schedule_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringVisits.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getExpiringVisits.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#getFieldEmployeesForExpiringVisits.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#getFieldEmployeesForExpiringVisits.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="Expiring Visits" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfloop>
        </cfif>
    </cfloop>

    <!--- Process Expiring Visits for QA/PM employees (all records) --->
    <cfloop query="getExpiringVisits">
        <!--- Calculate days until expiration (matching dashboard lines 104-105) --->
        <cfset age = DateDiff("d", getExpiringVisits.Visit_Date, now())>
        <cfset until_expiration = getExpiringVisits.timely_filing - age>
        
        <!--- Only process visits that are expiring soon (within 7 days) --->
        <cfif until_expiration LTE 7 AND until_expiration GTE 0>
            <!--- Get all QA/PM employees for this agency --->
            <cfquery name="getQAEmployeesForExpiringVisits" datasource="#Application.DataSrc#">
                SELECT DISTINCT
                    pEmployee.Emp_ID,
                    pEmployee.Emp_First,
                    pEmployee.Emp_Last
                FROM #Request.prefix_db_lookup#.pEmployee pEmployee
                INNER JOIN #Request.prefix_db_agency#.employee_auth ON pEmployee.Emp_ID = employee_auth.eaID
                WHERE pEmployee.Loc_ID = <cfqueryparam value="#Agencylist.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
                  AND pEmployee.Status = 0
                  AND (employee_auth.eaRole LIKE '%Project Manager%' OR employee_auth.eaRole LIKE '%Clinical Quality Assurance%')
            </cfquery>

            <cfloop query="getQAEmployeesForExpiringVisits">
                <cfquery name="checkExistingExpiringVisitsQA" datasource="#Application.DataSrc#">
                    SELECT COUNT(*) AS totalrecordCount
                    FROM #Request.prefix_db_agency#.Email_Daily_QA
                    WHERE Schedule_ID = <cfqueryparam value="#getExpiringVisits.Schedule_ID#" cfsqltype="CF_SQL_INTEGER">
                       AND Header = <cfqueryparam value="Expiring Visits" cfsqltype="CF_SQL_VARCHAR">
                      AND Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
                      AND status = 0
                </cfquery>

                <cfif checkExistingExpiringVisitsQA.totalrecordCount EQ 0>
                    <cfset encPatientId = encrypt("#getExpiringVisits.Patient_ID#", encryptKey, "AES", "Hex")>
                    <cfset linkUrl = Application.secure & "dashboard/index.cfm?page=dashboard&cat&rpt=Expiring_visits">
                    <cfset description = "Expiring Visits: Visit for " & getExpiringVisits.PatientLast & ", " & getExpiringVisits.PatientFirst & " expires in " & until_expiration & " days. <a href='" & linkUrl & "'>View expiring visits</a>">
                    <cfset empIdValue = getQAEmployeesForExpiringVisits.Emp_ID>
                    <cfif NOT Len(empIdValue) OR NOT IsNumeric(empIdValue)>
                        <cfset empIdValue = 0>
                    </cfif>
                    <cfset ptLastNull = NOT Len(Trim(getExpiringVisits.PatientLast))>
                    <cfset ptFirstNull = NOT Len(Trim(getExpiringVisits.PatientFirst))>
                    <cfset empFirstNull = NOT Len(Trim(getQAEmployeesForExpiringVisits.Emp_First))>
                    <cfset empLastNull = NOT Len(Trim(getQAEmployeesForExpiringVisits.Emp_Last))>
                    <cfquery name="insertExpiringVisitsQA" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_agency#.Email_Daily_QA
                        (Daily_QA_Date, Assmt_ID, Emp_ID, Patient_ID, Schedule_ID, Pt_Last, Pt_First, Emp_First, Emp_Last, Header, Description, Created_Date, status)
                        VALUES (
                            <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">,
                            <cfqueryparam value="#getExpiringVisits.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#empIdValue#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringVisits.Patient_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringVisits.Schedule_ID#" cfsqltype="CF_SQL_INTEGER">,
                            <cfqueryparam value="#getExpiringVisits.PatientLast#" cfsqltype="CF_SQL_VARCHAR" null="#ptLastNull#">,
                            <cfqueryparam value="#getExpiringVisits.PatientFirst#" cfsqltype="CF_SQL_VARCHAR" null="#ptFirstNull#">,
                            <cfqueryparam value="#getQAEmployeesForExpiringVisits.Emp_First#" cfsqltype="CF_SQL_VARCHAR" null="#empFirstNull#">,
                            <cfqueryparam value="#getQAEmployeesForExpiringVisits.Emp_Last#" cfsqltype="CF_SQL_VARCHAR" null="#empLastNull#">,
                            <cfqueryparam value="Expiring Visits" cfsqltype="CF_SQL_VARCHAR">,
                            <cfqueryparam value="#description#" cfsqltype="CF_SQL_LONGVARCHAR">,
                            <cfqueryparam value="#currentTimestamp#" cfsqltype="CF_SQL_TIMESTAMP">,
                            <cfqueryparam value="0" cfsqltype="CF_SQL_INTEGER">
                        )
                    </cfquery>
                </cfif>
            </cfloop>
        </cfif>
    </cfloop>

    <!--- Email summary to leadership --->
    <cfquery name="getDailyQAEmail" datasource="#Application.DataSrc#">
        SELECT Email_Daily_QA.*, pEmployee.Emp_Email
        FROM #Request.prefix_db_agency#.Email_Daily_QA Email_Daily_QA
        LEFT JOIN #Request.prefix_db_lookup#.pEmployee pEmployee ON pEmployee.Emp_ID = Email_Daily_QA.Emp_ID
        WHERE Email_Daily_QA.Header IN (
            'incomplete assessment',
            'orphan symptoms to review',
            'medications to review',
            'missed visit communication',
            'missed visit needs documentation',
            'unread communication',
            'late progress note',
            'procedure needs explanation',
            'procedure QA',
            'incomplete careplan',
            'VBP Inconsistencies',
            'Medications Need Reconciliation',
            'Missing OASIS',
            'Authorizations required',
            'Frequency Non-Compliance',
            'Missing 485',
            'Medication Updates Needed',
            'Coding Updates Needed',
            'Disabled Goals Need Approval',
            'Discharges to Review',
            'Missing Eligibility',
            'Pending Admissions',
            'New Orders Need 487',
            'Un-Sent Orders',
            'Un-Signed Orders',
            'Expiring Eligibility',
            'Expiring Authorizations',
            'Expiring OASIS/Evaluations',
            'Supervision non-Compliance',
            'PN to Review',
            'PN to Approve',
            'Expiring Visits'
        )
          AND Email_Daily_QA.Daily_QA_Date = <cfqueryparam value="#currentDate#" cfsqltype="CF_SQL_DATE">
          AND Email_Daily_QA.status = 0
        ORDER BY Email_Daily_QA.Header, Email_Daily_QA.Pt_Last, Email_Daily_QA.Pt_First
    </cfquery>

    <cfif getDailyQAEmail.recordcount gt 0>
        <cfquery name="getDailyQAHeaders" dbtype="query">
            SELECT DISTINCT Header
            FROM getDailyQAEmail
            ORDER BY Header
        </cfquery>

        <cfset environmentName = "">
        <cfif StructKeyExists(Application, "ServerName") AND Len(Trim(Application.ServerName))>
            <cfset environmentName = Trim(Application.ServerName)>
        <cfelse>
            <cfset environmentName = CGI.SERVER_NAME>
        </cfif>

        <!--- Determine email recipients based on environment --->
        <cfset isStageEnvironment = false>
        <cfif Application.ServerName EQ "Stage Server" OR CGI.SERVER_NAME EQ "54.175.136.41" OR CGI.SERVER_NAME EQ "stagesecure.myhomecarebiz.com">
            <cfset isStageEnvironment = true>
        </cfif>
        
        <cfif isStageEnvironment>
            <!--- Stage: Send only to vel --->
            <cfset emailTo = "velmurugan@myhomecarebiz.com">
            <cfset emailCc = "">
        <cfelse>
            <!--- Production: Send to all --->
            <cfset emailTo = "velmurugan@myhomecarebiz.com,melissa@myhomecarebiz.com,janice.l@myhomecarebiz.com">
            <cfset emailCc = "velmurugan@myhomecarebiz.com">
        </cfif>

        <cfmail to="#emailTo#"
                 from="info@myhomecarebiz.com"
                subject="[#environmentName#] Daily QA items for #Agencylist.Agency_Name# (#Agencylist.Agency_Login#)"
                type="html">
            <cfoutput>
                Environment: #HTMLEditFormat(environmentName)#<br>
                Hello Melissa/Janice,<br><br>
                The following QA items were generated for #DateFormat(currentDate,"mmmm dd, yyyy")# for #Agencylist.Agency_Name# (#Agencylist.Agency_Login#).<br><br>
                <cfloop query="getDailyQAHeaders">
                    <cfset headerValue = getDailyQAHeaders.Header>
                    <h3 style="font-family:Arial,Helvetica,sans-serif;font-size:14px;margin-bottom:8px;">#HTMLEditFormat(headerValue)#</h3>
                    <cfquery name="getDailyQASection" dbtype="query">
                        SELECT *
                        FROM getDailyQAEmail
                        WHERE Header = <cfqueryparam value="#headerValue#" cfsqltype="cf_sql_varchar">
                        ORDER BY Pt_Last, Pt_First
                    </cfquery>
                    <table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;font-family:Arial,Helvetica,sans-serif;font-size:12px;width:100%;">
                        <tr style="background-color:##f0f0f0;">
                            <th align="left">Patient</th>
                            <th align="left">Description</th>
                            <th align="left">Assigned Employee</th>
                        </tr>
                        <cfloop query="getDailyQASection">
                            <cfset patientLast = Trim(getDailyQASection.Pt_Last)>
                            <cfset patientFirst = Trim(getDailyQASection.Pt_First)>
                            <cfset empLastName = Trim(getDailyQASection.Emp_Last)>
                            <cfset empFirstName = Trim(getDailyQASection.Emp_First)>
                            <cfoutput>
                                <tr>
                                    <td>
                                        <cfif Len(patientLast)>#HTMLEditFormat(patientLast)#</cfif>
                                        <cfif Len(patientLast) AND Len(patientFirst)>, </cfif>
                                        <cfif Len(patientFirst)>#HTMLEditFormat(patientFirst)#</cfif>
                                    </td>
                                    <td>#Description#</td>
                                    <td>
                                        <cfif Len(empLastName)>#HTMLEditFormat(empLastName)#</cfif>
                                        <cfif Len(empLastName) AND Len(empFirstName)>, </cfif>
                                        <cfif Len(empFirstName)>#HTMLEditFormat(empFirstName)#</cfif>
                                    </td>
                                </tr>
                            </cfoutput>
                        </cfloop>
                    </table>
                    <br>
                </cfloop>
                <i>This is an automated system notification from MyHomeCareBiz.com. Therefore, there is no unsubscribe option.</i>
                <br><br>
            </cfoutput>
        </cfmail>
    </cfif>

    <cfcatch type="any">
        <cfsavecontent variable="errorDetails">
            <cfoutput>
                An error occurred in cron_email_daily_QA.cfm for agency #Agencylist.Agency_ID# (#Agencylist.Agency_Name# / #Agencylist.Agency_Login#).<br><br>
                <strong>Message:</strong> #cfcatch.message#<br>
                <strong>Detail:</strong> #cfcatch.detail#<br>
                <strong>Stacktrace:</strong><br>
                <pre>
<cfloop array="#cfcatch.TagContext#" index="stackItem">
#HTMLEditFormat(stackItem.template)# (line #stackItem.line#)
</cfloop>
                </pre>
            </cfoutput>
        </cfsavecontent>

        <cfmail to="velmurugan@myhomecarebiz.com"
				cc = "velmurugan@myhomecarebiz.com"
                from="info@myhomecarebiz.com"
                subject="Error in cron_email_daily_QA for Agency #Agencylist.Agency_ID#"
                type="html">
            #errorDetails#
        </cfmail>
    </cfcatch>
    </cftry>
</cfloop>
<cfif CGI.REMOTE_ADDR EQ "103.143.7.161">
 <cfabort>
 </cfif>
<!--- Redirect if redirect parameter is provided --->
<cfif url.redirect NEQ ''>
    <!--- Set session variable to track last run time for cooldown --->
    <cfif isDefined("session")>
        <cfset session.lastPendingItemsRun = now()>
    </cfif>
    
    <cfif url.redirect EQ 'homenew' OR url.redirect EQ 'dashboard'>
        <cflocation url="../dashboard/index.cfm?page=dashboard" addtoken="no">
    <cfelse>
        <cflocation url="../dashboard/index.cfm?page=dashboard&cat&rpt=#url.redirect#" addtoken="no">
    </cfif>
</cfif>
