<cfcomponent displayname="AHCCCS EVV related Functions" hint="I send AHCCCS EVV Information" output="false">
    <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />

    <cffunction name="init" displayname="Initialize Component" access="public" returntype="AHCCCS" hint="I initialize and return the AHCCCS EVV object.">
        <cfreturn this>
    </cffunction>

    <!--- Helper function to mark EVV records as needing retransmission when data changes --->
    <cffunction name="markEVVForRetransmission" access="public" returntype="void">
        <cfargument name="recordType" type="string" required="true" hint="Type: patient, employee, or schedule">
        <cfargument name="recordID" type="numeric" required="true" hint="ID of the record that was modified">
        <cfargument name="agencyID" type="string" required="true">
        
        <!--- Validate inputs --->
        <cfif NOT isDefined("arguments.agencyID") OR len(trim(arguments.agencyID)) EQ 0>
            <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: ERROR - agencyID is missing or empty for recordType: #arguments.recordType#, recordID: #arguments.recordID#">
            <cfreturn>
        </cfif>
        
        <!--- Agency_ID must be an integer (integer column in EVV table) --->
        <cfset agencyIDTrim = trim(arguments.agencyID)>
        <cfif NOT len(agencyIDTrim) OR NOT isNumeric(agencyIDTrim)>
            <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: ERROR - agencyID must be numeric. Provided: '#arguments.agencyID#' (recordType: #arguments.recordType#, recordID: #arguments.recordID#)">
            <cfreturn>
        </cfif>
        <cfset agencyIDInt = int(agencyIDTrim)>
        
        <cftry>
            <cfif recordType EQ "patient">
                <!--- First, check what EVV records exist for this patient --->
                <cfquery name="checkEVVRecords" datasource="#Application.DataSrc#">
                    SELECT EVV_ID, San_status, API_Type, Agency_ID
                    FROM #Request.prefix_db_lookup#.EVV
                    WHERE Patient_ID = <cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
                    AND Agency_ID = <cfqueryparam value="#agencyIDInt#" cfsqltype="cf_sql_integer">
                    AND API_Type IN ('visits', 'clients')
                    AND status = 0
                </cfquery>
                
                <!--- Log all found records with their statuses --->
                <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: Found #checkEVVRecords.recordcount# EVV records for Patient #recordID#, Agency_ID: #agencyIDInt#">
                <cfloop query="checkEVVRecords">
                    <cflog file="AHCCCS_EVV" text="  - EVV_ID: #EVV_ID#, API_Type: #API_Type#, Status: '#San_status#', Agency_ID: '#Agency_ID#'">
                </cfloop>
                
                <!--- Update EVV status for all client records related to this patient --->
                <cfquery name="updateEVVStatus" datasource="#Application.DataSrc#" result="updateResult">
                    UPDATE #Request.prefix_db_lookup#.EVV
                    SET San_status = 'Data Changed - Retransmission Required',
                        Date_Update = NOW()
                    WHERE Patient_ID = <cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
                    AND Agency_ID = <cfqueryparam value="#agencyIDInt#" cfsqltype="cf_sql_integer">
                    AND API_Type = 'clients'
                    AND status = 0
                    AND (
                        (San_status IS NOT NULL AND UPPER(San_status) LIKE '%SUCCESS%')
                        OR (San_status IS NOT NULL AND UPPER(San_status) LIKE '%TRANSMITTED%')
                        OR (San_status IS NOT NULL AND UPPER(San_status) LIKE '%TRANSACTION RECEIVED%')
                        OR (San_status IS NOT NULL AND UPPER(San_status) LIKE '%DATA CHANGED%')
                        OR San_status = ''
                        OR San_status IS NULL
                    )
                    AND (
                        San_status IS NULL
                        OR (
                            UPPER(San_status) NOT LIKE '%FAILED%'
                            AND UPPER(San_status) NOT LIKE '%ERROR%'
                            AND UPPER(San_status) NOT LIKE '%REJECTED%'
                        )
                    )
                </cfquery>
                <cfset rowsAffected = updateResult.recordcount>
                
                <!--- Log the update result - use recordcount from result struct for UPDATE queries --->
                <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: Updated #rowsAffected# client EVV records for Patient #recordID#. Agency_ID: #agencyIDInt#">
                
                <!--- If no rows were updated, try a more permissive update (update all except clear errors) --->
                <cfif rowsAffected EQ 0 AND checkEVVRecords.recordcount GT 0>
                    <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: WARNING - No client records updated with restrictive WHERE clause. Trying permissive update...">
                        <cfquery name="updateEVVStatusPermissive" datasource="#Application.DataSrc#" result="updatePermissiveResult">
                            UPDATE #Request.prefix_db_lookup#.EVV
                            SET San_status = 'Data Changed - Retransmission Required',
                                Date_Update = NOW()
                            WHERE Patient_ID = <cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
                            AND Agency_ID = <cfqueryparam value="#agencyIDInt#" cfsqltype="cf_sql_integer">
                        AND API_Type = 'clients'
                        AND status = 0
                        AND (
                            San_status IS NULL
                            OR San_status = ''
                            OR (San_status IS NOT NULL AND UPPER(San_status) NOT LIKE '%FAILED%' AND UPPER(San_status) NOT LIKE '%ERROR%' AND UPPER(San_status) NOT LIKE '%REJECTED%')
                        )
                    </cfquery>
                    <cfset permissiveRowsAffected = updatePermissiveResult.recordcount>
                    <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: Permissive update affected #permissiveRowsAffected# client records for Patient #recordID#">
                </cfif>             
            <cfelseif recordType EQ "employee">
                <!--- First, check what EVV records exist for this employee --->
                <cfquery name="checkEmployeeEVVRecords" datasource="#Application.DataSrc#">
                    SELECT EVV_ID, San_status, API_Type, Agency_ID
                    FROM #Request.prefix_db_lookup#.EVV
                    WHERE Emp_ID = <cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
                    AND Agency_ID = <cfqueryparam value="#agencyIDInt#" cfsqltype="cf_sql_integer">
                    AND API_Type IN ('employee')
                    AND status = 0
                </cfquery>
                
                <!--- Log all found records with their statuses --->
                <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: Found #checkEmployeeEVVRecords.recordcount# EVV records for Employee #recordID#, Agency_ID: #agencyIDInt#">
                <cfloop query="checkEmployeeEVVRecords">
                    <cflog file="AHCCCS_EVV" text="  - EVV_ID: #EVV_ID#, API_Type: #API_Type#, Status: '#San_status#', Agency_ID: '#Agency_ID#'">
                </cfloop>
                
                <!--- Update EVV status for all employee records --->
                <cfquery name="updateEmployeeEVVStatus" datasource="#Application.DataSrc#" result="updateEmpResult">
                    UPDATE #Request.prefix_db_lookup#.EVV
                    SET San_status = 'Data Changed - Retransmission Required',
                        Date_Update = NOW()
                    WHERE Emp_ID = <cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
                    AND Agency_ID = <cfqueryparam value="#agencyIDInt#" cfsqltype="cf_sql_integer">
                    AND API_Type = 'employee'
                    AND status = 0
                    AND (
                        (San_status IS NOT NULL AND UPPER(San_status) LIKE '%SUCCESS%')
                        OR (San_status IS NOT NULL AND UPPER(San_status) LIKE '%TRANSMITTED%')
                        OR (San_status IS NOT NULL AND UPPER(San_status) LIKE '%TRANSACTION RECEIVED%')
                        OR (San_status IS NOT NULL AND UPPER(San_status) LIKE '%DATA CHANGED%')
                        OR San_status = ''
                        OR San_status IS NULL
                    )
                    AND (
                        San_status IS NULL
                        OR (
                            UPPER(San_status) NOT LIKE '%FAILED%'
                            AND UPPER(San_status) NOT LIKE '%ERROR%'
                            AND UPPER(San_status) NOT LIKE '%REJECTED%'
                        )
                    )
                </cfquery>
                
                <cfset empRowsAffected = updateEmpResult.recordcount>
                <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: Updated #empRowsAffected# employee EVV records for Employee #recordID#">
                
                <!--- If no rows were updated, try a more permissive update --->
                <cfif empRowsAffected EQ 0 AND checkEmployeeEVVRecords.recordcount GT 0>
                    <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: WARNING - No employee records updated with restrictive WHERE clause. Trying permissive update...">
                    <cfquery name="updateEmployeeEVVStatusPermissive" datasource="#Application.DataSrc#" result="updateEmpPermissiveResult">
                        UPDATE #Request.prefix_db_lookup#.EVV
                        SET San_status = 'Data Changed - Retransmission Required',
                            Date_Update = NOW()
                        WHERE Emp_ID = <cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
                        AND Agency_ID = <cfqueryparam value="#agencyIDInt#" cfsqltype="cf_sql_integer">
                        AND API_Type = 'employee'
                        AND status = 0
                        AND (
                            San_status IS NULL
                            OR San_status = ''
                            OR (San_status IS NOT NULL AND UPPER(San_status) NOT LIKE '%FAILED%' AND UPPER(San_status) NOT LIKE '%ERROR%' AND UPPER(San_status) NOT LIKE '%REJECTED%')
                        )
                    </cfquery>
                    <cfset empPermissiveRowsAffected = updateEmpPermissiveResult.recordcount>
                    <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: Permissive update affected #empPermissiveRowsAffected# employee records for Employee #recordID#">
                </cfif>
                
            <cfelseif recordType EQ "schedule">
                <!--- Update EVV status for this specific visit --->
                <cfquery name="updateScheduleEVVStatus" datasource="#Application.DataSrc#" result="updateSchedResult">
                    UPDATE #Request.prefix_db_lookup#.EVV
                    SET San_status = 'Data Changed - Retransmission Required',
                        Date_Update = NOW()
                    WHERE Schedule_ID = <cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
                    AND Agency_ID = <cfqueryparam value="#agencyIDInt#" cfsqltype="cf_sql_integer">
                    AND API_Type = 'visits'
                    AND status = 0
                    AND (
                        (San_status IS NOT NULL AND UPPER(San_status) LIKE '%SUCCESS%')
                        OR (San_status IS NOT NULL AND UPPER(San_status) LIKE '%TRANSMITTED%')
                        OR (San_status IS NOT NULL AND UPPER(San_status) LIKE '%TRANSACTION RECEIVED%')
                        OR (San_status IS NOT NULL AND UPPER(San_status) LIKE '%DATA CHANGED%')
                        OR San_status = ''
                        OR San_status IS NULL
                    )
                    AND (
                        San_status IS NULL
                        OR (
                            UPPER(San_status) NOT LIKE '%FAILED%'
                            AND UPPER(San_status) NOT LIKE '%ERROR%'
                            AND UPPER(San_status) NOT LIKE '%REJECTED%'
                        )
                    )
                </cfquery>
                
                <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: Updated #updateSchedResult.recordcount# EVV record for Schedule #recordID#. Rows affected: #updateSchedResult.recordcount#">
                
                <!--- Reset EVV_Reason_Code_ID in pSchedules to force clinician to enter NEW reason code for NEW update --->
                <cfquery name="resetReasonCode" datasource="#Application.DataSrc#">
                    UPDATE #Request.prefix_db_agency#.pSchedules
                    SET EVV_Reason_Code_ID = NULL
                    WHERE Schedule_ID = <cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
                    AND Status = 0
                </cfquery>
                <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: Reset EVV_Reason_Code_ID to NULL for Schedule #recordID# to require new reason code">
                
                <!--- Deactivate old EVV_Update_Log entries and clear Change_Memo to force NEW memo entry --->
                <cfquery name="deactivateOldLogs" datasource="#Application.DataSrc#">
                    UPDATE #Request.prefix_db_lookup#.EVV_Update_Log
                    SET Status = 1,
                        Change_Memo = NULL
                    WHERE Schedule_ID = <cfqueryparam value="#recordID#" cfsqltype="cf_sql_integer">
                    AND Status = 0
                </cfquery>
                <cflog file="AHCCCS_EVV" text="markEVVForRetransmission: Deactivated old EVV_Update_Log entries and cleared Change_Memo for Schedule #recordID#">
            </cfif>
            
            <cfcatch>
                <!--- Log detailed error information --->
                <cflog file="AHCCCS_EVV" text="ERROR in markEVVForRetransmission - recordType: #arguments.recordType#, recordID: #arguments.recordID#, agencyID: #arguments.agencyID#">
                <cflog file="AHCCCS_EVV" text="  Error Message: #cfcatch.message#">
                <cflog file="AHCCCS_EVV" text="  Error Detail: #cfcatch.detail#">
                <cflog file="AHCCCS_EVV" text="  Error Type: #cfcatch.type#">
                <cfif structKeyExists(cfcatch, "sqlState")>
                    <cflog file="AHCCCS_EVV" text="  SQL State: #cfcatch.sqlState#">
                </cfif>
                <cfif structKeyExists(cfcatch, "nativeErrorCode")>
                    <cflog file="AHCCCS_EVV" text="  Native Error Code: #cfcatch.nativeErrorCode#">
                </cfif>
            </cfcatch>
        </cftry>
    </cffunction>

    <cffunction name="create_client" access="remote" returnFormat= "plain">
        <cfargument name="Agency_ID" required="no" hint="Agency_ID" default="#session.agencyId#">
        <cfargument name="Patient_ID" required="yes" default="0" hint="Patient_ID">
        
        <!--- Initialize LOCAL variables --->
        <cfif application.DEV EQ false>
            <!--- PROD subscription keys --->
            <cfset LOCAL.subscription_key_primary = "3f11f04e0fd74ad39c77c8cacbfef240">
            <cfset LOCAL.subscription_key_secondary = "3710f5d7890241d3beb7181e2b506f8b">
        <cfelse>
            <!--- DEV subscription keys --->
        <cfset LOCAL.subscription_key_primary = "b3446ef5e2ce497dbc9da4007b574c8b">
        <cfset LOCAL.subscription_key_secondary = "1c88925161e94f4cae914d91ad0c077c">
        </cfif>
        <cfset LOCAL.account = "a2f47e6e-5f6b-0e9b-c2c6-e003c1b48ac9">
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        <!--- Use server name in email subject --->
        <cfset envLabel = #Application.ServerName# />
         
        <!--- Get agency settings from database --->
        <cfquery name="getagency" datasource="#Application.DataSrc#">
            SELECT * FROM  #Request.prefix_db_lookup#.Agency
            WHERE Agency_ID = '#session.agencyId#'
            <cfif application.DEV EQ false>  
                AND EVV_prod_username IS NOT NULL
                AND EVV_prod_password IS NOT NULL
            <cfelse>
                AND EVV_username IS NOT NULL
                AND EVV_password IS NOT NULL
            </cfif>
        </cfquery>
        <cfif getagency.recordcount gt 0>
            <cfif application.DEV EQ false>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
            <cfelse>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
            </cfif>
        </cfif>
        
        <!--- Decrypt Patient_ID --->
        <cfset arguments.Patient_ID = decrypt(#arguments.Patient_ID#,#application.enckey#,"AES","Hex") />
        
        <!--- Set API endpoints based on environment --->
        <cfif application.DEV EQ false>
            <cfset LOCAL.ClientEndpoint = "https://si-api.azahcccs.gov/evv/aggregation/v1/clients/upload?key=" & LOCAL.subscription_key_primary>
        <cfelse>
            <cfset LOCAL.ClientEndpoint = "https://si-api.azahcccs.gov/test/evv/aggregation/v1/clients/upload?key=" & LOCAL.subscription_key_primary>
        </cfif>

        <!--- Get patient information --->
        <cfquery name="getpatient" datasource="#Application.DataSrc#">
            SELECT p.*, a.Agency_Name, a.Natl_Provider_ID 
            FROM #Request.prefix_db_agency#.pPatients p
            LEFT JOIN #Request.prefix_db_lookup#.Agency a ON p.Loc_ID = a.Agency_ID
            WHERE p.Patient_ID = #Patient_ID# AND p.Status IN (0,1,4)
        </cfquery>
        
        <cfquery name="Getpayers" datasource="#Application.DataSrc#">
            SELECT pPayer.M0150 AS paymentsource,pPtPayer.*,pPayer.*,
            (SELECT Eligibility.Start_Date FROM #Request.prefix_db_agency#.Eligibility 
            WHERE Eligibility.Patient_ID = pPtPayer.Patient_ID
            AND Eligibility.PtPayer_ID = pPtPayer.PtPayer_ID
            AND Eligibility.Status = 0 ORDER BY Start_Date DESC LIMIT 0,1) AS Start_Date
            FROM #Request.prefix_db_agency#.pPtPayer
            JOIN #Request.prefix_db_agency#.pPayer ON pPtPayer.Payer_ID = pPayer.Pay_ID
            WHERE pPtPayer.Patient_ID = #Patient_ID# AND pPtPayer.Status = 0 AND pPayer.Status = 0
            ORDER BY pPtPayer.PtPayer_ID DESC LIMIT 1
        </cfquery>

        <cfif getpatient.recordcount gt 0>
            <cfoutput query="getpatient">
                <!--- Generate unique sequence ID with datetime format YYYYMMDDHHMMSS + 2 digits (max 16 digits) --->
                <cfset Seq_ID = DateFormat(now(), "yyyymmdd") & TimeFormat(now(), "HHmmss") & Right(GetTickCount(), 2) />
                
                <!--- Set ClientMedicaidID from payers and format it properly --->
                <cfif Getpayers.recordcount gt 0>
                    <cfset ClientMedicaidID = #Getpayers.Sub_HIC#>
                <cfelse>
                    <cfset ClientMedicaidID = "#Pt_Agy_ID#">
                </cfif>
                
                <!--- Ensure we have a valid value and format it properly --->
                <cfif ClientMedicaidID EQ "" OR ClientMedicaidID EQ "0">
                    <cfset ClientMedicaidID = "#Pt_Agy_ID#">
                </cfif>
                <cfset FormattedMedicaidID = "A" & Right("00000000" & Replace(ClientMedicaidID, "A", "", "all"), 8)>
                <!--- Validate and format email address --->
                <cfif Email EQ "" OR Email EQ "NULL" OR NOT IsValid("email", Email)>
                    <cfset ValidEmail = "test@myhomecarebiz.com">
                <cfelse>
                <cfset ValidEmail = Email>
                </cfif>
                
                <!--- Split address into two lines if longer than 30 characters --->
                <cfset TrimmedStreet = Trim(Pt_Street)>
                <cfif Len(TrimmedStreet) GT 30>
                    <cfset AddressLine1 = Left(TrimmedStreet, 30)>
                    <cfset AddressLine2 = Mid(TrimmedStreet, 31, Len(TrimmedStreet) - 30)>
                <cfelse>
                    <cfset AddressLine1 = TrimmedStreet>
                    <cfset AddressLine2 = "">
                </cfif>

                <!--- Normalize ZIP for AHCCCS: digits only, use 5-digit ZIP (ZIP+4 is reduced to base ZIP) --->
                <cfset RawClientZip = Trim(Pt_Zip)>
                <cfset FormattedClientZip = Left(REReplace(RawClientZip, "[^0-9]", "", "all"), 9)>
                <cfif Len(FormattedClientZip) EQ 0>
                    <cfset FormattedClientZip = "00000">
                </cfif>
                
                <!--- Create client JSON payload --->
                <cfset clientData = {
                    "ProviderIdentification": {
                        "ProviderQualifier": "MedicaidID",
                        "ProviderID": "#LOCAL.ProviderID#"
                    },
                    "ClientID": "#FormattedMedicaidID#",
                    "ClientFirstName": "#Pt_First#",
                    "ClientMiddleInitial": "#Left(Pt_Middle, 1)#",
                    "ClientLastName": "#Pt_Last#",
                    "ClientQualifier": "ClientCustomID",
                    "ClientMedicaidID": "#FormattedMedicaidID#",
                    "ClientIdentifier": "#FormattedMedicaidID#",
                    "MissingMedicaidID": "false",
                    "SequenceID": #Seq_ID#,
                    "ClientCustomID": "#FormattedMedicaidID#",
                    "ClientOtherID": "#FormattedMedicaidID#",
                    "ClientSSN": "999999999",
                    "ClientTimezone": "US/Arizona",
                    "Coordinator": "T51",
                    "ProviderAssentContPlan": "Yes",
                    "ClientPayerInformation": javaCast("null", ""),
                    "ClientAddress": [
                        {
                            "ClientAddressType": "Home",
                            "ClientAddressIsPrimary": true,
                            "ClientAddressLine1": "#AddressLine1#",
                            "ClientAddressLine2": "#AddressLine2#",
                            "ClientCounty": "USA",
                            "ClientCity": "#Pt_City#",
                            "ClientState": "#Pt_State#",
                            "ClientZip": "#FormattedClientZip#",
                            "ClientAddressLongitude": javaCast("null", ""),
                            "ClientAddressLatitude": javaCast("null", "")
                        }
                    ],
                    "ClientPhone": [
                        {
                            "ClientPhoneType": "Home",
                            "ClientPhone": "#Replace(Pt_Phone, '-', '', 'all')#"
                        }
                    ],
                    "ClientDesignee": [
                        {
                            "ClientDesigneeFirstName": "#Pt_First#",
                            "ClientDesigneeLastName": "#Pt_Last#",
                            "ClientDesigneeEmail": "#ValidEmail#",
                            "ClientDesigneeStatus": "02",
                            "ClientDesigneeStartDate": "#DateFormat(now(), 'yyyy-mm-dd')#",
                            "ClientDesigneeEndDate": "2999-12-31",
                            "ClientDesigneeRelationship": "Other"
                        }
                    ]
                }>

                <!--- Convert to JSON array like Arizona.cfc --->
                <cfset Request.stFields = [clientData]>
                <cfset jsonPayload = SerializeJSON(Request.stFields)>
                <br>
                 <!--- Send HTTP request to AHCCCS API --->
                <cfhttp url="#LOCAL.ClientEndpoint#" method="POST" timeout="30">
                    <cfhttpparam type="header" name="Content-Type" value="application/json">
                    <cfhttpparam type="header" name="Accept" value="application/json">
                    <cfhttpparam type="header" name="account" value="#LOCAL.account#">
                    <cfhttpparam type="body" value="#jsonPayload#">
                </cfhttp>
                 <!--- Log response --->
                 <cflog file="AHCCCS_Client" text="Response: #cfhttp.StatusCode# - #cfhttp.FileContent#">
                <cfif cfhttp.StatusCode EQ "200 OK" OR cfhttp.StatusCode EQ "200" OR cfhttp.StatusCode EQ "201">
                    <!--- Parse response to get UUID --->
                    <cfset responseData = DeserializeJSON(cfhttp.FileContent)>
                    <cfset UUID = responseData.id />
                    <cfset api_return_status = responseData.status />
                    
                    <!--- Extract reason from response data if available --->
                    <cfif structKeyExists(responseData, "data") AND isStruct(responseData.data) AND structKeyExists(responseData.data, "reason")>
                        <cfset api_return_status = responseData.data.reason />
                    </cfif>
                    
                    <!--- Set initial status to "Transmitted - Initial submission" instead of API status --->
                    <!--- Status will be updated to actual status (Transaction Received, etc) when check_client_status is called --->
                    <cfset return_status = "Transmitted - Initial submission">
                    
                    <!--- Check if status is FAILED --->
                    <cfif api_return_status EQ "FAILED">
                        <!--- Parse error response for FAILED status --->
                        <cfset error_status = "">
                        
                        <cfif structKeyExists(responseData, "data") AND isArray(responseData.data)>
                            <cfloop array="#responseData.data#" index="item">
                                <cfif structKeyExists(item, "ErrorMessage") AND NOT isNull(item.ErrorMessage)>
                                    <cfset errorList = listToArray(item.ErrorMessage, "|")>
                                    <cfloop array="#errorList#" index="err">
                                        <cfif len(trim(err)) GT 0>
                                            <cfset error_status = error_status & trim(err) & "<br>" />
                                        </cfif>
                                    </cfloop>
                                </cfif>
                            </cfloop>
                        </cfif>
                        
                        <cfif error_status EQ "">
                            <cfset error_status = "Client upload failed - no error details available">
                        </cfif>
                        
                        <!--- Send failed email notification with request and response --->
                        <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Client Upload Failed - #Pt_First#, #Pt_Last# (#Patient_ID#)" type="html">
                            <h3>AHCCCS Client Upload Failed</h3>
                            <p><strong>Patient Information:</strong></p>
                            <ul>
                                <li><strong>Name:</strong> #Pt_First# #Pt_Last#</li>
                                <li><strong>Patient ID:</strong> #Patient_ID#</li>
                                <li><strong>Agency ID:</strong> #session.agencyid#</li>
                                <li><strong>Medicaid ID:</strong> #FormattedMedicaidID#</li>
                                <li><strong>Sequence ID:</strong> #Seq_ID#</li>
                            </ul>
                            
                            <p><strong>Error Details:</strong></p>
                            <div style="background-color: ##ffe6e6; padding: 10px; border-left: 4px solid ##ff0000; margin: 10px 0;">
                                #error_status#
                            </div>
                            
                            <p><strong>API Request Payload:</strong></p>
                            <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#jsonPayload#</pre>
                            
                            <p><strong>API Response Data:</strong></p>
                            <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#cfhttp.FileContent#</pre>
                            
                            <p><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</p>
                        </cfmail>
                        
                        <cfreturn error_status>
                    <cfelse>
                        <!--- Status is SUCCESS, insert into EVV table --->
                        <cfquery name="INSERT_EVV" datasource="#Application.DataSrc#" result="evvResult">
                            INSERT INTO #Request.prefix_db_lookup#.EVV 
                            (UUID, Seq_ID, San_status, API_type, Agency_ID, Patient_ID, Emp_ID, Schedule_ID, Date_Create, Created_by)
                            VALUES
                            ('#UUID#', '#Seq_ID#','#return_status#', 'clients', '#session.agencyid#', #Patient_ID#, 0, 0, #now()#, #session.employeeid#)
                        </cfquery>
                        
                        <!--- Log to EVV_Update_Log --->
                        <cfquery name="INSERT_EVV_LOG" datasource="#Application.DataSrc#">
                            INSERT INTO #Request.prefix_db_lookup#.EVV_Update_Log (
                                Schedule_ID,
                                Agency_ID,
                                EVV_ID,
                                Date_Updated,
                                Change_Memo,
                                Changed_By,
                                Changed_By_Email,
                                Status
                            ) VALUES (
                                0,
                                <cfqueryparam value="#session.agencyid#" cfsqltype="cf_sql_integer">,
                                <cfqueryparam value="#evvResult.GENERATED_KEY#" cfsqltype="cf_sql_integer">,
                                <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                                <cfqueryparam value="Client data transmitted to AHCCCS - Patient ID: #Patient_ID# - Status: #return_status#" cfsqltype="cf_sql_longvarchar">,
                                <cfqueryparam value="#session.employeeid#" cfsqltype="cf_sql_integer">,
                                <cfqueryparam value="system@powerpathemr.com" cfsqltype="cf_sql_varchar">,
                                0
                            )
                        </cfquery>
                        
                         <!--- Send success email notification --->
                        <cfmail to="#sendto_email#" from="info@myhomecarebiz.com" subject="#envLabel# AHCCCS Client Upload Success - #Pt_First#, #Pt_Last# (#Patient_ID#)" type="html">
                            <h3>AHCCCS Client Upload Successful</h3>
                            <p><strong>Patient Information:</strong></p>
                            <ul>
                                <li><strong>Name:</strong> #Pt_First# #Pt_Last#</li>
                                <li><strong>Patient ID:</strong> #Patient_ID#</li>
                                <li><strong>Agency ID:</strong> #session.agencyid#</li>
                                <li><strong>Medicaid ID:</strong> #FormattedMedicaidID#</li>
                                <li><strong>Sequence ID:</strong> #Seq_ID#</li>
                            </ul>
                            
                            <p><strong>API Response:</strong></p>
                            <ul>
                                <li><strong>UUID:</strong> #UUID#</li>
                                <li><strong>API Status:</strong> #api_return_status#</li>
                                <li><strong>Initial Status (in system):</strong> #return_status#</li>
                                <li><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</li>
                            </ul>
                            
                            <p><strong>API Request Payload:</strong></p>
                            <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#jsonPayload#</pre>
                            
                            <p><strong>API Response Data:</strong></p>
                            <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#SerializeJSON(responseData)#</pre>
                            
                            <p>The client has been successfully uploaded to AHCCCS EVV system with initial status "Transmitted - Initial submission". Use check status to get the current transaction status.</p>
                            
                            <p>The client has been successfully uploaded to AHCCCS EVV system.</p>
                        </cfmail>
                        
                        <cfreturn "Client uploaded successfully">
                    </cfif>
                <cfelse>
                    <!--- Parse error response like Arizona.cfc --->
                    <cfset responseData = DeserializeJSON(cfhttp.FileContent)>
                    <cfset return_status = "">
                    
                    <cfif structKeyExists(responseData, "data") AND isArray(responseData.data)>
                        <cfloop array="#responseData.data#" index="item">
                            <cfif structKeyExists(item, "ErrorMessage") AND NOT isNull(item.ErrorMessage)>
                                <cfset errorList = listToArray(item.ErrorMessage, "|")>
                                <cfloop array="#errorList#" index="err">
                                    <cfif len(trim(err)) GT 0>
                                        <cfset return_status = return_status & trim(err) & "<br>" />
                                    </cfif>
                                </cfloop>
                            </cfif>
                        </cfloop>
                    </cfif>
                    <cfif return_status EQ "">
                        <cfset return_status = "Error uploading client">
                    </cfif>
                    
                    <!--- Send error email notification with request and response --->
                    <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Client Upload Error - #Pt_First#, #Pt_Last# (#Patient_ID#)" type="html">
                        <h3>AHCCCS Client Upload Error</h3>
                        <p><strong>Patient Information:</strong></p>
                        <ul>
                            <li><strong>Name:</strong> #Pt_First# #Pt_Last#</li>
                            <li><strong>Patient ID:</strong> #Patient_ID#</li>
                            <li><strong>Agency ID:</strong> #session.agencyid#</li>
                            <li><strong>Medicaid ID:</strong> #FormattedMedicaidID#</li>
                            <li><strong>Sequence ID:</strong> #Seq_ID#</li>
                        </ul>
                        
                        <p><strong>Error Details:</strong></p>
                        <div style="background-color: ##ffe6e6; padding: 10px; border-left: 4px solid ##ff0000; margin: 10px 0;">
                            #return_status#
                        </div>
                        
                        <p><strong>HTTP Status Code:</strong> #cfhttp.StatusCode#</p>
                        
                        <p><strong>API Request Payload:</strong></p>
                        <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#jsonPayload#</pre>
                        
                        <p><strong>API Response Data:</strong></p>
                        <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#cfhttp.FileContent#</pre>
                        
                        <p><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</p>
                    </cfmail>
                    
                    <cfreturn return_status>
                </cfif>
            </cfoutput>
        <cfelse>
            <cfreturn "Patient not found">
        </cfif>
    </cffunction>

    <cffunction name="create_employee" access="remote" returnFormat= "plain">
        <cfargument name="Agency_ID" required="no" hint="Agency_ID" default="#session.agencyId#">
        <cfargument name="Emp_ID" required="yes" default="0" hint="Emp_ID">

        <cfset Employee_ID  = decrypt(#arguments.Emp_ID#,#application.enckey#,"AES","Hex") />
        
        <!--- Initialize LOCAL variables --->
        <cfif application.DEV EQ false>
            <!--- PROD subscription keys --->
            <cfset LOCAL.subscription_key_primary = "3f11f04e0fd74ad39c77c8cacbfef240">
            <cfset LOCAL.subscription_key_secondary = "3710f5d7890241d3beb7181e2b506f8b">
        <cfelse>
            <!--- DEV subscription keys --->
        <cfset LOCAL.subscription_key_primary = "b3446ef5e2ce497dbc9da4007b574c8b">
        <cfset LOCAL.subscription_key_secondary = "1c88925161e94f4cae914d91ad0c077c">
        </cfif>
        <cfset LOCAL.account = "a2f47e6e-5f6b-0e9b-c2c6-e003c1b48ac9">
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- Use server name in email subject --->
        <cfset envLabel = #Application.ServerName# />
        
        <!--- Get agency settings from database --->
        <cfquery name="getagency" datasource="#Application.DataSrc#">
            SELECT * FROM  #Request.prefix_db_lookup#.Agency
            WHERE Agency_ID = '#session.agencyId#'
        <cfif application.DEV EQ false>
                AND EVV_prod_username IS NOT NULL
                AND EVV_prod_password IS NOT NULL
        <cfelse>
                AND EVV_username IS NOT NULL
                AND EVV_password IS NOT NULL
            </cfif>
        </cfquery>
        <cfif getagency.recordcount gt 0>
            <cfif application.DEV EQ false>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
            <cfelse>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
            </cfif>
        </cfif>
       
        <cftry> 
             <cfif application.DEV EQ false>
                <cfset LOCAL.AuthorizationEndpoint = "https://si-api.azahcccs.gov/evv/aggregation/v1/employees/upload?key=" & LOCAL.subscription_key_primary>
            <cfelse>
                <cfset LOCAL.AuthorizationEndpoint = "https://si-api.azahcccs.gov/test/evv/aggregation/v1/employees/upload?key=" & LOCAL.subscription_key_primary>
            </cfif>
            <cfquery  name="GetEmp"  datasource="#Application.DataSrc#">
                SELECT *   FROM #Request.prefix_db_lookup#.pEmployee 
                WHERE  Status = 0 AND Emp_ID = #Employee_ID#
        </cfquery>
            <cfset currentDate = Now()>
            <cfset Todaydate = DateFormat(currentDate, "yyyy-mm-dd")>
            <cfset formattedDateTime = DateFormat(currentDate, "yyyy-mm-dd") & "T" & TimeFormat(currentDate, "HH:mm:ss") & "Z">
            <cfset Previous_Day = DateAdd("d", -1, Now())>
            <cfset Emp_SSN = "000099999" />
             <cfset EmployeeIdentifier =  #RIGHT(Emp_SSN,5)# & #LEFT(GetEmp.Emp_Last,4)#>
            <cfif GetEmp.Emp_SSN NEQ ''>
                <cfset Emp_SSN = #RIGHT(GetEmp.Emp_SSN,5)#>
                <cfset Emp_SSN = #RIGHT(GetEmp.Emp_SSN,5)#>
                <cfset EmployeeIdentifier =  repeatString("0", 5 - len(Emp_SSN)) & #LEFT(GetEmp.Emp_Last,4)#>
            </cfif> 
            <cfset EmployeeManagerEmail = listFirst(getagency.Agency_Contact_Email) />

             <!--- Generate unique sequence ID with datetime format YYYYMMDDHHMMSS + 2 digits (max 16 digits) --->
                <cfset Seq_ID = DateFormat(now(), "yyyymmdd") & TimeFormat(now(), "HHmmss") & Right(GetTickCount(), 2) />
                
            <!--- Set EmployeeEndDate based on Date_Terminate --->
            <cfset EmployeeEndDate = DateFormat(DateAdd('yyyy', 1, now()), 'yyyy-mm-dd')>
            <cfif GetEmp.Date_Terminate NEQ '' AND GetEmp.Date_Terminate NEQ '0000-00-00'>
                <cfset EmployeeEndDate = DateFormat(GetEmp.Date_Terminate, 'yyyy-mm-dd')>
            </cfif>

            <cfset Request.stFields =
                    [{
                    "ProviderIdentification": {
                    "ProviderQualifier": "MedicaidID",
                    "ProviderID": "#LOCAL.ProviderID#"
                    },
                    "EmployeeQualifier": "EmployeeSSN",
                    "EmployeeIdentifier": "#GetEmp.Emp_SSN#",
                    "EmployeeOtherID": "#GetEmp.Emp_SSN#",
                    "SequenceID": #Seq_ID#,
                    "EmployeeSSN": "#GetEmp.Emp_SSN#",
                    "EmployeeLastName": "#GetEmp.Emp_Last#",
                    "EmployeeFirstName": "#GetEmp.Emp_First#",
                    "EmployeeEmail": "#GetEmp.Emp_Email#",
                    "EmployeeManagerEmail": "#getagency.Agency_Contact_Email#",
                    "EmployeeAPI": "null",
                    "EmployeePosition": "#GetEmp.Skill_1#",
                    "EmployeeHireDate": "#DateFormat(now(), 'yyyy-mm-dd')#",
                    "EmployeeEndDate": "#EmployeeEndDate#",
                    "ErrorCode": "null",
                    "ErrorMessage": "null"
                    }]

            > 
            <cfset LOCAL.RestStartTime  = GetTickCount()>
            <cfhttp 
                url         = "#LOCAL.AuthorizationEndpoint#"
                method      = "POST" 
                timeout     =  "100"
                result      = "httpEVVResponse">
                <cfhttpparam name="Content-Type"  type="HEADER" value="application/json">
                <cfhttpparam name="Accept" type="HEADER" value="application/json">
                <cfhttpparam name="account" type="HEADER" value="#LOCAL.account#">
                <cfhttpparam type="body" value="#serializeJSON(Request.stFields)#">
                </cfhttp>
            <cfset LOCAL.RestEndTime = GetTickCount()>
            <cfset LOCAL.returnFaxSendResult.FaxProcessTime = NumberFormat((LOCAL.RestEndTime - LOCAL.RestStartTime)/1000,'__.___')>
            <cfset return_status =  "failure">
           
            <cfset structureData  = DeserializeJSON(httpEVVResponse.Filecontent)>
           
            <cfif httpEVVResponse.responseHeader.Status_Code contains '200'>              
            <cfset api_return_status = structureData.status >
            <cfset UUID = structureData.id />
            
            <!--- Extract reason from response data if available --->
            <cfif structKeyExists(structureData, "data") AND isStruct(structureData.data) AND structKeyExists(structureData.data, "reason")>
                <cfset api_return_status = structureData.data.reason />
            </cfif>
            
            <!--- Set initial status to "Transmitted - Initial submission" instead of API status --->
            <!--- Status will be updated to actual status (Transaction Received, etc) when check_employee_status is called --->
            <cfset return_status = "Transmitted - Initial submission">
            
            <cfif api_return_status EQ 'SUCCESS' OR FindNoCase('Transaction Received', api_return_status) GT 0>
                <cfmail to="#sendto_email#" from="info@myhomecarebiz.com" subject="#envLabel# AHCCCS Employee Upload Success - #GetEmp.Emp_First#, #GetEmp.Emp_Last# (#GetEmp.Emp_ID#)" type="html">
                    <h3>AHCCCS Employee Upload Successful</h3>
                    <p><strong>Employee Information:</strong></p>
                    <ul>
                        <li><strong>Employee Name:</strong> #GetEmp.Emp_First# #GetEmp.Emp_Last#</li>
                        <li><strong>Employee ID:</strong> #GetEmp.Emp_ID#</li>
                        <li><strong>Employee SSN:</strong> #GetEmp.Emp_SSN#</li>
                        <li><strong>Employee Email:</strong> #GetEmp.Emp_Email#</li>
                        <li><strong>Position:</strong> #GetEmp.Skill_1#</li>
                        <li><strong>Hire Date:</strong> #DateFormat(now(), "yyyy-mm-dd")#</li>
                        <li><strong>End Date:</strong> #EmployeeEndDate#</li>
                        <li><strong>Agency ID:</strong> #session.agencyid#</li>
                        <li><strong>Sequence ID:</strong> #Seq_ID#</li>
                    </ul>
                    
                    <p><strong>API Response:</strong></p>
                    <ul>
                        <li><strong>UUID:</strong> #UUID#</li>
                        <li><strong>API Status:</strong> #api_return_status#</li>
                        <li><strong>Initial Status (in system):</strong> #return_status#</li>
                        <li><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</li>
                    </ul>
                    
                    <p><strong>API Request Payload:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#serializeJSON(Request.stFields)#</pre>
                    
                    <p><strong>API Response Data:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#SerializeJSON(structureData)#</pre>
                    
                    <p>The employee has been successfully uploaded to AHCCCS EVV system with initial status "Transmitted - Initial submission". Use check status to get the current transaction status.</p>
                    
                    <p>The employee has been successfully uploaded to AHCCCS EVV system.</p>
                </cfmail>
            <cfelse>
                <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Employee Upload Failed - #GetEmp.Emp_First#, #GetEmp.Emp_Last# (#GetEmp.Emp_ID#)" type="html">
                    <h3>AHCCCS Employee Upload Failed</h3>
                    <p><strong>Employee Information:</strong></p>
                    <ul>
                        <li><strong>Employee Name:</strong> #GetEmp.Emp_First# #GetEmp.Emp_Last#</li>
                        <li><strong>Employee ID:</strong> #GetEmp.Emp_ID#</li>
                        <li><strong>Employee SSN:</strong> #GetEmp.Emp_SSN#</li>
                        <li><strong>Employee Email:</strong> #GetEmp.Emp_Email#</li>
                        <li><strong>Position:</strong> #GetEmp.Skill_1#</li>
                        <li><strong>Hire Date:</strong> #DateFormat(now(), "yyyy-mm-dd")#</li>
                        <li><strong>End Date:</strong> #EmployeeEndDate#</li>
                        <li><strong>Agency ID:</strong> #session.agencyid#</li>
                        <li><strong>Sequence ID:</strong> #Seq_ID#</li>
                    </ul>
                    
                    <p><strong>Error Details:</strong></p>
                    <div style="background-color: ##ffe6e6; padding: 10px; border-left: 4px solid ##ff0000; margin: 10px 0;">
                        #return_status#
                    </div>
                    
                    <p><strong>API Request Payload:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#serializeJSON(Request.stFields)#</pre>
                    
                    <p><strong>API Response Data:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#httpEVVResponse.FileContent#</pre>
                    
                    <p><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</p>
                    
                    <p>The employee upload failed. Please check the error details above.</p>
                </cfmail>
            </cfif> 
                    <cfquery name="INSERT_EVV" datasource="#Application.DataSrc#" result="evvResult">
                        INSERT INTO #Request.prefix_db_lookup#.EVV 
                        (UUID, Seq_ID, San_status, API_type, Agency_ID, Patient_ID, Emp_ID, Schedule_ID, Date_Create, Created_by)
                        VALUES
                ('#UUID#', '#Seq_ID#','#return_status#', 'employee', '#session.agencyid#', 0, #GetEmp.Emp_ID#, 0, #now()#, #session.employeeid#)
                    </cfquery>
                    
                    <!--- Log to EVV_Update_Log --->
                    <cfquery name="INSERT_EVV_LOG" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_lookup#.EVV_Update_Log (
                            Schedule_ID,
                            Agency_ID,
                            EVV_ID,
                            Date_Updated,
                            Change_Memo,
                            Changed_By,
                            Changed_By_Email,
                            Status
                        ) VALUES (
                            0,
                            <cfqueryparam value="#session.agencyid#" cfsqltype="cf_sql_integer">,
                            <cfqueryparam value="#evvResult.GENERATED_KEY#" cfsqltype="cf_sql_integer">,
                            <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                            <cfqueryparam value="Employee data transmitted to AHCCCS - Emp ID: #GetEmp.Emp_ID# (#GetEmp.Emp_First# #GetEmp.Emp_Last#) - Status: #return_status#" cfsqltype="cf_sql_longvarchar">,
                            <cfqueryparam value="#session.employeeid#" cfsqltype="cf_sql_integer">,
                            <cfqueryparam value="#GetEmp.Emp_Email#" cfsqltype="cf_sql_varchar">,
                            0
                        )
                    </cfquery>
                    
                <cfelse>
            <cfset responseStruct = structureData>
            <cfset UUID = "N/A">
            <cfif httpEVVResponse.responseHeader.Status_Code NEQ '401'>
                <cfif structKeyExists(responseStruct, "data") AND isArray(responseStruct.data)>
                    <cfset return_status = "">
                    <cfloop array="#responseStruct.data#" index="item">
                        <!--- Check top-level ErrorMessage --->
                        <cfif structKeyExists(item, "ErrorMessage") AND NOT isNull(item.ErrorMessage)>
                            <cfset errorList = listToArray(item.ErrorMessage, "|")>
                            <!--- Display each error line by line --->
                            <cfoutput>
                                <cfloop array="#errorList#" index="err">
                                    <cfif len(trim(err)) GT 0>
                                        <cfset return_status = return_status & trim(err) & "<br>" />
                </cfif>
                                </cfloop>
            </cfoutput>
                        </cfif>
                    </cfloop>
        <cfelse>
                    <cfset return_status = structureData.message>
        </cfif>
        <cfelse>
                <cfset return_status = structureData.message>
        </cfif>
            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Employee Upload Error - #GetEmp.Emp_First#, #GetEmp.Emp_Last# (#GetEmp.Emp_ID#)" type="html">
                <h3>AHCCCS Employee Upload Error</h3>
                <p><strong>Employee Information:</strong></p>
                <ul>
                    <li><strong>Employee Name:</strong> #GetEmp.Emp_First# #GetEmp.Emp_Last#</li>
                    <li><strong>Employee ID:</strong> #GetEmp.Emp_ID#</li>
                    <li><strong>Employee SSN:</strong> #GetEmp.Emp_SSN#</li>
                    <li><strong>Employee Email:</strong> #GetEmp.Emp_Email#</li>
                    <li><strong>Position:</strong> #GetEmp.Skill_1#</li>
                    <li><strong>Hire Date:</strong> #DateFormat(now(), "yyyy-mm-dd")#</li>
                    <li><strong>End Date:</strong> #EmployeeEndDate#</li>
                    <li><strong>Agency ID:</strong> #session.agencyid#</li>
                    <li><strong>Sequence ID:</strong> #Seq_ID#</li>
                </ul>
                
                <p><strong>Error Details:</strong></p>
                <div style="background-color: ##ffe6e6; padding: 10px; border-left: 4px solid ##ff0000; margin: 10px 0;">
                    #return_status#
                </div>
                
                <p><strong>API Request Payload:</strong></p>
                <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#serializeJSON(Request.stFields)#</pre>
                
                <p><strong>API Response Data:</strong></p>
                <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#httpEVVResponse.FileContent#</pre>
                
                <p><strong>HTTP Response Code:</strong> #httpEVVResponse.responseHeader.Status_Code#</p>
                <p><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</p>
                
                <p>The employee upload encountered an error. Please check the error details above.</p>
            </cfmail>
        </cfif>
        <cfreturn return_status>
        <cfcatch>
            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Employee Upload Error - #GetEmp.Emp_First#, #GetEmp.Emp_Last# (#GetEmp.Emp_ID#)" type="html">
                <h3>AHCCCS Employee Upload Error</h3>
                <p><strong>Employee Information:</strong></p>
                <ul>
                    <li><strong>Employee Name:</strong> #GetEmp.Emp_First# #GetEmp.Emp_Last#</li>
                    <li><strong>Employee ID:</strong> #GetEmp.Emp_ID#</li>
                    <li><strong>Employee SSN:</strong> #GetEmp.Emp_SSN#</li>
                    <li><strong>Employee Email:</strong> #GetEmp.Emp_Email#</li>
                    <li><strong>Position:</strong> #GetEmp.Skill_1#</li>
                    <li><strong>Agency ID:</strong> #session.agencyid#</li>
                </ul>
                
                <p><strong>Error Details:</strong></p>
                <p>An unexpected error occurred during the employee upload process.</p>
                
                <p><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</p>
                
                <p>The employee upload encountered an unexpected error. Please check the system logs for more details.</p>
            </cfmail>
            <cfreturn "Unexpected error occurred during employee upload">
        </cfcatch>
        </cftry>
    </cffunction>

    <cffunction name="visit_creation" access="remote" returnFormat= "plain">
        <cfargument name="Agency_ID" required="no" hint="Agency_ID" default="#session.agencyId#">
        <cfargument name="Schedule_ID" required="yes" default="0" hint="Schedule_ID">
        <cfargument name="confirmed" required="no" default="false" hint="Set to true to confirm and submit, false to preview data">
        
        <cfset Sch_ID = decrypt(#arguments.Schedule_ID#,#Application.enckey#,"AES","Hex") />
        
        <!--- Initialize LOCAL variables --->
        <cfif application.DEV EQ false>
            <!--- PROD subscription keys --->
            <cfset LOCAL.subscription_key_primary = "3f11f04e0fd74ad39c77c8cacbfef240">
            <cfset LOCAL.subscription_key_secondary = "3710f5d7890241d3beb7181e2b506f8b">
        <cfelse>
            <!--- DEV subscription keys --->
        <cfset LOCAL.subscription_key_primary = "b3446ef5e2ce497dbc9da4007b574c8b">
            <cfset LOCAL.subscription_key_secondary = "1c88925161e94f4cae914d91ad0c077c">
        </cfif>
        <cfset LOCAL.account = "a2f47e6e-5f6b-0e9b-c2c6-e003c1b48ac9">
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- Use server name in email subject --->
        <cfset envLabel = #Application.ServerName# />
        
        <!--- Get agency settings from database --->
        <cfquery name="getagency" datasource="#Application.DataSrc#">
            SELECT * FROM  #Request.prefix_db_lookup#.Agency
            WHERE Agency_ID = '#session.agencyId#'
            <cfif application.DEV EQ false>  
                AND EVV_prod_username IS NOT NULL
                AND EVV_prod_password IS NOT NULL
            <cfelse>
                AND EVV_username IS NOT NULL
                AND EVV_password IS NOT NULL
            </cfif>
        </cfquery>
        <cfif getagency.recordcount gt 0>
            <cfif application.DEV EQ false>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
            <cfelse>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
            </cfif>
        </cfif>
        
        <cftry>
        <cfif application.DEV EQ false>
                <cfset LOCAL.AuthorizationEndpoint = "https://si-api.azahcccs.gov/evv/aggregation/v1/visits/upload?key=" & LOCAL.subscription_key_primary>
        <cfelse>
                <cfset LOCAL.AuthorizationEndpoint = "https://si-api.azahcccs.gov/test/evv/aggregation/v1/visits/upload?key=" & LOCAL.subscription_key_primary>
        </cfif>
            <cfquery name="GtSched" datasource="#Application.DataSrc#">
                SELECT pPatients.Patient_ID, pPatients.Pt_Last AS PatientLast, pPatients.Pt_Middle, pPatients.Pt_First AS PatientFirst,
                       pPatients.Pt_Agy_ID, pPatients.Status AS clientStatus, pPatients.Pt_SSN, pPatients.Pt_Street,
                       pPatients.Pt_City, pPatients.Pt_State, pPatients.Pt_Zip, pPatients.Pt_Longitude, pPatients.Pt_Latitude, pPatients.Pt_Phone,
                       pPatients.Email,
                       pSchedules.Schedule_ID, pSchedules.Visit_Date, pSchedules.Skill AS Type, pSchedules.Visit_Type,
                       pSchedules.Total_Units, pSchedules.Mi_Pay, pSchedules.GPS_start_time, pSchedules.GPS_end_time,
                       pSchedules.patient_sign, pSchedules.Date_Change, pSchedules.Change_by, pSchedules.EVV_Reason_Code_ID,
                CASE WHEN length(pSchedules.patient_sign) > 0 THEN true
                     ELSE false
                END AS patient_sign_indicator,
                CONCAT(RIGHT(pEmployee.Emp_SSN, 5), LEFT(Emp_Last,4)) AS EmployeeIdentifier,
                CONCAT(DATE_FORMAT(CONVERT_TZ(pSchedules.Date_Create, @@session.time_zone, '+00:00'),'%Y-%m-%dT%H:%i:%s'), 'Z') AS CallDateTime,
                pSchedules.Progress_Note, pSchedules.pgnotesdraft, pSchedules.GPS_start_latitude,
                pSchedules.GPS_start_longitude, pSchedules.GPS_end_latitude, pSchedules.GPS_end_longitude,
                pSchedules.Pay_ID, 0 AS No_Days_Progress, "" AS Note_QA, pSchedules.Notes AS Memo,
                IFNULL(pSchedules.Sch_Latitude,40.34455) AS Sch_Latitude,
                IFNULL(pSchedules.Sch_Longitude,-21.99383) AS Sch_Longitude,
                pSchedules.GPS_start_date, pSchedules.GPS_end_date,
                pSchedules.StartTime, pSchedules.EndTime, pSchedules.Date_Create AS CallDateTime_old,
                (TIME_TO_SEC(TIMEDIFF(pSchedules.EndTime,pSchedules.StartTime))/3600) AS totalhours,
                IFNULL(pPtPayer.Sub_HIC,pSchedules.Schedule_ID) AS Sub_HICs, 
                pEmployee.*, pAssessments.Assmt_ID, pAuths.*, pPayer.*, pPtPayer.*, Agency.*, pRevenue_Code.HCPCS, pRevenue_Code.Modifier, pPhysicians.Phys_NPI
                FROM #Request.prefix_db_agency#.pSchedules
                LEFT OUTER JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Assmt_ID = pSchedules.Assmt_ID AND pAssessments.status = 0
                LEFT OUTER JOIN #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID
                JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pSchedules.Patient_ID AND pPatients.Status IN (0,1,4)
                JOIN #Request.prefix_db_lookup#.pEmployee ON pSchedules.Emp_ID = pEmployee.Emp_ID AND pEmployee.Status < 2
                LEFT OUTER JOIN #Request.prefix_db_agency#.pAuths ON pAuths.Patient_ID = pSchedules.Patient_ID
                AND  pAuths.Auth_ID = pSchedules.Auth_ID AND pAuths.Status = 0
                LEFT OUTER JOIN #Request.prefix_db_agency#.pPtPayer ON pPtPayer.Patient_ID = pPatients.Patient_ID 
                    AND pPtPayer.PtPayer_ID = pAuths.PtPayer_ID AND pPtPayer.Status = 0
                LEFT OUTER JOIN #Request.prefix_db_agency#.pPayer ON pPayer.Pay_ID = pPtPayer.Payer_ID AND pPayer.Status = 0
                LEFT OUTER JOIN #Request.prefix_db_lookup#.Agency ON Agency.Agency_ID = pPatients.Loc_ID AND Agency.Status = 'active'
                LEFT OUTER JOIN #Request.prefix_db_agency#.pRevenue_Code ON pRevenue_Code.Rev_CodeID = pSchedules.HCPCS_ID AND pRevenue_Code.Status = 0
                LEFT OUTER JOIN #Request.prefix_db_lookup#.pPhysicians ON pPhysicians.Emp_ID = pEmployee.Emp_ID AND pPhysicians.Status = 0
                WHERE pSchedules.status = 0
                    AND pSchedules.Emp_ID != 0
                    AND pSchedules.Missed = '0'
                    AND pSchedules.Visit_Date >= '2024-07-31'
                    AND pSchedules.EVV_Export = 0
                    AND pSchedules.Schedule_ID IN (<cfqueryparam cfsqltype="cf_sql_integer" value="#Sch_ID#" list="yes">)   
                GROUP BY pSchedules.Schedule_ID
                ORDER BY pPatients.Pt_Last ASC, pPatients.Pt_First ASC, pEmployee.Emp_Last ASC, pEmployee.Emp_First ASC,
                         pSchedules.Skill ASC, pSchedules.Visit_Date ASC 
        </cfquery>
        
        <!--- Check if this visit has already been submitted to AHCCCS --->
        <cfquery name="CheckExistingSubmission" datasource="#Application.DataSrc#">
            SELECT UUID, San_status, Date_Create, Seq_ID as Original_Seq_ID
            FROM #Request.prefix_db_lookup#.EVV
            WHERE API_Type = 'visits'
            AND Agency_ID = '#session.agencyid#'
            AND Schedule_ID = '#Sch_ID#'
            AND status = 0
            ORDER BY EVV_ID DESC LIMIT 1
        </cfquery>
        
        <!--- Get the previously submitted schedule data from history to compare for actual changes --->
        <cfquery name="GetPreviousScheduleData" datasource="#Application.DataSrc#">
            SELECT Visit_Date, StartTime, EndTime, GPS_start_time, GPS_end_time,
                   GPS_start_date, GPS_end_date, GPS_start_latitude, GPS_start_longitude,
                   GPS_end_latitude, GPS_end_longitude, Emp_ID, Total_Units, Mi_Pay,
                   Notes, patient_sign
            FROM #Request.prefix_db_agency#.pSchedules
            WHERE Schedule_ID = '#Sch_ID#'
            AND status = 2
            ORDER BY Date_Create DESC
            LIMIT 1
        </cfquery>
        
        <!--- Get EVV Reason Code information if it exists --->
        <cfquery name="GetReasonCodeInfo" datasource="#Application.DataSrc#">
            SELECT 
                rc.Reason_Code_ID,
                rc.Description,
                ul.Change_Memo,
                ul.Date_Updated,
                ul.Changed_By,
                ul.Changed_By_Email
            FROM #Request.prefix_db_lookup#.EVV_Update_Log ul
            LEFT JOIN #Request.prefix_db_lookup#.EVV_Reason_Codes rc ON rc.Reason_Code_ID = ul.Reason_Code_ID
            WHERE ul.Schedule_ID = '#Sch_ID#'
            AND ul.Status = 0
            ORDER BY ul.Date_Reason_Added DESC
            LIMIT 1
        </cfquery>
        
        <!--- Initialize datetime variables early --->
        <cfset currentDate = Now()>
        <cfset formattedDateTime = DateFormat(currentDate, "yyyy-mm-dd") & "T" & TimeFormat(currentDate, "HH:mm:ss") & "Z">
        
        <!--- Get user email who made the change --->
        <cfset ChangeMadeByEmail = "">
        <cfset ChangeReasonMemo = "">
        <cfset ChangeDateTime = formattedDateTime>
        
        <cfif GtSched.recordcount GT 0>
            <!--- If Date_Change exists, use that for ChangeDateTime --->
            <cfif isDefined('GtSched.Date_Change') AND IsDate(GtSched.Date_Change)>
                <cfset ChangeDateTime = DateFormat(GtSched.Date_Change, "yyyy-mm-dd") & "T" & TimeFormat(GtSched.Date_Change, "HH:mm:ss") & "Z">
            </cfif>
            
            <!--- If Change_by exists, get their email --->
            <cfif isDefined('GtSched.Change_by') AND IsNumeric(GtSched.Change_by) AND GtSched.Change_by GT 0>
                <cfquery name="GetChangedByUser" datasource="#Application.DataSrc#">
                    SELECT Emp_Email
                    FROM #Request.prefix_db_lookup#.pEmployee
                    WHERE Emp_ID = <cfqueryparam value="#GtSched.Change_by#" cfsqltype="cf_sql_integer">
                    LIMIT 1
                </cfquery>
                <cfif GetChangedByUser.recordcount GT 0 AND Len(Trim(GetChangedByUser.Emp_Email)) GT 0>
                    <cfset ChangeMadeByEmail = GetChangedByUser.Emp_Email>
                <cfelse>
                    <cfset ChangeMadeByEmail = GtSched.Emp_Email>
                </cfif>
            <cfelse>
                <cfset ChangeMadeByEmail = GtSched.Emp_Email>
            </cfif>
            
            <!--- Use Change_Memo and ChangeMadeByEmail from CURRENT active EVV_Update_Log if available --->
            <!--- This gets the memo that clinician entered in the EVV Update Log page for THIS update --->
            <cfif GetReasonCodeInfo.recordcount GT 0>
                <!--- Log what we got from EVV_Update_Log --->
                <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | GetReasonCodeInfo found | Change_Memo=[#GetReasonCodeInfo.Change_Memo#] | Changed_By_Email=[#GetReasonCodeInfo.Changed_By_Email#] | Reason_Code_ID=[#GetReasonCodeInfo.Reason_Code_ID#]">
                
                <!--- Use the Change_Memo from current active EVV_Update_Log entry (entered by clinician) --->
                <cfif Len(Trim(GetReasonCodeInfo.Change_Memo)) GT 0>
                    <cfset ChangeReasonMemo = Trim(GetReasonCodeInfo.Change_Memo)>
                    <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | ChangeReasonMemo set from EVV_Update_Log: [#ChangeReasonMemo#]">
                <cfelse>
                    <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | ChangeReasonMemo is BLANK in EVV_Update_Log - will remain BLANK (no fallback to visit notes)">
                </cfif>
                
                <!--- Use ChangeMadeByEmail from log if available --->
                <cfif Len(Trim(GetReasonCodeInfo.Changed_By_Email)) GT 0>
                    <cfset ChangeMadeByEmail = GetReasonCodeInfo.Changed_By_Email>
                </cfif>
                
                <!--- Use Date_Updated from log if available for ChangeDateTime --->
                <cfif isDefined('GetReasonCodeInfo.Date_Updated') AND IsDate(GetReasonCodeInfo.Date_Updated)>
                    <cfset ChangeDateTime = DateFormat(GetReasonCodeInfo.Date_Updated, "yyyy-mm-dd") & "T" & TimeFormat(GetReasonCodeInfo.Date_Updated, "HH:mm:ss") & "Z">
                </cfif>
            <cfelse>
                <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | GetReasonCodeInfo.recordcount = 0 (no EVV_Update_Log record found) - ChangeReasonMemo will remain BLANK">
            </cfif>
            
            <!--- REMOVED: Fallback to visit notes - ChangeReasonMemo should ONLY come from EVV_Update_Log.Change_Memo --->
            <!--- DO NOT use visit notes field for ChangeReasonMemo - clinician must enter it in EVV Update Log --->
            <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | Final ChangeReasonMemo value (ONLY from EVV_Update_Log): [#ChangeReasonMemo#] (Length: #Len(ChangeReasonMemo)#)">
        </cfif>
        
        <!--- Determine if this is a new submission or an update --->
        <cfset isVisitUpdate = false>
        <cfset hasActualChanges = false>
        <cfset originalUUID = "">
        
        <!--- Initialize reason code - will be set properly later based on whether it's initial or update --->
        <!--- Default to 10 for initial submission --->
        <cfset changeReasonCode = "10">
        
        <!--- Get Reason_Code_ID from EVV_Update_Log table instead of pSchedules --->
        <!--- If Reason_Code_ID is set in EVV_Update_Log, use that --->
        <!--- Otherwise, will be set to 11 (modification) later if isVisitUpdate = true --->
        <cfif GetReasonCodeInfo.recordcount GT 0 AND isDefined('GetReasonCodeInfo.Reason_Code_ID') AND IsNumeric(GetReasonCodeInfo.Reason_Code_ID) AND GetReasonCodeInfo.Reason_Code_ID GT 0>
            <cfset changeReasonCode = ToString(GetReasonCodeInfo.Reason_Code_ID)>
            <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | Using Reason_Code_ID from EVV_Update_Log: #changeReasonCode#">
        </cfif>
        
        <!--- Check if there's any prior successful submission --->
        <cfif CheckExistingSubmission.recordcount GT 0 AND (
            CheckExistingSubmission.San_status EQ 'SUCCESS' OR 
             CheckExistingSubmission.San_status EQ 'Data Changed - Retransmission Required' OR
            FindNoCase('Transaction Received', CheckExistingSubmission.San_status) GT 0 OR
            FindNoCase('Transmitted', CheckExistingSubmission.San_status) GT 0
        )>
            <cfset originalUUID = CheckExistingSubmission.UUID>
            
            <!--- Compare current data with previous submission to detect actual changes --->
            <cfif GetPreviousScheduleData.recordcount GT 0>
                <!--- Check if key fields have changed --->
                <cfif 
                    DateFormat(GtSched.Visit_Date, "yyyy-mm-dd") NEQ DateFormat(GetPreviousScheduleData.Visit_Date, "yyyy-mm-dd") OR
                    TimeFormat(GtSched.StartTime, "HH:mm:ss") NEQ TimeFormat(GetPreviousScheduleData.StartTime, "HH:mm:ss") OR
                    TimeFormat(GtSched.EndTime, "HH:mm:ss") NEQ TimeFormat(GetPreviousScheduleData.EndTime, "HH:mm:ss") OR
                    Trim(GtSched.GPS_start_time) NEQ Trim(GetPreviousScheduleData.GPS_start_time) OR
                    Trim(GtSched.GPS_end_time) NEQ Trim(GetPreviousScheduleData.GPS_end_time) OR
                    Trim(GtSched.GPS_start_latitude) NEQ Trim(GetPreviousScheduleData.GPS_start_latitude) OR
                    Trim(GtSched.GPS_start_longitude) NEQ Trim(GetPreviousScheduleData.GPS_start_longitude) OR
                    Trim(GtSched.GPS_end_latitude) NEQ Trim(GetPreviousScheduleData.GPS_end_latitude) OR
                    Trim(GtSched.GPS_end_longitude) NEQ Trim(GetPreviousScheduleData.GPS_end_longitude) OR
                    GtSched.Emp_ID NEQ GetPreviousScheduleData.Emp_ID OR
                    GtSched.Total_Units NEQ GetPreviousScheduleData.Total_Units OR
                    GtSched.Mi_Pay NEQ GetPreviousScheduleData.Mi_Pay OR
                    Trim(GtSched.Memo) NEQ Trim(GetPreviousScheduleData.Notes) OR
                    Len(Trim(GtSched.patient_sign)) NEQ Len(Trim(GetPreviousScheduleData.patient_sign))
                >
                    <cfset hasActualChanges = true>
                </cfif>
            <cfelse>
                <!--- No history found, assume it's a change if there's a previous submission --->
                <cfset hasActualChanges = true>
            </cfif>
            
            <!--- 
            DEBUG: Show previous vs current values table for specific IP only - COMMENTED OUT
            <cfset clientIP = CGI.REMOTE_ADDR>
            <cfif clientIP EQ "103.143.7.161" AND GetPreviousScheduleData.recordcount GT 0>
                <cfset debugComparisonTable = "">
                <cfsavecontent variable="debugComparisonTable">
                    <cfoutput>
                    <div style="font-family: Arial, sans-serif; padding: 20px; max-width: 1200px; margin: 20px auto; background-color: ##f8f9fa; border: 2px solid ##007bff; border-radius: 8px;">
                        <h2 style="color: ##007bff; border-bottom: 2px solid ##007bff; padding-bottom: 10px; margin-top: 0;">🔍 DEBUG: Previous vs Current Values Comparison</h2>
                        <p style="color: ##666; font-size: 12px; margin-bottom: 15px;">Schedule ID: #Sch_ID# | IP: #clientIP#</p>
                        <table style="width: 100%; border-collapse: collapse; background-color: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                            <thead>
                                <tr style="background-color: ##007bff; color: white;">
                                    <th style="padding: 12px; text-align: left; border: 1px solid ##ddd; width: 25%;">Field Name</th>
                                    <th style="padding: 12px; text-align: left; border: 1px solid ##ddd; width: 37.5%;">Previous Value</th>
                                    <th style="padding: 12px; text-align: left; border: 1px solid ##ddd; width: 37.5%;">Current Value</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr style="background-color: <cfif DateFormat(GtSched.Visit_Date, 'yyyy-mm-dd') NEQ DateFormat(GetPreviousScheduleData.Visit_Date, 'yyyy-mm-dd')>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">Visit Date</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.Visit_Date NEQ "">#DateFormat(GetPreviousScheduleData.Visit_Date, "yyyy-mm-dd")#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.Visit_Date NEQ "">#DateFormat(GtSched.Visit_Date, "yyyy-mm-dd")#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif TimeFormat(GtSched.StartTime, 'HH:mm:ss') NEQ TimeFormat(GetPreviousScheduleData.StartTime, 'HH:mm:ss')>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">Start Time</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.StartTime NEQ "">#TimeFormat(GetPreviousScheduleData.StartTime, "HH:mm:ss")#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.StartTime NEQ "">#TimeFormat(GtSched.StartTime, "HH:mm:ss")#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif TimeFormat(GtSched.EndTime, 'HH:mm:ss') NEQ TimeFormat(GetPreviousScheduleData.EndTime, 'HH:mm:ss')>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">End Time</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.EndTime NEQ "">#TimeFormat(GetPreviousScheduleData.EndTime, "HH:mm:ss")#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.EndTime NEQ "">#TimeFormat(GtSched.EndTime, "HH:mm:ss")#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif Trim(GtSched.GPS_start_time) NEQ Trim(GetPreviousScheduleData.GPS_start_time)>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">GPS Start Time</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.GPS_start_time NEQ "">#GetPreviousScheduleData.GPS_start_time#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.GPS_start_time NEQ "">#GtSched.GPS_start_time#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif Trim(GtSched.GPS_end_time) NEQ Trim(GetPreviousScheduleData.GPS_end_time)>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">GPS End Time</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.GPS_end_time NEQ "">#GetPreviousScheduleData.GPS_end_time#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.GPS_end_time NEQ "">#GtSched.GPS_end_time#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif Trim(GtSched.GPS_start_latitude) NEQ Trim(GetPreviousScheduleData.GPS_start_latitude)>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">GPS Start Latitude</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.GPS_start_latitude NEQ "">#GetPreviousScheduleData.GPS_start_latitude#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.GPS_start_latitude NEQ "">#GtSched.GPS_start_latitude#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif Trim(GtSched.GPS_start_longitude) NEQ Trim(GetPreviousScheduleData.GPS_start_longitude)>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">GPS Start Longitude</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.GPS_start_longitude NEQ "">#GetPreviousScheduleData.GPS_start_longitude#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.GPS_start_longitude NEQ "">#GtSched.GPS_start_longitude#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif Trim(GtSched.GPS_end_latitude) NEQ Trim(GetPreviousScheduleData.GPS_end_latitude)>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">GPS End Latitude</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.GPS_end_latitude NEQ "">#GetPreviousScheduleData.GPS_end_latitude#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.GPS_end_latitude NEQ "">#GtSched.GPS_end_latitude#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif Trim(GtSched.GPS_end_longitude) NEQ Trim(GetPreviousScheduleData.GPS_end_longitude)>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">GPS End Longitude</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.GPS_end_longitude NEQ "">#GetPreviousScheduleData.GPS_end_longitude#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.GPS_end_longitude NEQ "">#GtSched.GPS_end_longitude#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif GtSched.Emp_ID NEQ GetPreviousScheduleData.Emp_ID>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">Employee ID</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.Emp_ID NEQ "">#GetPreviousScheduleData.Emp_ID#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.Emp_ID NEQ "">#GtSched.Emp_ID#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif GtSched.Total_Units NEQ GetPreviousScheduleData.Total_Units>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">Total Units</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.Total_Units NEQ "">#GetPreviousScheduleData.Total_Units#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.Total_Units NEQ "">#GtSched.Total_Units#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif GtSched.Mi_Pay NEQ GetPreviousScheduleData.Mi_Pay>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">Mi Pay</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.Mi_Pay NEQ "">#GetPreviousScheduleData.Mi_Pay#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.Mi_Pay NEQ "">#GtSched.Mi_Pay#<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif Trim(GtSched.Memo) NEQ Trim(GetPreviousScheduleData.Notes)>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">Memo/Notes</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.Notes NEQ "">#Left(GetPreviousScheduleData.Notes, 100)#<cfif Len(GetPreviousScheduleData.Notes) GT 100>...<cfelse></cfif><cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.Memo NEQ "">#Left(GtSched.Memo, 100)#<cfif Len(GtSched.Memo) GT 100>...<cfelse></cfif><cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                                <tr style="background-color: <cfif Len(Trim(GtSched.patient_sign)) NEQ Len(Trim(GetPreviousScheduleData.patient_sign))>##fff3cd<cfelse>##ffffff</cfif>;">
                                    <td style="padding: 10px; border: 1px solid ##ddd; font-weight: bold;">Patient Signature (Length)</td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GetPreviousScheduleData.patient_sign NEQ "">#Len(Trim(GetPreviousScheduleData.patient_sign))# characters<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                    <td style="padding: 10px; border: 1px solid ##ddd;"><cfif GtSched.patient_sign NEQ "">#Len(Trim(GtSched.patient_sign))# characters<cfelse><em style="color: ##999;">(empty)</em></cfif></td>
                                </tr>
                            </tbody>
                        </table>
                        <div style="margin-top: 15px; padding: 10px; background-color: <cfif hasActualChanges>##d4edda<cfelse>##fff3cd</cfif>; border-left: 4px solid <cfif hasActualChanges>##28a745<cfelse>##ffc107</cfif>;">
                            <strong>Change Detection Result:</strong> 
                            <cfif hasActualChanges>
                                ✅ <span style="color: ##155724;">Changes Detected - Visit will be marked as UPDATE</span>
                            <cfelse>
                                ⚠️ <span style="color: ##856404;">No Changes Detected</span>
                            </cfif>
                            <br>
                            <strong>isVisitUpdate:</strong> <cfif isVisitUpdate>true<cfelse>false</cfif> | 
                            <strong>Reason Code:</strong> #changeReasonCode# | 
                            <strong>Change Made By:</strong> #ChangeMadeByEmail#
                        </div>
                    </div>
                    </cfoutput>
                </cfsavecontent>
                <!--- Store debug table for inclusion in response --->
                <cfset Request.debugComparisonTable = debugComparisonTable>
                <!--- Also log that comparison table was generated --->
                <cflog file="AHCCCS_Visit_Comparison" text="Schedule_ID=#Sch_ID# | Comparison Table Generated for IP #clientIP# | hasActualChanges=#hasActualChanges# | isVisitUpdate=#isVisitUpdate#">
            </cfif>
            --->
            
            <!--- Only mark as update if there are actual changes --->
            <cfif hasActualChanges>
                <cfset isVisitUpdate = true>
                
                <!--- Get Reason_Code_ID from EVV_Update_Log for updates --->
                <!--- Each new update requires clinician to select a NEW reason code via EVV Update Log page --->
                <!--- If not yet set in EVV_Update_Log, default to 11 (modification) --->
                <cfif NOT (GetReasonCodeInfo.recordcount GT 0 AND isDefined('GetReasonCodeInfo.Reason_Code_ID') AND IsNumeric(GetReasonCodeInfo.Reason_Code_ID) AND GetReasonCodeInfo.Reason_Code_ID GT 0)>
                    <cfset changeReasonCode = "11">
                    <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | isVisitUpdate=true, setting changeReasonCode to 11 (modification) - clinician should update via EVV Update Log">
                </cfif>
                
                <!--- ChangeReasonMemo stays blank - clinician must enter NEW memo for NEW changes --->
                <!--- Already initialized as blank on line 1021 --->
                <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | ChangeReasonMemo remains BLANK for new update">
            </cfif>
        </cfif>
        
        <!--- 
        AHCCCS VisitChanges Reason Codes:
        10 = Initial visit submission
        11 = Visit modification/update
        12 = Time correction
        13 = Service type change
        14 = Employee change
        15 = Client signature added
        16 = GPS location correction
        --->
        
        <!--- Check if schedule record exists --->
        <cfif GtSched.recordcount EQ 0>
            <cfreturn "Visit not found or does not meet the criteria for EVV export">
        </cfif>
        
        <!--- Initialize variables for JSON payload early --->
        <cfset Modifier1Value = "">
        <cfset ModifierForJSON = javaCast("null", "")>
        <cfset ProcedureCode = 'G0151'>
        <cfset ClientVerifiedTasks = javaCast("null", "")>
        <cfset NeedExceptionAcknowledgement = true>
        <cfset ClientSignatureAvailable = "false">

        <cfset Start_Time = DateFormat(GtSched.Visit_Date, "yyyy-mm-dd") & "T" & TimeFormat(GtSched.StartTime, "HH:mm:ss") & "Z">
        <cfset End_Time = DateFormat(GtSched.Visit_Date, "yyyy-mm-dd") & "T" & TimeFormat(GtSched.EndTime, "HH:mm:ss") & "Z">
        <cfset Previous_Day = DateAdd("d", -1, Now())>
        <cfset Adjust_Start_Time = "">
        <cfset Adjust_End_Time = "">
        <cfif GtSched.GPS_start_time NEQ ''>
            <cfset Adjust_Start_Time = DateFormat(GtSched.GPS_start_date, "yyyy-mm-dd") & "T" & TimeFormat(GtSched.GPS_start_time, "HH:mm:ss") & "Z">
        </cfif>
        <cfif GtSched.GPS_end_time NEQ ''>
            <cfset Adjust_End_Time = DateFormat(GtSched.GPS_end_date, "yyyy-mm-dd") & "T" & TimeFormat(GtSched.GPS_end_time, "HH:mm:ss") & "Z">
        </cfif>
        <cfif session.employeeid EQ 2>
            <cfif GtSched.GPS_start_time EQ ''>
                <cfset Adjust_Start_Time = DateFormat(GtSched.Visit_Date, "yyyy-mm-dd") & "T" & TimeFormat(GtSched.StartTime, "HH:mm:ss") & "Z">
                <cfset Adjust_End_Time = DateFormat(GtSched.Visit_Date, "yyyy-mm-dd") & "T" & TimeFormat(GtSched.EndTime, "HH:mm:ss") & "Z">  
            </cfif>   
        </cfif>
        <!--- Calculate total hours to bill using time difference: (TIME_TO_SEC(TIMEDIFF(EndTime, StartTime))/3600) --->
        <!--- Use the same calculation as authorizations.cfm (Time spent) --->
        <cfif IsDefined("GtSched.totalhours") AND IsNumeric(GtSched.totalhours)>
            <cfset Total_Hours = NumberFormat(GtSched.totalhours, "0.00")>
        <cfelse>
            <!--- Fallback calculation if totalhours is not available --->
            <cfset startDateTime = CreateDateTime(Year(GtSched.Visit_Date), Month(GtSched.Visit_Date), Day(GtSched.Visit_Date), 
                                                   ListGetAt(GtSched.StartTime, 1, ':'), ListGetAt(GtSched.StartTime, 2, ':'), 0)>
            <cfset endDateTime = CreateDateTime(Year(GtSched.Visit_Date), Month(GtSched.Visit_Date), Day(GtSched.Visit_Date), 
                                                 ListGetAt(GtSched.EndTime, 1, ':'), ListGetAt(GtSched.EndTime, 2, ':'), 0)>
            
            <!--- Handle case where end time is next day --->
            <cfif endDateTime LTE startDateTime>
                <cfset endDateTime = DateAdd("d", 1, endDateTime)>
            </cfif>
            
            <!--- Calculate time difference in seconds and convert to hours --->
            <cfset timeDiffInSeconds = DateDiff("s", startDateTime, endDateTime)>
            <cfset Total_Hours = NumberFormat(timeDiffInSeconds / 3600, "0.00")>
        </cfif>
        <cfset logMessage = "Schedule #GtSched.Schedule_ID# - Start: #GtSched.StartTime# End: #GtSched.EndTime# - Hours: #Total_Hours#">
        <cfif IsDefined("GtSched.totalhours") AND IsNumeric(GtSched.totalhours)>
            <cfset logMessage = logMessage & " (from totalhours: #GtSched.totalhours#)">
        </cfif>
        <cflog file="AHCCCS_Hours" text="#logMessage#">
        <cfset VisitTimeZone = "US/Arizona"> 

        <!--- Use EVV_Payer_ID from payer setup if available, otherwise default to AZCCCS --->
        <cfif StructKeyExists(GtSched, "EVV_Payer_ID") AND NOT IsNull(GtSched.EVV_Payer_ID) AND Len(Trim(GtSched.EVV_Payer_ID)) GT 0>
            <cfset PayerID = GtSched.EVV_Payer_ID>
        <cfelse>
            <cfset PayerID = 'AZCCCS'>
        </cfif>
        <cfset PayerProgram = 'AHCCCS'>
        <!--- Get ProcedureCode from HCPCS field of selected revenue code, default to G0151 if not available --->
        <cfif StructKeyExists(GtSched, "HCPCS") AND Len(Trim(GtSched.HCPCS)) GT 0>
            <cfset ProcedureCode = Trim(GtSched.HCPCS)>
        </cfif>
        <!--- Get Modifier from revenue code --->
        <cfif StructKeyExists(GtSched, "Modifier") AND NOT IsNull(GtSched.Modifier) AND Len(Trim(GtSched.Modifier)) GT 0>
            <cfset Modifier1Value = Trim(GtSched.Modifier)>
            <cfset ModifierForJSON = Trim(GtSched.Modifier)>
        </cfif>
        <cfset ModifierForJSON = Modifier1Value />
        <cfset Emp_SSN = "9999999999" />
        <cfset EmployeeIdentifier = #RIGHT(Emp_SSN,5)# & #LEFT(GtSched.Emp_Last,4)#>
        <cfif GtSched.Emp_SSN NEQ ''>
            <cfset Emp_SSN = #RIGHT(GtSched.Emp_SSN,5)#>
            <cfset EmployeeIdentifier = repeatString("0", 5 - len(Emp_SSN)) & #LEFT(GtSched.Emp_Last,4)#>
            <cfset EmployeeIdentifier = GtSched.Emp_SSN>
        </cfif> 

            <!--- Generate unique sequence ID with datetime format YYYYMMDDHHMMSS + 2 digits (max 16 digits) --->
            <cfset Seq_ID = DateFormat(now(), "yyyymmdd") & TimeFormat(now(), "HHmmss") & Right(GetTickCount(), 2) />
        
        <!--- Get ClientIdentifier from Sub_HIC column, format with A prefix and padding --->
        <cfif StructKeyExists(GtSched, "Sub_HICs") AND Len(Trim(GtSched.Sub_HICs)) GT 0>
            <cfset ClientMedicaidID = Trim(GtSched.Sub_HICs)>
        <cfelse>
            <cfset ClientMedicaidID = GtSched.Patient_ID>
        </cfif>
        <!---
            Preserve payer-specific identifier formats:
            - AHCCCS style: A########
            - UHC/AHCCCS style: ######### (9 digits)
        --->
        <cfset rawClientMedicaidID = UCase(Trim(ClientMedicaidID))>
        <cfif ReFind("^A[0-9]{8}$", rawClientMedicaidID) GT 0>
            <cfset ClientIdentifier = rawClientMedicaidID>
        <cfelseif ReFind("^[0-9]{9}$", rawClientMedicaidID) GT 0>
            <cfset ClientIdentifier = rawClientMedicaidID>
        <cfelseif ReFind("^[0-9]+$", rawClientMedicaidID) GT 0>
            <cfset ClientIdentifier = "A" & Right("00000000" & rawClientMedicaidID, 8)>
        <cfelse>
            <cfset CleanMedicaidID = REReplace(rawClientMedicaidID, "[^0-9]", "", "all")>
            <cfset ClientIdentifier = "A" & Right("00000000" & CleanMedicaidID, 8)>
        </cfif>
        
        <!--- Convert patient signature indicator to proper boolean for JSON --->
        <cfif isDefined('GtSched.patient_sign_indicator') AND GtSched.patient_sign_indicator>
            <cfset ClientSignatureAvailable = "true">
            <cfset ClientVerifiedTasks = true>
            <cfset NeedExceptionAcknowledgement = false>
        <cfelse>
            <cfset ClientSignatureAvailable = "false">
            <cfset ClientVerifiedTasks = javaCast("null", "")>
            <cfset NeedExceptionAcknowledgement = true>
        </cfif>
        
        <!--- Determine CallType, MobileLogin, and Location based on GPS data availability and update status --->
        <cfif isVisitUpdate>
            <!--- If visit is being updated after initial submission, always use Manual --->
            <cfset CallType = "Manual">
            <cfset MobileLogin = "">
            <cfset CallLocation = "Dublin">
        <cfelseif (Len(Trim(GtSched.GPS_start_latitude)) GT 0 AND NOT IsNull(GtSched.GPS_start_latitude) AND Val(GtSched.GPS_start_latitude) NEQ 0) AND 
                  (Len(Trim(GtSched.GPS_start_longitude)) GT 0 AND NOT IsNull(GtSched.GPS_start_longitude) AND Val(GtSched.GPS_start_longitude) NEQ 0)>
            <!--- If GPS coordinates exist and are valid (latitude/longitude captured via start button), use Mobile --->
            <cfset CallType = "Mobile">
            <cfset MobileLogin = GtSched.Emp_Email>
            <cfset CallLocation = GtSched.Pt_City>
        <cfelse>
            <!--- If no GPS coordinates or invalid (manually entered times), use Manual and default location --->
            <cfset CallType = "Manual">
            <cfset MobileLogin = "">
            <cfset CallLocation = "Dublin">
        </cfif>
        
        <!--- Create visit data structure with proper null handling --->
        <cfset visitData = {
                "ProviderIdentification": {
                "ProviderID": "#LOCAL.ProviderID#",
                "ProviderQualifier": "MedicaidID"
            },
            "HasManualCalls": javaCast("null", ""),
            "VisitSequenceID": javaCast("null", ""),
            "AgencyIdentifier": javaCast("null", ""),
            "VisitOtherID": "#Sch_ID#",
            "SequenceID": #Seq_ID#,
            "EmployeeQualifier": "EmployeeSSN",
            "EmployeeOtherID": "#EmployeeIdentifier#" ,
            "EmployeeIdentifier": "#EmployeeIdentifier#",
            "GroupCode": javaCast("null", ""),
            "ClientIDQualifier": "ClientCustomID",
            "ClientID": "#ClientIdentifier#",
            "ClientOtherID": "#ClientIdentifier#",
            "VisitCancelledIndicator": false,
            "PayerID": "#PayerID#",
            "PayerProgram": "#PayerProgram#",
            "ProcedureCode": "#ProcedureCode#",
            "Modifier1": ModifierForJSON,
            "Modifier2": javaCast("null", ""),
            "Modifier3": javaCast("null", ""),
            "Modifier4": javaCast("null", ""),
            "VisitTimeZone": "#VisitTimeZone#",
            "ScheduleStartTime": "#Start_Time#",
            "ScheduleEndTime": "#End_Time#"
        }>
        
        <!--- Add AdjInDateTime and AdjOutDateTime if visit has been updated/changed --->
        <cfif isVisitUpdate>
            <cfset visitData["AdjInDateTime"] = Start_Time>
            <cfset visitData["AdjOutDateTime"] = End_Time>
        <cfelse>
            <cfset visitData["AdjInDateTime"] = javaCast("null", "")>
            <cfset visitData["AdjOutDateTime"] = javaCast("null", "")>
        </cfif>
        
        <!--- Continue with remaining fields --->
        <cfset visitData["BillVisit"] = true>
        <cfset visitData["HoursToBill"] = Total_Hours>
        <cfset visitData["HoursToPay"] = Total_Hours>
        <cfset visitData["Memo"] = Left(Trim(GtSched.Memo), 511)>
        <cfset visitData["ClientVerifiedTimes"] = true>
        <cfif isDefined("ClientVerifiedTasks")>
            <cfset visitData["ClientVerifiedTasks"] = ClientVerifiedTasks>
        <cfelse>
            <cfset visitData["ClientVerifiedTasks"] = javaCast("null", "")>
        </cfif>
        <cfset visitData["ClientVerifiedService"] = true>
        <cfset visitData["ClientSignatureAvailable"] = ClientSignatureAvailable>
        <cfset visitData["ClientVoiceRecording"] = false>
        <cfset visitData["ContingencyPlan"] = "CP01">
        <cfset visitData["Reschedule"] = false>
        <cfset visitData["BypassReason"] = javaCast("null", "")>
        <cfset visitData["Calls"] = [
                {
                    "CallExternalID": "#repeatString("0", 16 - len(GtSched.Schedule_ID))##GtSched.Schedule_ID#",
                    "CallDateTime": "#Start_Time#",
                    "CallAssignment": "Time In",
                    "GroupCode": "",
                    "CallType": "#CallType#",
                    "ProcedureCode": "#ProcedureCode#",
                    "ClientIdentifierOnCall": "#ClientIdentifier#",
                    "MobileLogin": "#MobileLogin#",
                    "CallLatitude": "#GtSched.GPS_start_latitude#",
                    "CallLongitude": "#GtSched.GPS_start_longitude#",
                    "Location": "#CallLocation#",
                    "VisitLocationType": "1",
                    "TelephonyPIN": javaCast("null", ""),
                    "OriginatingPhoneNumber": javaCast("null", ""),
                    "IpAddress": javaCast("null", ""),
                    "WorkerPin": javaCast("null", "")
                },
                {
                    "CallExternalID": "#repeatString("0", 16 - len(GtSched.Schedule_ID))##GtSched.Schedule_ID#", 
                    "CallDateTime": "#End_Time#",
                    "CallAssignment": "Time Out", 
                    "GroupCode": "", 
                    "CallType": "#CallType#",
                    "ProcedureCode": "#ProcedureCode#", 
                    "ClientIdentifierOnCall": "#ClientIdentifier#",
                    "MobileLogin": "#MobileLogin#",
                    "CallLatitude": "#GtSched.GPS_end_latitude#",
                    "CallLongitude": "#GtSched.GPS_end_longitude#",
                    "Location": "#CallLocation#",
                    "VisitLocationType": "1",
                    "TelephonyPIN": javaCast("null", ""),
                    "OriginatingPhoneNumber": javaCast("null", ""),
                    "IpAddress": javaCast("null", ""),
                    "WorkerPin": javaCast("null", "")
                }
            ]>
        <cfset visitData["VisitTasks"] = javaCast("null", "")>
        
        <!--- Add GPS coordinates to Calls only if CallType is Mobile (GPS was actually captured) --->
        <cfif CallType EQ "Mobile">
            <cfset visitData.Calls[1]["CallLatitude"] = GtSched.GPS_start_latitude>
            <cfset visitData.Calls[1]["CallLongitude"] = GtSched.GPS_start_longitude>
            <cfset visitData.Calls[2]["CallLatitude"] = GtSched.GPS_end_latitude>
            <cfset visitData.Calls[2]["CallLongitude"] = GtSched.GPS_end_longitude>
        </cfif>
        
        <!--- Add VisitChanges for Manual calls or updates/modifications --->
        <cfif CallType EQ "Manual" OR isVisitUpdate>
            <!--- Ensure ChangeReasonMemo is never NULL for JSON - use empty string if blank --->
            <cfif NOT isDefined('ChangeReasonMemo') OR ChangeReasonMemo IS "">
                <cfset ChangeReasonMemo = "">
            </cfif>
            
            <cfset visitData["VisitChanges"] = [
                {
                    "VisitHasManualCalls": javaCast("null", ""),
                    "SequenceID": "#Seq_ID#",
                    "ChangeMadeBy": "#ChangeMadeByEmail#",
                    "ChangeDateTime": "#ChangeDateTime#",
                    "GroupCode": "",
                    "ReasonCode": "#changeReasonCode#",
                    "ChangeReasonMemo": "#ChangeReasonMemo#",
                    "ResolutionCode": javaCast("null", ""),
                    "ErrorCode": javaCast("null", ""),
                    "ErrorMessage": javaCast("null", "")
                }
            ]>
            
            <!--- Log VisitChanges data for debugging with source information --->
            <cfif GetReasonCodeInfo.recordcount GT 0 AND Len(Trim(GetReasonCodeInfo.Change_Memo)) GT 0>
                <cfset memoSource = "EVV_Update_Log">
            <cfelse>
                <cfset memoSource = "Empty/Not Set (Clinician must enter in EVV Update Log)">
            </cfif>
            <cflog file="AHCCCS_Visit_Changes" text="Schedule_ID=#Sch_ID#, isVisitUpdate=true, ReasonCode=#changeReasonCode#, ChangeMadeBy=#ChangeMadeByEmail#, ChangeDateTime=#ChangeDateTime#, ChangeReasonMemo=[#ChangeReasonMemo#], ChangeReasonMemoLength=#Len(ChangeReasonMemo)#, MemoSource=#memoSource#, EVV_Update_Log.Change_Memo=[#GetReasonCodeInfo.Change_Memo#]">
        <cfelse>
            <!--- Log when VisitChanges is NOT included (initial submission) --->
            <cflog file="AHCCCS_Visit_Changes" text="Schedule_ID=#Sch_ID#, isVisitUpdate=false, CallType=#CallType# - VisitChanges section NOT included (initial submission)">
        </cfif>
        
        <!--- Add VisitExceptionAcknowledgement only if patient did not sign (tasks not verified) --->
        <cfif NeedExceptionAcknowledgement>
            <cfset visitData["VisitExceptionAcknowledgement"] = [{
                "ExceptionID": "40",
                "ExceptionAcknowledged": true
            }]>
        <cfelse>
            <cfset visitData["VisitExceptionAcknowledgement"] = []>
        </cfif>
        
        <!--- Log final ChangeReasonMemo value before JSON serialization --->
        <cfif isVisitUpdate OR CallType EQ "Manual">
            <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | FINAL ChangeReasonMemo before SerializeJSON: [#ChangeReasonMemo#] | Length=#Len(ChangeReasonMemo)# | isVisitUpdate=#isVisitUpdate# | CallType=#CallType#">
        </cfif>
        
        <cfset Request.stFields = [visitData]>
        <cfset jsonPayload = SerializeJSON(Request.stFields)>
        
        <!--- Log the VisitChanges section of the JSON if it exists --->
        <cfif structKeyExists(visitData, "VisitChanges") AND isArray(visitData.VisitChanges) AND arrayLen(visitData.VisitChanges) GT 0>
            <cfset visitChangesJSON = SerializeJSON(visitData.VisitChanges)>
            <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#Sch_ID# | VisitChanges JSON: #visitChangesJSON#">
        </cfif>
        
        <!--- If not confirmed, return preview of data for user confirmation --->
        <cfif NOT arguments.confirmed OR arguments.confirmed EQ "false">
            <cfset confirmationHTML = "">
            <cfsavecontent variable="confirmationHTML">
                <cfoutput>
                <div style="font-family: Arial, sans-serif; padding: 20px; max-width: 800px;">
                    <h2 style="color: ##333; border-bottom: 2px solid ##007bff; padding-bottom: 10px;">Visit Data Confirmation</h2>
                    <p style="background-color: ##fff3cd; padding: 10px; border-left: 4px solid ##ffc107;">
                        <strong>Please review the following data before submission:</strong>
                    </p>
                    
                    <h3 style="color: ##007bff; margin-top: 20px;">Visit Information</h3>
                    <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Patient Name:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#GtSched.PatientFirst# #GtSched.PatientLast#</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Patient ID:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#GtSched.Patient_ID#</td>
                        </tr>
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Client Identifier (Medicaid ID):</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#ClientIdentifier# </td>
                        </tr>
                        <tr>
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Schedule ID:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#GtSched.Schedule_ID#</td>
                        </tr>
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Visit Date:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#DateFormat(GtSched.Visit_Date, "yyyy-mm-dd")#</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Visit Type:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#GtSched.Type#</td>
                        </tr>
                    </table>
                    
                    <h3 style="color: ##007bff;">Employee Information</h3>
                    <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Employee Name:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#GtSched.Emp_First# #GtSched.Emp_Last#</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Employee ID:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#GtSched.Emp_ID#</td>
                        </tr>
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Employee Identifier:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#EmployeeIdentifier#</td>
                        </tr>
                    </table>
                    
                    <h3 style="color: ##007bff;">Time Information</h3>
                    <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Scheduled Start Time:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#Start_Time#</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Scheduled End Time:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#End_Time#</td>
                        </tr>
                        <cfif Start_Time NEQ "">
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Actual Start Time:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#Start_Time#</td>
                        </tr>
                        </cfif>
                        <cfif  End_Time NEQ "">
                        <tr>
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Actual End Time:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#End_Time#</td>
                        </tr>
                        </cfif>
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Hours to Bill:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#Total_Hours#</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Hours to Pay:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#Total_Hours#</td>
                        </tr>
                    </table>
                    
                    <h3 style="color: ##007bff;">Billing Information</h3>
                    <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Provider ID:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#LOCAL.ProviderID#</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Payer ID:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#PayerID#</td>
                        </tr>
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Payer Program:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#PayerProgram#</td>
                        </tr>
                        <tr>
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Procedure Code (HCPCS):</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#ProcedureCode#</td>
                        </tr>
                        <cfif Len(Modifier1Value) GT 0>
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Modifier:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#Modifier1Value#</td>
                        </tr>
                        </cfif>
                        <tr style="background-color: ##f8f9fa;">
                            <td style="padding: 10px; border: 1px solid ##dee2e6; font-weight: bold;">Sequence ID:</td>
                            <td style="padding: 10px; border: 1px solid ##dee2e6;">#Seq_ID#</td>
                        </tr>
                    </table>
                    
                    <cfif Len(Trim(GtSched.Memo)) GT 0>
                    <h3 style="color: ##007bff;">Notes/Memo</h3>
                    <div style="padding: 10px; border: 1px solid ##dee2e6; background-color: ##f8f9fa; margin-bottom: 20px;">
                        #Left(Trim(GtSched.Memo), 511)#
                    </div>
                    </cfif>
                    
                    <div style="background-color: ##fff3cd; padding: 20px; border-left: 4px solid ##ffc107; margin-top: 30px; text-align: center;">
                        <p style="margin: 0 0 20px 0; font-weight: bold; color: ##856404; font-size: 18px;">
                            Is all the information correct?
                        </p>
                        <div style="margin-top: 15px;">
                            <button class="confirm-btn" onclick="confirmSubmission()" style="background-color: ##28a745; color: white; padding: 12px 40px; border: none; border-radius: 5px; font-size: 16px; font-weight: bold; cursor: pointer; margin-right: 15px; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">
                                ✓ Yes, Submit Visit
                            </button>
                            <button class="confirm-btn" onclick="cancelSubmission()" style="background-color: ##dc3545; color: white; padding: 12px 40px; border: none; border-radius: 5px; font-size: 16px; font-weight: bold; cursor: pointer; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">
                                ✗ No, Cancel
                            </button>
                        </div>
                    </div>
                    
                    <details style="margin-top: 20px;">
                        <summary style="cursor: pointer; padding: 10px; background-color: ##e9ecef; border: 1px solid ##dee2e6; font-weight: bold;">
                            View JSON Payload (Click to expand)
                        </summary>
                        <pre style="background-color: ##f8f9fa; padding: 15px; border: 1px solid ##dee2e6; overflow-x: auto; margin-top: 0;">#jsonPayload#</pre>
                    </details>
                    
                    <div id="resultMessage" style="margin-top: 20px;"></div>
                    
                    <script>
                    function confirmSubmission() {
                        // Show loading message
                        document.getElementById('resultMessage').innerHTML = '<div style="background-color: ##d1ecf1; padding: 15px; border-left: 4px solid ##0dcaf0; text-align: center;"><strong>Processing...</strong> Please wait while we submit the visit data.</div>';
                        
                        // Disable only the confirmation buttons to prevent double submission
                        var buttons = document.querySelectorAll('.confirm-btn');
                        buttons.forEach(function(btn) {
                            btn.disabled = true;
                            btn.style.opacity = '0.5';
                            btn.style.cursor = 'not-allowed';
                        });
                        
                        // Call the API with confirmed=true
                        var scheduleId = '#arguments.Schedule_ID#';
                        var agencyId = '#arguments.Agency_ID#';
                        
                        // Use AJAX to call the function with confirmed=true
                        var xhr = new XMLHttpRequest();
                        xhr.open('POST', '/components/sandata/AHCCCS.cfc?method=visit_creation', true);
                        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                        
                        xhr.onload = function() {
                            if (xhr.status === 200) {
                                // Show success message with OK button
                                document.getElementById('resultMessage').innerHTML = '<div style="background-color: ##d4edda; padding: 15px; border-left: 4px solid ##28a745; text-align: center;"><strong>Success!</strong><br>' + xhr.responseText + '<br><br><button id="okCloseBtn" style="background-color: ##28a745; color: white; padding: 10px 30px; border: none; border-radius: 5px; font-size: 14px; font-weight: bold; cursor: pointer; margin-top: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.2);">OK</button></div>';
                                
                                // Add event listener to OK button
                                setTimeout(function() {
                                    document.getElementById('okCloseBtn').addEventListener('click', function() {
                                        // Try multiple methods to close the window/modal
                                        try {
                                            // Method 1: Close popup window
                                            if (window.opener) {
                                                window.close();
                                                return;
                                            }
                                            
                                            // Method 2: Close parent window if in iframe
                                            if (window.parent && window.parent !== window) {
                                                window.parent.close();
                                                return;
                                            }
                                            
                                            // Method 3: Try to close using self.close
                                            window.self.close();
                                        } catch(e) {
                                            // If all methods fail, hide the body and show message
                                            document.body.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100vh; font-family: Arial;"><div style="text-align: center;"><h2>Success!</h2><p>You can now close this window.</p></div></div>';
                                        }
                                    });
                                }, 100);
                            } else {
                                // Show error message
                                document.getElementById('resultMessage').innerHTML = '<div style="background-color: ##f8d7da; padding: 15px; border-left: 4px solid ##dc3545; text-align: center;"><strong>Error!</strong><br>Failed to submit visit data. Please try again.</div>';
                                // Re-enable buttons
                                buttons.forEach(function(btn) {
                                    btn.disabled = false;
                                    btn.style.opacity = '1';
                                    btn.style.cursor = 'pointer';
                                });
                            }
                        };
                        
                        xhr.onerror = function() {
                            document.getElementById('resultMessage').innerHTML = '<div style="background-color: ##f8d7da; padding: 15px; border-left: 4px solid ##dc3545; text-align: center;"><strong>Error!</strong><br>Network error occurred. Please try again.</div>';
                            // Re-enable buttons
                            buttons.forEach(function(btn) {
                                btn.disabled = false;
                                btn.style.opacity = '1';
                                btn.style.cursor = 'pointer';
                            });
                        };
                        
                        xhr.send('Schedule_ID=' + encodeURIComponent(scheduleId) + '&Agency_ID=' + encodeURIComponent(agencyId) + '&confirmed=true');
                    }
                    
                    function cancelSubmission() {
                        if (confirm('Are you sure you want to cancel? No data will be submitted.')) {
                            // Close the window immediately on cancel (parent page stays the same)
                            if (window.opener) {
                                // If opened as popup, just close it (parent page stays)
                                window.close();
                            } else {
                                // If in iframe or same window, show message and stay on page
                                document.getElementById('resultMessage').innerHTML = '<div style="background-color: ##f8d7da; padding: 15px; border-left: 4px solid ##dc3545; text-align: center;"><strong>Cancelled</strong><br>Visit submission has been cancelled. No data was sent to the API.</div>';
                            }
                        }
                    }
                    </script>
                </div>
                
                <!--- 
                Include debug comparison table if available (only for IP 103.143.7.161) - COMMENTED OUT
                <cfif isDefined('Request.debugComparisonTable') AND Len(Trim(Request.debugComparisonTable))>
                    #Request.debugComparisonTable#
                </cfif>
                --->
                </cfoutput>
            </cfsavecontent>
            <cfreturn confirmationHTML>
        </cfif>
        
        <!--- If confirmed, proceed with API submission --->
        <cfset LOCAL.RestStartTime = GetTickCount()>
        <cfhttp 
            url         = "#LOCAL.AuthorizationEndpoint#"
            method      = "POST" 
            timeout     = "100"
            result      = "httpEVVResponse">
            <cfhttpparam name="Content-Type" type="HEADER" value="application/json">
            <cfhttpparam name="Accept" type="HEADER" value="application/json">
            <cfhttpparam name="account" type="HEADER" value="#LOCAL.account#">
            <cfhttpparam type="body" value="#jsonPayload#">
        </cfhttp>
        <cfset LOCAL.RestEndTime = GetTickCount()>
        <cfset LOCAL.returnFaxSendResult.FaxProcessTime = NumberFormat((LOCAL.RestEndTime - LOCAL.RestStartTime)/1000,'__.___')>
        <cfset return_status = "failure">
        <cfif httpEVVResponse.responseHeader.Status_Code contains "200">
            <cfset structureData = DeserializeJSON(httpEVVResponse.Filecontent)>
            <cfset api_return_status = structureData.status>
            <cfset UUID = structureData.id />
            
            <!--- Extract reason from response data if available --->
            <cfif structKeyExists(structureData, "data") AND isStruct(structureData.data) AND structKeyExists(structureData.data, "reason")>
                <cfset api_return_status = structureData.data.reason />
            </cfif>
            
            <!--- Set initial status to "Transmitted - Initial submission" instead of API status --->
            <!--- Status will be updated to actual status (Transaction Received, etc) when check_visit_status is called --->
            <cfset return_status = "Transmitted - Initial submission">
            
            <cfif api_return_status EQ 'SUCCESS' OR FindNoCase('Transaction Received', api_return_status) GT 0>
                <cfmail to="#sendto_email#" from="info@myhomecarebiz.com" subject="#envLabel# AHCCCS Visit Upload Success - #GtSched.PatientFirst#, #GtSched.PatientLast# (#GtSched.Patient_ID#)" type="html">
                    <h3>AHCCCS Visit Upload Successful</h3>
                    <p><strong>Visit Information:</strong></p>
                    <ul>
                        <li><strong>Patient Name:</strong> #GtSched.PatientFirst# #GtSched.PatientLast#</li>
                        <li><strong>Patient ID:</strong> #GtSched.Patient_ID#</li>
                        <li><strong>Schedule ID:</strong> #GtSched.Schedule_ID#</li>
                        <li><strong>Employee:</strong> #GtSched.Emp_First# #GtSched.Emp_Last#</li>
                        <li><strong>Visit Date:</strong> #DateFormat(GtSched.Visit_Date, "yyyy-mm-dd")#</li>
                        <li><strong>Visit Type:</strong> #GtSched.Type#</li>
                        <li><strong>Agency ID:</strong> #session.agencyid#</li>
                        <li><strong>Sequence ID:</strong> #Seq_ID#</li>
                    </ul>
                    
                    <p><strong>API Response:</strong></p>
                    <ul>
                        <li><strong>UUID:</strong> #UUID#</li>
                        <li><strong>API Status:</strong> #api_return_status#</li>
                        <li><strong>Initial Status (in system):</strong> #return_status#</li>
                        <li><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</li>
                    </ul>
                    
                    <p><strong>API Request Payload:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#jsonPayload#</pre>
                    
                    <p><strong>API Response Data:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#SerializeJSON(structureData)#</pre>
                    
                    <p>The visit has been successfully uploaded to AHCCCS EVV system with initial status "Transmitted - Initial submission". Use check status to get the current transaction status.</p>
                </cfmail>
        <cfelse>
                <!--- Parse error response for FAILED status --->
                <cfset error_details = "">
                <cfset error_summary = "">
                
                <!--- Extract error details from response --->
                <cfif structKeyExists(structureData, "messageSummary") AND NOT isNull(structureData.messageSummary)>
                    <cfset error_summary = structureData.messageSummary>
        </cfif>
                
                <!--- Extract detailed errors from data array --->
                <cfif structKeyExists(structureData, "data") AND isArray(structureData.data)>
                    <cfloop array="#structureData.data#" index="item">
                        <cfif structKeyExists(item, "ErrorMessage") AND NOT isNull(item.ErrorMessage)>
                            <cfset error_details = error_details & item.ErrorMessage & "<br>" />
                        </cfif>
                    </cfloop>
                </cfif>
                
                <!--- Extract errors from errors array --->
                <cfif structKeyExists(structureData, "errors") AND isArray(structureData.errors)>
                    <cfloop array="#structureData.errors#" index="errorItem">
                        <cfif structKeyExists(errorItem, "Errors") AND isArray(errorItem.Errors)>
                            <cfloop array="#errorItem.Errors#" index="err">
                                <cfif structKeyExists(err, "ErrorMessage") AND NOT isNull(err.ErrorMessage)>
                                    <cfset error_details = error_details & err.ErrorMessage & " (Code: " & err.ErrorCode & ")<br>" />
                                </cfif>
                            </cfloop>
                        </cfif>
                    </cfloop>
                </cfif>
                
                <cfif error_details EQ "">
                    <cfset error_details = "Visit upload failed - no specific error details available">
        </cfif>

                <!--- Set return_status to error summary instead of FAILED --->
                <cfset return_status = error_summary>
                
                <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Visit Upload Failed - #GtSched.PatientFirst#, #GtSched.PatientLast# (#GtSched.Patient_ID#)" type="html">
                    <h3>AHCCCS Visit Upload Failed</h3>
                    <p><strong>Visit Information:</strong></p>
                    <ul>
                        <li><strong>Patient Name:</strong> #GtSched.PatientFirst# #GtSched.PatientLast#</li>
                        <li><strong>Patient ID:</strong> #GtSched.Patient_ID#</li>
                        <li><strong>Schedule ID:</strong> #GtSched.Schedule_ID#</li>
                        <li><strong>Employee:</strong> #GtSched.Emp_First# #GtSched.Emp_Last#</li>
                        <li><strong>Visit Date:</strong> #DateFormat(GtSched.Visit_Date, "yyyy-mm-dd")#</li>
                        <li><strong>Visit Type:</strong> #GtSched.Type#</li>
                        <li><strong>Agency ID:</strong> #session.agencyid#</li>
                        <li><strong>Sequence ID:</strong> #Seq_ID#</li>
                    </ul>
                    
                    <p><strong>Error Summary:</strong></p>
                    <div style="background-color: ##ffe6e6; padding: 10px; border-left: 4px solid ##ff0000; margin: 10px 0;">
                        #error_summary#
                    </div>
                    
                    <p><strong>Error Details:</strong></p>
                    <div style="background-color: ##fff3cd; padding: 10px; border-left: 4px solid ##ffc107; margin: 10px 0;">
                        #error_details#
                    </div>
                    
                    <p><strong>API Request Payload:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#jsonPayload#</pre>
                    
                    <p><strong>API Response Data:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#httpEVVResponse.FileContent#</pre>
                    
                    <p><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</p>
                    
                    <p>The visit upload failed. Please check the error details above.</p>
                </cfmail>
                
                <!--- Return detailed error information --->
                <cfreturn error_summary & " - " & error_details>
        </cfif>
            <cfquery name="INSERT_EVV" datasource="#Application.DataSrc#" result="evvResult">
                INSERT INTO #Request.prefix_db_lookup#.EVV 
                (UUID, Seq_ID, San_status, API_type, Agency_ID, Patient_ID, Emp_ID, Schedule_ID, Date_Create, Created_by)
                VALUES
                ('#UUID#', '#Seq_ID#','#return_status#', 'visits', '#session.agencyid#', #GtSched.Patient_ID#, #GtSched.Emp_ID#, #GtSched.Schedule_ID#, #now()#, #session.employeeid#)
        </cfquery>
        
        <!--- Log to EVV_Update_Log - ONLY for retransmissions, not initial submissions --->
        <!--- Initial submissions don't need a log entry since nothing was changed --->
        <cfif isVisitUpdate>
            <!--- Mark any existing EVV_Update_Log records for this schedule as inactive --->
            <!--- Each new update gets a fresh log entry with blank memo and NULL reason code --->
            <cfquery name="DEACTIVATE_OLD_LOGS" datasource="#Application.DataSrc#">
                UPDATE #Request.prefix_db_lookup#.EVV_Update_Log
                SET Status = 1
                WHERE Schedule_ID = <cfqueryparam value="#GtSched.Schedule_ID#" cfsqltype="cf_sql_integer">
                AND Status = 0
            </cfquery>
            
            <!--- Extract ChangeReasonMemo directly from the JSON structure to ensure it matches exactly what was sent --->
            <cfset jsonChangeReasonMemo = "">
            <cfif structKeyExists(visitData, "VisitChanges") AND isArray(visitData.VisitChanges) AND arrayLen(visitData.VisitChanges) GT 0>
                <cfif structKeyExists(visitData.VisitChanges[1], "ChangeReasonMemo")>
                    <cfset jsonChangeReasonMemo = visitData.VisitChanges[1].ChangeReasonMemo>
                    <!--- Use the exact value from JSON structure to ensure it matches what was sent --->
                    <cfset ChangeReasonMemo = jsonChangeReasonMemo>
                </cfif>
            </cfif>
            
            <!--- Log the ChangeReasonMemo value that will be inserted to ensure it matches the JSON --->
            <cflog file="AHCCCS_ChangeReasonMemo" text="Schedule_ID=#GtSched.Schedule_ID# | INSERTING into EVV_Update_Log | ChangeReasonMemo from JSON=[#jsonChangeReasonMemo#] | ChangeReasonMemo variable=[#ChangeReasonMemo#] | JSON Length=#Len(jsonChangeReasonMemo)# | Variable Length=#Len(ChangeReasonMemo)# | This should match the JSON value">
            
            <cfquery name="INSERT_EVV_LOG" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_lookup#.EVV_Update_Log (
                    Schedule_ID,
                    Agency_ID,
                    EVV_ID,
                    Date_Updated,
                    Change_Memo,
                    Changed_By,
                    Changed_By_Email,
                    Reason_Code_ID,
                    Status
                ) VALUES (
                    <cfqueryparam value="#GtSched.Schedule_ID#" cfsqltype="cf_sql_integer">,
                    <cfqueryparam value="#session.agencyid#" cfsqltype="cf_sql_integer">,
                    <cfqueryparam value="#evvResult.GENERATED_KEY#" cfsqltype="cf_sql_integer">,
                    <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                    <!--- Use the exact ChangeReasonMemo value from the JSON structure to ensure it matches what was sent --->
                    <cfqueryparam value="#ChangeReasonMemo#" cfsqltype="cf_sql_longvarchar" null="#NOT len(trim(ChangeReasonMemo))#">,
                    <cfqueryparam value="#session.employeeid#" cfsqltype="cf_sql_integer">,
                    <!--- Use ChangeMadeByEmail which has proper priority: EVV_Update_Log > Change_by employee > Visit employee --->
                    <cfqueryparam value="#ChangeMadeByEmail#" cfsqltype="cf_sql_varchar">,
                    <!--- Get Reason_Code_ID from EVV_Update_Log instead of pSchedules --->
                    <cfif GetReasonCodeInfo.recordcount GT 0 AND isDefined('GetReasonCodeInfo.Reason_Code_ID') AND isNumeric(GetReasonCodeInfo.Reason_Code_ID) AND GetReasonCodeInfo.Reason_Code_ID GT 0>
                        <cfqueryparam value="#GetReasonCodeInfo.Reason_Code_ID#" cfsqltype="cf_sql_integer">,
                    <cfelse>
                        NULL,
                    </cfif>
                    0
                )
            </cfquery>
        </cfif>
        
        <cfelse>
            <cfset structureData = DeserializeJSON(httpEVVResponse.Filecontent)>
            <cfset responseStruct = structureData>
            <cfset UUID = "N/A">
            <cfif structKeyExists(responseStruct, "data") AND isArray(responseStruct.data)>
                <cfset return_status = "">
                <cfloop array="#responseStruct.data#" index="item">
                    <!--- Check top-level ErrorMessage --->
                    <cfif structKeyExists(item, "ErrorMessage") AND NOT isNull(item.ErrorMessage)>
                        <cfset errorList = listToArray(item.ErrorMessage, "|")>
                        <!--- Display each error line by line --->
                        <cfoutput>
                            <cfloop array="#errorList#" index="err">
                                <cfif len(trim(err)) GT 0>
                                    <cfset return_status = return_status & trim(err) & "<br>" />
                                </cfif>
                            </cfloop>
        </cfoutput>
                    </cfif>
                </cfloop>
            </cfif>
            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Visit Upload Error - #GtSched.PatientFirst#, #GtSched.PatientLast# (#GtSched.Patient_ID#)" type="html">
                <h3>AHCCCS Visit Upload Error</h3>
                <p><strong>Visit Information:</strong></p>
                <ul>
                    <li><strong>Patient Name:</strong> #GtSched.PatientFirst# #GtSched.PatientLast#</li>
                    <li><strong>Patient ID:</strong> #GtSched.Patient_ID#</li>
                    <li><strong>Schedule ID:</strong> #GtSched.Schedule_ID#</li>
                    <li><strong>Employee:</strong> #GtSched.Emp_First# #GtSched.Emp_Last#</li>
                    <li><strong>Visit Date:</strong> #DateFormat(GtSched.Visit_Date, "yyyy-mm-dd")#</li>
                    <li><strong>Visit Type:</strong> #GtSched.Type#</li>
                    <li><strong>Agency ID:</strong> #session.agencyid#</li>
                    <li><strong>Sequence ID:</strong> #Seq_ID#</li>
                </ul>
                
                <p><strong>Error Details:</strong></p>
                <div style="background-color: ##ffe6e6; padding: 10px; border-left: 4px solid ##ff0000; margin: 10px 0;">
                    #return_status#
                </div>
                
                <p><strong>API Request Payload:</strong></p>
                <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#jsonPayload#</pre>
                
                <p><strong>API Response Data:</strong></p>
                <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#httpEVVResponse.FileContent#</pre>
                
                <p><strong>HTTP Response Code:</strong> #httpEVVResponse.responseHeader.Status_Code#</p>
                <p><strong>Upload Date:</strong> #DateFormat(now(), "yyyy-mm-dd")# #TimeFormat(now(), "HH:mm:ss")#</p>
                
                <p>The visit upload encountered an error. Please check the error details above.</p>
            </cfmail>
        </cfif>
            <cfreturn return_status>
            <cfcatch>
                <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# Powerpath EVV Visit API Error" type="html">
                    <cfdump var="#cfcatch#">
                </cfmail> 
            </cfcatch>
        </cftry>

    </cffunction>

    <cffunction name="check_client_status" access="remote" returnFormat= "json">
        <cfargument name="Agency_ID" required="no" hint="Agency_ID" default="#session.agencyId#">
        <cfargument name="Patient_ID" required="yes" default="0" hint="Patient_ID">

        <cfset Patient_ID = decrypt(#arguments.Patient_ID#,#application.enckey#,"AES","Hex") />
        
        <!--- Initialize LOCAL variables --->
        <cfif application.DEV EQ false>
            <!--- PROD subscription keys --->
            <cfset LOCAL.subscription_key_primary = "3f11f04e0fd74ad39c77c8cacbfef240">
            <cfset LOCAL.subscription_key_secondary = "3710f5d7890241d3beb7181e2b506f8b">
        <cfelse>
            <!--- DEV subscription keys --->
        <cfset LOCAL.subscription_key_primary = "b3446ef5e2ce497dbc9da4007b574c8b">
        <cfset LOCAL.subscription_key_secondary = "1c88925161e94f4cae914d91ad0c077c">
        </cfif>
        <cfset LOCAL.account = "a2f47e6e-5f6b-0e9b-c2c6-e003c1b48ac9">
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- Use server name in email subject --->
        <cfset envLabel = #Application.ServerName# />
        
        <!--- Get agency settings from database --->
        <cfquery name="getagency" datasource="#Application.DataSrc#">
            SELECT * FROM  #Request.prefix_db_lookup#.Agency
            WHERE Agency_ID = '#session.agencyId#'
            <cfif application.DEV EQ false>  
                AND EVV_prod_username IS NOT NULL
                AND EVV_prod_password IS NOT NULL
            <cfelse>
                AND EVV_username IS NOT NULL
                AND EVV_password IS NOT NULL
            </cfif>
        </cfquery>
        
        <cfif getagency.recordcount gt 0>
            <cfif application.DEV EQ false>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
            <cfelse>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
            </cfif>
        </cfif>

        <cftry>
            <!--- Get patient information --->
            <cfquery name="GetPatientInfo" datasource="#Application.DataSrc#">
                SELECT Pt_First, Pt_Last FROM #Request.prefix_db_agency#.pPatients 
                WHERE Patient_ID = '#Patient_ID#'
                AND status IN (0,1,4)
            </cfquery>
            
            <!--- Get UUID from EVV table for the client --->
            <cfquery name="GetEVVUUID" datasource="#Application.DataSrc#">
                SELECT UUID FROM #Request.prefix_db_lookup#.EVV
                WHERE API_Type = 'clients'
                AND Agency_ID = '#session.agencyid#'
                AND status = 0
                AND Patient_ID = '#Patient_ID#'
                ORDER BY EVV_ID DESC LIMIT 1
            </cfquery>

            <cfif GetEVVUUID.recordcount GT 0>
                <cfset LOCAL.uuid = GetEVVUUID.UUID>
                
                <!--- Determine the correct API endpoint based on environment --->
                <cfif application.DEV EQ false>
                    <cfset LOCAL.statusEndpoint = "https://si-api.azahcccs.gov/evv/aggregation/v1/clients/status?uuid=#LOCAL.uuid#&key=" & LOCAL.subscription_key_primary>
                <cfelse>
                    <cfset LOCAL.statusEndpoint = "https://si-api.azahcccs.gov/test/evv/aggregation/v1/clients/status?uuid=#LOCAL.uuid#&key=" & LOCAL.subscription_key_primary>
                </cfif>
                
                <!--- Make API call to AHCCCS status endpoint --->
                <cfhttp 
                    url="#LOCAL.statusEndpoint#"
                    method="GET" 
                    timeout="100"
                    result="httpStatusResponse">
                    <cfhttpparam name="Content-Type" type="HEADER" value="application/json">
                    <cfhttpparam name="Accept" type="HEADER" value="application/json">
                    <cfhttpparam name="account" type="HEADER" value="#LOCAL.account#">
                </cfhttp>

                <cfset return_status = "Pending">
                <cfset currentStatus = "Pending">
                
                <!--- Parse status response and update EVV table --->
                <cfif httpStatusResponse.StatusCode EQ "200" OR httpStatusResponse.StatusCode CONTAINS "200">
                    <cfset statusResponseData = DeserializeJSON(httpStatusResponse.FileContent)>
                    <cfset currentStatus = "SUCCESS">
                    
                    <!--- Extract reason from status response if available --->
                    <cfif structKeyExists(statusResponseData, "data") AND isStruct(statusResponseData.data) AND structKeyExists(statusResponseData.data, "reason")>
                        <cfset currentStatus = trim(statusResponseData.data.reason) />
                        <!--- Remove trailing period if present --->
                        <cfif right(currentStatus, 1) EQ ".">
                            <cfset currentStatus = left(currentStatus, len(currentStatus) - 1) />
                        </cfif>
                    </cfif>
                    
                    <!--- Log the extracted status for debugging --->
                    <cflog file="AHCCCS_Client_Status" text="check_client_status: Patient_ID=#Patient_ID#, UUID=#LOCAL.uuid#, Extracted Status='#currentStatus#'">
                    
                    <!--- Update EVV table with current status --->
                    <cfquery name="UPDATE_EVV_STATUS" datasource="#Application.DataSrc#" result="updateResult">
                        UPDATE #Request.prefix_db_lookup#.EVV 
                        SET San_status = <cfqueryparam value="#currentStatus#" cfsqltype="cf_sql_varchar">,
                            Date_Update = NOW()
                        WHERE UUID = <cfqueryparam value="#LOCAL.uuid#" cfsqltype="cf_sql_varchar">
                        AND API_Type = 'clients'
                        AND Agency_ID = '#session.agencyid#'
                        AND Patient_ID = '#Patient_ID#'
                        AND status = 0
                    </cfquery>
                    
                    <!--- Log update result --->
                    <cflog file="AHCCCS_Client_Status" text="check_client_status: Updated #updateResult.recordcount# EVV record(s) for Patient_ID=#Patient_ID# with status '#currentStatus#'">
                    
                    <cfset return_status = currentStatus>
                </cfif>
                
                <!--- Send email notification --->
                <cfmail to="#sendto_email#" from="info@myhomecarebiz.com" subject="#envLabel# AHCCCS Client Status Check - #GetPatientInfo.Pt_First#, #GetPatientInfo.Pt_Last# (#Patient_ID#)" type="html">
                    <h3>AHCCCS Client Status Check Results</h3>
                    <p><strong>Patient Name:</strong> #GetPatientInfo.Pt_First#, #GetPatientInfo.Pt_Last#</p>
                    <p><strong>Patient ID:</strong> #Patient_ID#</p>
                    <p><strong>UUID:</strong> #LOCAL.uuid#</p>
                    <p><strong>Status Check Time:</strong> #now()#</p>
                    <p><strong>Current EVV Status:</strong> <span style="color: ##28a745; font-weight: bold;">#currentStatus#</span></p>
                    <hr>
                    <p><strong>Full API Response:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#httpStatusResponse.Filecontent#</pre>
                </cfmail>
                
            <cfelse>
                <cfset return_status = "No UUID found for client #Patient_ID#">
                
                <!--- Send error email notification --->
                <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Client Status Check Error - #GetPatientInfo.Pt_First#, #GetPatientInfo.Pt_Last# (#Patient_ID#)" type="html">
                    <h3>AHCCCS Client Status Check Error</h3>
                    <p><strong>Patient Name:</strong> #GetPatientInfo.Pt_First#, #GetPatientInfo.Pt_Last#</p>
                    <p><strong>Patient ID:</strong> #Patient_ID#</p>
                    <p><strong>Error:</strong> No UUID found for this client in EVV table</p>
                    <p><strong>Status Check Time:</strong> #now()#</p>
                </cfmail>
                
                <!--- Return error response as JSON --->
                <cfreturn {
                    "success" = false,
                    "message" = "No UUID found for client",
                    "status" = "error",
                    "patientId" = Patient_ID,
                    "data" = {
                        "reason" = return_status,
                        "status" = "error"
                    }
                }>
            </cfif>
            
        <cfcatch type="any">
            <cfset return_status = "Error: #cfcatch.message#">
            
            <!--- Send error email notification --->
            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Client Status Check Error - #GetPatientInfo.Pt_First#, #GetPatientInfo.Pt_Last# (#Patient_ID#)" type="html">
                <h3>AHCCCS Client Status Check Error</h3>
                <p><strong>Patient Name:</strong> #GetPatientInfo.Pt_First#, #GetPatientInfo.Pt_Last#</p>
                <p><strong>Patient ID:</strong> #Patient_ID#</p>
                <p><strong>Error:</strong> #cfcatch.message#</p>
                <p><strong>Status Check Time:</strong> #now()#</p>
            </cfmail>
            
            <!--- Return error response as JSON --->
            <cfreturn {
                "success" = false,
                "message" = cfcatch.message,
                "status" = "error",
                "patientId" = Patient_ID,
                "data" = {
                    "reason" = return_status,
                    "status" = "error"
                }
            }>
        </cfcatch>
        </cftry>
        
        <!--- Return success response as JSON --->
        <cfreturn {
            "success" = true,
            "message" = "Status retrieved successfully",
            "status" = return_status,
            "patientId" = Patient_ID,
            "data" = {
                "reason" = return_status,
                "status" = return_status
            }
        }>
    </cffunction>

    <cffunction name="check_employee_status" access="remote" returnFormat= "json">
        <cfargument name="Agency_ID" required="no" hint="Agency_ID" default="#session.agencyId#">
        <cfargument name="Emp_ID" required="yes" default="0" hint="Employee_ID">

        <cfset Employee_ID = decrypt(#arguments.Emp_ID#,#application.enckey#,"AES","Hex") />
        
        <!--- Initialize LOCAL variables --->
        <cfif application.DEV EQ false>
            <!--- PROD subscription keys --->
            <cfset LOCAL.subscription_key_primary = "3f11f04e0fd74ad39c77c8cacbfef240">
            <cfset LOCAL.subscription_key_secondary = "3710f5d7890241d3beb7181e2b506f8b">
        <cfelse>
            <!--- DEV subscription keys --->
        <cfset LOCAL.subscription_key_primary = "b3446ef5e2ce497dbc9da4007b574c8b">
        <cfset LOCAL.subscription_key_secondary = "1c88925161e94f4cae914d91ad0c077c">
        </cfif>
        <cfset LOCAL.account = "a2f47e6e-5f6b-0e9b-c2c6-e003c1b48ac9">
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- Use server name in email subject --->
        <cfset envLabel = #Application.ServerName# />
        
        <!--- Get agency settings from database --->
        <cfquery name="getagency" datasource="#Application.DataSrc#">
            SELECT * FROM  #Request.prefix_db_lookup#.Agency
            WHERE Agency_ID = '#session.agencyId#'
            <cfif application.DEV EQ false>  
                AND EVV_prod_username IS NOT NULL
                AND EVV_prod_password IS NOT NULL
            <cfelse>
                AND EVV_username IS NOT NULL
                AND EVV_password IS NOT NULL
            </cfif>
        </cfquery>
        
        <cfif getagency.recordcount gt 0>
            <cfif application.DEV EQ false>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
            <cfelse>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
            </cfif>
        </cfif>

        <cftry>
            <!--- Get employee information --->
            <cfquery name="GetEmpInfo" datasource="#Application.DataSrc#">
                SELECT Emp_First, Emp_Last FROM #Request.prefix_db_lookup#.pEmployee 
                WHERE Emp_ID = '#Employee_ID#'
                AND status = 0
            </cfquery>
            
            <!--- Get UUID from EVV table for the employee --->
            <cfquery name="GetEVVUUID" datasource="#Application.DataSrc#">
                SELECT UUID FROM #Request.prefix_db_lookup#.EVV
                WHERE API_Type = 'employee'
                AND Agency_ID = '#session.agencyid#'
                AND status = 0
                AND Emp_ID = '#Employee_ID#'
                ORDER BY EVV_ID DESC LIMIT 1
            </cfquery>

            <cfif GetEVVUUID.recordcount GT 0>
                <cfset LOCAL.uuid = GetEVVUUID.UUID>
                
                <!--- Determine the correct API endpoint based on environment --->
                <cfif application.DEV EQ false>
                    <cfset LOCAL.statusEndpoint = "https://si-api.azahcccs.gov/evv/aggregation/v1/employees/status?uuid=#LOCAL.uuid#&key=" & LOCAL.subscription_key_primary>
                <cfelse>
                    <cfset LOCAL.statusEndpoint = "https://si-api.azahcccs.gov/test/evv/aggregation/v1/employees/status?uuid=#LOCAL.uuid#&key=" & LOCAL.subscription_key_primary>
                </cfif>
                
                <!--- Make API call to AHCCCS status endpoint --->
                <cfhttp 
                    url="#LOCAL.statusEndpoint#"
                    method="GET" 
                    timeout="100"
                    result="httpStatusResponse">
                    <cfhttpparam name="Content-Type" type="HEADER" value="application/json">
                    <cfhttpparam name="Accept" type="HEADER" value="application/json">
                    <cfhttpparam name="account" type="HEADER" value="#LOCAL.account#">
                </cfhttp>

                <cfset return_status = "Pending">
                <cfset currentStatus = "Pending">
                
                <!--- Parse status response and update EVV table --->
                <cfif httpStatusResponse.StatusCode EQ "200" OR httpStatusResponse.StatusCode CONTAINS "200">
                    <cfset statusResponseData = DeserializeJSON(httpStatusResponse.FileContent)>
                    <cfset currentStatus = "SUCCESS">
                    
                    <!--- Extract reason from status response if available --->
                    <cfif structKeyExists(statusResponseData, "data") AND isStruct(statusResponseData.data) AND structKeyExists(statusResponseData.data, "reason")>
                        <cfset currentStatus = trim(statusResponseData.data.reason) />
                        <!--- Remove trailing period if present --->
                        <cfif right(currentStatus, 1) EQ ".">
                            <cfset currentStatus = left(currentStatus, len(currentStatus) - 1) />
                        </cfif>
                    </cfif>
                    
                    <!--- Log the extracted status for debugging --->
                    <cflog file="AHCCCS_Employee_Status" text="check_employee_status: Emp_ID=#Employee_ID#, UUID=#LOCAL.uuid#, Extracted Status='#currentStatus#'">
                    
                    <!--- Update EVV table with current status --->
                    <cfquery name="UPDATE_EVV_STATUS" datasource="#Application.DataSrc#" result="updateResult">
                        UPDATE #Request.prefix_db_lookup#.EVV 
                        SET San_status = <cfqueryparam value="#currentStatus#" cfsqltype="cf_sql_varchar">,
                            Date_Update = NOW()
                        WHERE UUID = <cfqueryparam value="#LOCAL.uuid#" cfsqltype="cf_sql_varchar">
                        AND API_Type = 'employee'
                        AND Agency_ID = '#session.agencyid#'
                        AND Emp_ID = '#Employee_ID#'
                        AND status = 0
                    </cfquery>
                    
                    <!--- Log update result --->
                    <cflog file="AHCCCS_Employee_Status" text="check_employee_status: Updated #updateResult.recordcount# EVV record(s) for Emp_ID=#Employee_ID# with status '#currentStatus#'">
                    
                    <cfset return_status = currentStatus>
                </cfif>
                
                <!--- Send email notification --->
                <cfmail to="#sendto_email#" from="info@myhomecarebiz.com" subject="#envLabel# AHCCCS Employee Status Check - #GetEmpInfo.Emp_First#, #GetEmpInfo.Emp_Last# (#Employee_ID#)" type="html">
                    <h3>AHCCCS Employee Status Check Results</h3>
                    <p><strong>Employee Name:</strong> #GetEmpInfo.Emp_First#, #GetEmpInfo.Emp_Last#</p>
                    <p><strong>Employee ID:</strong> #Employee_ID#</p>
                    <p><strong>UUID:</strong> #LOCAL.uuid#</p>
                    <p><strong>Status Check Time:</strong> #now()#</p>
                    <p><strong>Current EVV Status:</strong> <span style="color: ##28a745; font-weight: bold;">#currentStatus#</span></p>
                    <hr>
                    <p><strong>Full API Response:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#httpStatusResponse.Filecontent#</pre>
                </cfmail>
                
            <cfelse>
                <cfset return_status = "No UUID found for employee #Employee_ID#">
                
                <!--- Send error email notification --->
                <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Employee Status Check Error - #GetEmpInfo.Emp_First#, #GetEmpInfo.Emp_Last# (#Employee_ID#)" type="html">
                    <h3>AHCCCS Employee Status Check Error</h3>
                    <p><strong>Employee Name:</strong> #GetEmpInfo.Emp_First#, #GetEmpInfo.Emp_Last#</p>
                    <p><strong>Employee ID:</strong> #Employee_ID#</p>
                    <p><strong>Error:</strong> No UUID found for this employee in EVV table</p>
                    <p><strong>Status Check Time:</strong> #now()#</p>
                </cfmail>
                
                <!--- Return error response as JSON --->
                <cfreturn {
                    "success" = false,
                    "message" = "No UUID found for employee",
                    "status" = "error",
                    "employeeId" = Employee_ID,
                    "data" = {
                        "reason" = return_status,
                        "status" = "error"
                    }
                }>
            </cfif>
            
        <cfcatch type="any">
            <cfset return_status = "Error: #cfcatch.message#">
            
            <!--- Send error email notification --->
            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Employee Status Check Error - #GetEmpInfo.Emp_First#, #GetEmpInfo.Emp_Last# (#Employee_ID#)" type="html">
                <h3>AHCCCS Employee Status Check Error</h3>
                <p><strong>Employee Name:</strong> #GetEmpInfo.Emp_First#, #GetEmpInfo.Emp_Last#</p>
                <p><strong>Employee ID:</strong> #Employee_ID#</p>
                <p><strong>Error:</strong> #cfcatch.message#</p>
                <p><strong>Status Check Time:</strong> #now()#</p>
            </cfmail>
            
            <!--- Return error response as JSON --->
            <cfreturn {
                "success" = false,
                "message" = cfcatch.message,
                "status" = "error",
                "employeeId" = Employee_ID,
                "data" = {
                    "reason" = return_status,
                    "status" = "error"
                }
            }>
        </cfcatch>
        </cftry>
        
        <!--- Return success response as JSON --->
        <cfreturn {
            "success" = true,
            "message" = "Status retrieved successfully",
            "status" = return_status,
            "employeeId" = Employee_ID,
            "data" = {
                "reason" = return_status,
                "status" = return_status
            }
        }>
    </cffunction>

    <cffunction name="check_visit_status" access="remote" returnFormat= "json">
        <cfargument name="Agency_ID" required="no" hint="Agency_ID" default="#session.agencyId#">
        <cfargument name="Schedule_ID" required="yes" default="0" hint="Schedule_ID">

        <cfset Schedule_ID = decrypt(#arguments.Schedule_ID#,#application.enckey#,"AES","Hex") />
        
        <!--- Initialize LOCAL variables --->
        <cfif application.DEV EQ false>
            <!--- PROD subscription keys --->
            <cfset LOCAL.subscription_key_primary = "3f11f04e0fd74ad39c77c8cacbfef240">
            <cfset LOCAL.subscription_key_secondary = "3710f5d7890241d3beb7181e2b506f8b">
        <cfelse>
            <!--- DEV subscription keys --->
        <cfset LOCAL.subscription_key_primary = "b3446ef5e2ce497dbc9da4007b574c8b">
        <cfset LOCAL.subscription_key_secondary = "1c88925161e94f4cae914d91ad0c077c">
        </cfif>
        <cfset LOCAL.account = "a2f47e6e-5f6b-0e9b-c2c6-e003c1b48ac9">
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- Use server name in email subject --->
        <cfset envLabel = #Application.ServerName# />
        
        <!--- Get agency settings from database --->
        <cfquery name="getagency" datasource="#Application.DataSrc#">
            SELECT * FROM  #Request.prefix_db_lookup#.Agency
            WHERE Agency_ID = '#session.agencyId#'
            <cfif application.DEV EQ false>  
                AND EVV_prod_username IS NOT NULL
                AND EVV_prod_password IS NOT NULL
            <cfelse>
                AND EVV_username IS NOT NULL
                AND EVV_password IS NOT NULL
            </cfif>
        </cfquery>
        
        <cfif getagency.recordcount gt 0>
            <cfif application.DEV EQ false>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
            <cfelse>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
            </cfif>
        </cfif>

        <cftry>
            <!--- Get visit information --->
            <cfquery name="GetVisitInfo" datasource="#Application.DataSrc#">
                SELECT pp.Pt_First, pp.Pt_Last, ps.Schedule_ID
                FROM #Request.prefix_db_agency#.pSchedules ps
                INNER JOIN #Request.prefix_db_agency#.pPatients pp ON ps.Patient_ID = pp.Patient_ID
                WHERE ps.Schedule_ID = '#Schedule_ID#'
                AND ps.Status = 0
            </cfquery>
            
            <!--- Get UUID from EVV table for the visit --->
            <cfquery name="GetEVVUUID" datasource="#Application.DataSrc#">
                SELECT UUID FROM #Request.prefix_db_lookup#.EVV
                WHERE API_Type = 'visits'
                AND Agency_ID = '#session.agencyid#'
                AND status = 0
                AND Schedule_ID = '#Schedule_ID#'
                ORDER BY EVV_ID DESC LIMIT 1
            </cfquery>

            <cfif GetEVVUUID.recordcount GT 0>
                <cfset LOCAL.uuid = GetEVVUUID.UUID>
                
                <!--- Determine the correct API endpoint based on environment --->
                <cfif application.DEV EQ false>
                    <cfset LOCAL.statusEndpoint = "https://si-api.azahcccs.gov/evv/aggregation/v1/visits/status?uuid=#LOCAL.uuid#&key=" & LOCAL.subscription_key_primary>
                <cfelse>
                    <cfset LOCAL.statusEndpoint = "https://si-api.azahcccs.gov/test/evv/aggregation/v1/visits/status?uuid=#LOCAL.uuid#&key=" & LOCAL.subscription_key_primary>
                </cfif>
                
                <!--- Make API call to AHCCCS status endpoint --->
                <cfhttp 
                    url="#LOCAL.statusEndpoint#"
                    method="GET" 
                    timeout="100"
                    result="httpStatusResponse">
                    <cfhttpparam name="Content-Type" type="HEADER" value="application/json">
                    <cfhttpparam name="Accept" type="HEADER" value="application/json">
                    <cfhttpparam name="account" type="HEADER" value="#LOCAL.account#">
                </cfhttp>

                <cfset return_status = "Pending">
                <cfset currentStatus = "Pending">
                
                <!--- Parse status response and update EVV table --->
                <cfif httpStatusResponse.StatusCode EQ "200" OR httpStatusResponse.StatusCode CONTAINS "200">
                    <cfset statusResponseData = DeserializeJSON(httpStatusResponse.FileContent)>
                    <cfset currentStatus = "SUCCESS">
                    
                    <!--- Extract reason from status response if available --->
                    <cfif structKeyExists(statusResponseData, "data") AND isStruct(statusResponseData.data) AND structKeyExists(statusResponseData.data, "reason")>
                        <cfset currentStatus = trim(statusResponseData.data.reason) />
                        <!--- Remove trailing period if present --->
                        <cfif right(currentStatus, 1) EQ ".">
                            <cfset currentStatus = left(currentStatus, len(currentStatus) - 1) />
                        </cfif>
                    </cfif>
                    
                    <!--- Log the extracted status for debugging --->
                    <cflog file="AHCCCS_Visit_Status" text="check_visit_status: Schedule_ID=#Schedule_ID#, UUID=#LOCAL.uuid#, Extracted Status='#currentStatus#', HTTP StatusCode=#httpStatusResponse.StatusCode#">
                    
                    <!--- Update EVV table with current status --->
                    <cfquery name="UPDATE_EVV_STATUS" datasource="#Application.DataSrc#" result="updateResult">
                        UPDATE #Request.prefix_db_lookup#.EVV 
                        SET San_status = <cfqueryparam value="#currentStatus#" cfsqltype="cf_sql_varchar">,
                            Date_Update = NOW()
                        WHERE UUID = <cfqueryparam value="#LOCAL.uuid#" cfsqltype="cf_sql_varchar">
                        AND API_Type = 'visits'
                        AND Agency_ID = '#session.agencyid#'
                        AND Schedule_ID = '#Schedule_ID#'
                        AND status = 0
                    </cfquery>
                    
                    <!--- Log update result --->
                    <cflog file="AHCCCS_Visit_Status" text="check_visit_status: Updated #updateResult.recordcount# EVV record(s) for Schedule_ID=#Schedule_ID# with status '#currentStatus#'">
                    
                    <cfset return_status = currentStatus>
                <cfelse>
                    <cfset return_status = "Unable to retrieve status (HTTP #httpStatusResponse.StatusCode#)">
                </cfif>
                
                <!--- Send email notification --->
                <cfmail to="#sendto_email#" from="info@myhomecarebiz.com" subject="#envLabel# AHCCCS Visit Status Check - #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last# (#Schedule_ID#)" type="html">
                    <h3>AHCCCS Visit Status Check Results</h3>
                    <p><strong>Patient Name:</strong> #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last#</p>
                    <p><strong>Schedule ID:</strong> #Schedule_ID#</p>
                    <p><strong>UUID:</strong> #LOCAL.uuid#</p>
                    <p><strong>Status Check Time:</strong> #now()#</p>
                    <p><strong>Current EVV Status:</strong> <span style="color: ##28a745; font-weight: bold;">#currentStatus#</span></p>
                    <hr>
                    <p><strong>Full API Response:</strong></p>
                    <pre style="background-color: ##f4f4f4; padding: 10px; border: 1px solid ##ddd; overflow-x: auto;">#httpStatusResponse.Filecontent#</pre>
                </cfmail>
                
            <cfelse>
                <cfset return_status = "No UUID found for visit #Schedule_ID#">
                
                <!--- Send error email notification --->
                <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Visit Status Check Error - #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last# (#Schedule_ID#)" type="html">
                    <h3>AHCCCS Visit Status Check Error</h3>
                    <p><strong>Patient Name:</strong> #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last#</p>
                    <p><strong>Schedule ID:</strong> #Schedule_ID#</p>
                    <p><strong>Error:</strong> No UUID found for this visit in EVV table</p>
                    <p><strong>Status Check Time:</strong> #now()#</p>
                </cfmail>
                
                <!--- Return error response as JSON --->
                <cfreturn {
                    "success" = false,
                    "message" = "No UUID found for visit",
                    "status" = "error",
                    "scheduleId" = Schedule_ID,
                    "data" = {
                        "reason" = return_status,
                        "status" = "error"
                    }
                }>
            </cfif>
            
        <cfcatch type="any">
            <cfset return_status = "Error: #cfcatch.message#">
            
            <!--- Send error email notification --->
            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="#envLabel# AHCCCS Visit Status Check Error - #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last# (#Schedule_ID#)" type="html">
                <h3>AHCCCS Visit Status Check Error</h3>
                <p><strong>Patient Name:</strong> #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last#</p>
                <p><strong>Schedule ID:</strong> #Schedule_ID#</p>
                <p><strong>Error:</strong> #cfcatch.message#</p>
                <p><strong>Status Check Time:</strong> #now()#</p>
            </cfmail>
            
            <!--- Return error response as JSON --->
            <cfreturn {
                "success" = false,
                "message" = cfcatch.message,
                "status" = "error",
                "scheduleId" = Schedule_ID,
                "data" = {
                    "reason" = return_status,
                    "status" = "error"
                }
            }>
        </cfcatch>
        </cftry>
        
        <!--- Return success response as JSON --->
        <cfreturn {
            "success" = true,
            "message" = "Status retrieved successfully",
            "status" = return_status,
            "scheduleId" = Schedule_ID,
            "data" = {
                "reason" = return_status,
                "status" = return_status
            }
        }>
    </cffunction>

</cfcomponent>

