<cfcomponent displayname="Medicare Arizona sandata related Functions" hint="I send Medicare Arizona sandata Information" output="false">
    <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />

   <cffunction name="init" displayname="Initialize Component" access="public" returntype="sandata" hint="I initialize and return the Medicare Arizona sandata object.">
        <cfreturn this>
    </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 --->
        <cfset LOCAL.username = "2n9xzzfv">
        <cfset LOCAL.password = "@$48jnh6{0}G">
        <cfset LOCAL.account = '215035'>
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- 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.username = getagency.EVV_prod_username>
                <cfset LOCAL.password = getagency.EVV_prod_password>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
                <cfset LOCAL.account = getagency.EVV_prod_account>
            <cfelse>
                <cfset LOCAL.username = getagency.EVV_username>
                <cfset LOCAL.password = getagency.EVV_password>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
                <cfset LOCAL.account = getagency.EVV_account>
            </cfif>
        </cfif>
        <cfset LOCAL.authString = toBase64(LOCAL.username & ":" & LOCAL.password)>
        
        <cfif application.DEV EQ false>
            <cfset LOCAL.AuthorizationEndpoint = "https://api.sandata.com/interfaces/intake/clients/rest/api/v1.1">
        <cfelse>
            <cfset LOCAL.AuthorizationEndpoint = "https://uat-api.sandata.com/interfaces/intake/clients/rest/api/v1.1">
        </cfif>
        <cfset arguments.Patient_ID  = decrypt(#arguments.Patient_ID#,#application.enckey#,"AES","Hex") />
        <cftry>
            <cfquery  name="GetPat"  datasource="#Application.DataSrc#">
                SELECT *   FROM #Request.prefix_db_agency#.pPatients 
                WHERE  pPatients.Status IN (0,1)
                AND Patient_ID  =  #Patient_ID#
                GROUP BY Patient_ID
            </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 Patient_ID  =  #Patient_ID#
                AND pPtPayer.status = 0
                AND pPayer.status = 0
                ORDER BY pPtPayer.Payer_Responsibility ASC
            </cfquery>
            <cfquery  name="GetContacts"  datasource="#Application.DataSrc#">
                SELECT  *
                FROM #Request.prefix_db_agency#.pPtContacts
                WHERE Patient_ID =  #Patient_ID#
                AND status < 2
                Order by Emergency DESC, status ASC
            </cfquery>
            <cfquery  name="GET_EVV"  datasource="#Application.DataSrc#">
                SELECT (IFNULL(Max(Seq_ID),0)+1) as seq_id FROM #Request.prefix_db_lookup#.EVV 
                WHERE API_type = 'clients'               
            </cfquery>
            <cfset Seq_ID = #GET_EVV.seq_id# />

            <cfset ClientIdentifier = "A" & repeatString("0", 8 - len(#Patient_ID#)) & #Patient_ID#>
            <cfset ClientMedicaidID = #Getpayers.Sub_HIC#>
            <cfset Pt_Phone    = rereplace(GetPat.Pt_Phone, "[^0-9]", "", "all")>
            <cfset ClientPhone = right(Pt_Phone, 10)>
            <cfset Telephone1 = rereplace(GetContacts.Telephone1, "[^0-9]", "", "all")>
            <cfset ClientContactPhone = right(Telephone1, 10)>
            <cfset ClientZip = rereplace( GetPat.Pt_Zip, "[^0-9]", "", "all")>
            <cfset Contact_Type = 'Other'/>

            <cfloop list = "Child,Friend,Other,Parent,Sibling,Spouse" index="con_type">
                <cfif GetContacts.Pt_Realtionship contains con_type>
                        <cfset Contact_Type = con_type />
                </cfif>
            </cfloop>
        

            <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 VisitTimeZone = "US/Mountain"> 
            <cfif application.TimeZone  EQ 'CST'>
                <cfset VisitTimeZone = "US/Central">
            <cfelseif application.TimeZone  EQ 'MST'>
                <cfset VisitTimeZone = "US/Mountain">
            <cfelseif application.TimeZone  EQ 'PST'>
                <cfset VisitTimeZone = "US/Pacific">
            <cfelseif application.TimeZone  EQ 'AKST'>
                <cfset VisitTimeZone = "US/Alaska">
            <cfelseif application.TimeZone  EQ 'HST'>
                <cfset VisitTimeZone = "US/Hawaii">
            </cfif>
            <cfset PayerID = 'AZCCCS'>
            <cfset PayerProgram = 'AHCCCS'>
            <cfset ProcedureCode = 'G0151'>
            <cfset Start_Date = '2025-01-01' >
            <cfif Getpayers.Start_Date NEQ ''>
                <cfset Start_Date = #Dateformat(Getpayers.Start_Date,"yyyy-mm-dd")# />
            </cfif>
            <cfset EffectiveStartDate = "2020-01-01">
            <cfset EffectiveEndDate = "2026-01-01">
            <cfif Getpayers.Date_Start NEQ ''>
                <cfset EffectiveStartDate = #Dateformat(Getpayers.Date_Start,"yyyy-mm-dd")# />
            </cfif>
            <cfif Getpayers.Date_End NEQ ''>
                <cfset EffectiveEndDate = #Dateformat(Getpayers.Date_End,"yyyy-mm-dd")# />
            </cfif>
             <cfset client_email = "noemail@mail.com" />
            <cfif GetPat.Email NEQ ''>
                <cfset client_email = GetPat.Email />
            </cfif>

             

              <cfset Request.stFields =
                [
                    {
                        "ProviderIdentification":
                        {  
                            "ProviderQualifier": "MedicaidID",
                            "ProviderID": "#LOCAL.ProviderID#"
                        },
                        "ClientID": "#Patient_ID#",
                        "ClientFirstName": "#GetPat.Pt_First#",
                        "ClientMiddleInitial": "#GetPat.Pt_Middle#",
                        "ClientLastName": "#GetPat.Pt_Last#",
                        "ClientQualifier": "ClientCustomID",
                        "ClientMedicaidID": "#ClientMedicaidID#",
                        "ClientIdentifier": "#ClientMedicaidID#",
                        <!--- "MissingMedicaidID": "",--->
                        "SequenceID": "#Seq_ID#",
                        "ClientCustomID": "#ClientMedicaidID#",
                        "ClientOtherID": "#ClientMedicaidID#",
                        "ClientTimezone": "#VisitTimeZone#",
                        "ClientSSN": "999999999",
                        "Coordinator": "123",
                        "ProviderAssentContPlan": "No",
                        "ClientPayerInformation": 
                        [
                            {
                            "PayerID": "#PayerID#",
                            "PayerProgram": "#PayerProgram#",
                            "ProcedureCode": "#ProcedureCode#",
                            "ClientPayerID": "#Getpayers.Sub_HIC#",
                            "ClientEligibilityDateBegin": "#Start_Date#",
                            "ClientEligibilityDateEnd": "#Todaydate#",
                            "ClientStatus": "02",
                            "EffectiveStartDate": "#EffectiveStartDate#",
                            "EffectiveEndDate": "#EffectiveEndDate#"
                            }
                        ],
                        "ClientAddress": 
                        [
                            {
                            "ClientAddressType": "Home",
                            "ClientAddressIsPrimary": true,
                            "ClientAddressLine1": "#GetPat.Pt_Street#",
                            "ClientAddressLine2": "",
                            "ClientCounty": "USA",
                            "ClientCity": "#GetPat.Pt_City#",
                            "ClientState": "#GetPat.Pt_State#",
                            "ClientZip": "#ClientZip#",
                            "ClientAddressLongitude":"#GetPat.Pt_Longitude#",
                            "ClientAddressLatitude": "#GetPat.Pt_Latitude#"
                            }
                        ],
                        "ClientPhone": 
                        [
                            {
                            "ClientPhoneType": "Home",
                            "ClientPhone": "#ClientPhone#"
                            }
                        ],
                        "ClientDesignee": 
                        [
                            {
                            "ClientDesigneeFirstName": "#GetPat.Pt_First#",
                            "ClientDesigneeLastName": "#GetPat.Pt_Last#",
                            "ClientDesigneeEmail": "#client_email#" ,
                            "ClientDesigneeStatus": "02" ,
                            "ClientDesigneeStartDate":  "#Start_Date#",
                            "ClientDesigneeEndDate":  "#Todaydate#",
                            "ClientDesigneeRelationship": ""
                            }
                        ],
                        "ClientResponsibleParty": 
                        [
                            {
                            "ClientContactType": "#Contact_Type#",
                            "ClientContactFirstName": "#GetContacts.First_Name#",
                            "ClientContactLastName": "#GetContacts.Last_Name#",
                            "ClientContactPhoneType": "Mobile",
                            "ClientContactPhone": "#ClientContactPhone#",
                            "ClientContactEmailAddress": "#GetContacts.Contact_Email#",
                            "ClientContactAddressLine1": "",
                            "ClientContactAddressLine2": "",
                            "ClientContactCity": "",
                            "ClientContactState": "",
                            "ClientContactZip": ""
                            }
                        ]
                    }
                ]
            >
            <!--- <cfdump var="#serializeJSON(Request.stFields)#"> --->
            <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="Authorization" type="HEADER" value="Basic #LOCAL.authString#">
                <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">
       <!--- <cfif CGI.REMOTE_ADDR EQ '3.217.216.133'>
        <cfdump var = "#Request.stFields#">  
            <br><br>
              <cfdump var = "#httpEVVResponse#">  
            <cfabort>
        </cfif> --->
        <cfif httpEVVResponse.responseHeader.Status_Code eq 200>  
            <cfset structureData  = DeserializeJSON(httpEVVResponse.Filecontent)>
            <!--- <cfdump var="#structureData.status#"><cfabort> --->
            <cfset return_status = structureData.status >

            <cfif return_status EQ 'SUCCESS'>
                <cfset title = "Powerpath Client EVV API  Successfuly send to SAN">
                <cfset fromaddress = "info@myhomecarebiz.com">
            <cfelse>
                <cfset responseStruct = structureData>
                <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 return_status = #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>
                       <!---  <cfset nestedKeys = ["ClientAddress", "ClientPhone", "ClientResponsibleParty", "ClientPayerInformation", "ClientDesignee"]>
                        <cfloop array="#nestedKeys#" index="key">
                            <cfif structKeyExists(item, key) AND isArray(item[key])>
                                <cfloop array="#item[key]#" index="subItem">
                                    <cfif structKeyExists(subItem, "ErrorMessage") AND NOT isNull(subItem.ErrorMessage)>
                                        Error in #key#: #subItem.ErrorMessage#<br> <br><br>
                                    </cfif>
                                </cfloop>
                            </cfif>
                        </cfloop>                           
                        <cfif structKeyExists(item, "ProviderIdentification") AND isStruct(item.ProviderIdentification)>
                            <cfif structKeyExists(item.ProviderIdentification, "ErrorMessage") AND NOT isNull(item.ProviderIdentification.ErrorMessage)>
                                Error in ProviderIdentification: #item.ProviderIdentification.ErrorMessage#<br>
                            </cfif>
                        </cfif>--->
                    </cfloop>
                </cfif>
                <cfset title = "Powerpath Client EVV API Failed due to SAN data return">
                <cfset fromaddress = "error@myhomecarebiz.com">
            </cfif>           
            <cfmail to="#sendto_email#" from="#fromaddress#" subject="#title#" type="html">
                    REQUEST: <cfdump var="#serializeJSON(Request.stFields)#"><br>
                    RESPONSE: <cfdump var="#httpEVVResponse#">
            </cfmail> 
            <cfset UUID = structureData.id />
            <cfquery  name="INSERT_EVV"  datasource="#Application.DataSrc#">
                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>
        <cfelse>

            <cfset structureData  = DeserializeJSON(httpEVVResponse.Filecontent)>
            <cfset responseStruct = structureData>
            <cfif structKeyExists(responseStruct, "data") AND isArray(responseStruct.data)>
                <cfloop array="#responseStruct.data#" index="item">
                    <!--- Check top-level ErrorMessage --->
                    <cfif structKeyExists(item, "ErrorMessage") AND NOT isNull(item.ErrorMessage)>
                        <cfset return_status = #item.ErrorMessage#  />
                    </cfif>
                   <!---  <cfset nestedKeys = ["ClientAddress", "ClientPhone", "ClientResponsibleParty", "ClientPayerInformation", "ClientDesignee"]>
                    <cfloop array="#nestedKeys#" index="key">
                        <cfif structKeyExists(item, key) AND isArray(item[key])>
                            <cfloop array="#item[key]#" index="subItem">
                                <cfif structKeyExists(subItem, "ErrorMessage") AND NOT isNull(subItem.ErrorMessage)>
                                    Error in #key#: #subItem.ErrorMessage#<br> <br><br>
                                </cfif>
                            </cfloop>
                        </cfif>
                    </cfloop>                           
                    <cfif structKeyExists(item, "ProviderIdentification") AND isStruct(item.ProviderIdentification)>
                        <cfif structKeyExists(item.ProviderIdentification, "ErrorMessage") AND NOT isNull(item.ProviderIdentification.ErrorMessage)>
                            Error in ProviderIdentification: #item.ProviderIdentification.ErrorMessage#<br>
                        </cfif>
                    </cfif>--->
                </cfloop>
            </cfif>



            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="Powerpath Client EVV API  Error" type="html">
                    REQUEST: <cfdump var="#serializeJSON(Request.stFields)#"><br>
                    RESPONSE: <cfdump var="#httpEVVResponse#">
            </cfmail>            
        </cfif>
        <cfreturn return_status>

       <cfcatch>
                 <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="Powerpath Client EVV API  Error" type="html">
                    <cfdump var="#cfcatch#">
                </cfmail> 
        </cfcatch>
        </cftry>

    </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 --->
        <cfset LOCAL.username = "2n9xzzfv">
        <cfset LOCAL.password = "@$48jnh6{0}G">
        <cfset LOCAL.account = '215035'>
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- 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.username = getagency.EVV_prod_username>
                <cfset LOCAL.password = getagency.EVV_prod_password>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
                <cfset LOCAL.account = getagency.EVV_prod_account>
            <cfelse>
                <cfset LOCAL.username = getagency.EVV_username>
                <cfset LOCAL.password = getagency.EVV_password>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
                <cfset LOCAL.account = getagency.EVV_account>
            </cfif>
        </cfif>
        <cfset LOCAL.authString = toBase64(LOCAL.username & ":" & LOCAL.password)>
        <cftry>
             <cfif application.DEV EQ false>
                <cfset LOCAL.AuthorizationEndpoint = "https://api.sandata.com/interfaces/intake/employees/rest/api/v1.1">
            <cfelse>
                <cfset LOCAL.AuthorizationEndpoint = "https://uat-api.sandata.com/interfaces/intake/employees/rest/api/v1.1">
            </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) />

             <cfquery  name="GET_EVV"  datasource="#Application.DataSrc#">
                SELECT (IFNULL(Max(Seq_ID),0)+1) as seq_id FROM #Request.prefix_db_lookup#.EVV 
                WHERE API_type = 'employee'               
            </cfquery>
            <cfset Seq_ID = #GET_EVV.seq_id# />

            <cfset Request.stFields =
                    [{
                    "ProviderIdentification": {
                    "ProviderQualifier": "MedicaidID",
                    "ProviderID": "#LOCAL.ProviderID#"
                    },
                    "EmployeeQualifier": "EmployeeSSN",
                    "EmployeeIdentifier": "#GetEmp.Emp_SSN#",
                    "EmployeeOtherID": "#GetEmp.Emp_ID#",
                    "SequenceID": #Seq_ID#,
                    "EmployeeSSN": "#GetEmp.Emp_SSN#",
                    "EmployeeLastName": "#GetEmp.Emp_Last#",
                    "EmployeeFirstName": "#GetEmp.Emp_First#",
                    "EmployeeEmail": "#GetEmp.Emp_Email#",
                    "EmployeeManagerEmail":  "#EmployeeManagerEmail#",
                    "EmployeeAPI": "#Seq_ID#",
                    "EmployeePosition": "#GetEmp.Skill_1#"
                    }]

            > 
            <!--- <cfdump var="#Request.stFields#">
            <cfdump var="#serializeJSON(Request.stFields)#">
             <cfif CGI.REMOTE_ADDR EQ '103.143.7.161'>
                     <cfdump var="#serializeJSON(Request.stFields)#"><br><br><cfabort>
            </cfif>--->
            <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="Authorization" type="HEADER" value="Basic #LOCAL.authString#">
                <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">
            <!--- <cfif CGI.REMOTE_ADDR EQ '3.217.216.133'>
                <cfdump var="#serializeJSON(Request.stFields)#"><br><br>
                <cfdump var = "#httpEVVResponse#">
                <cfdump var = "#LOCAL#"> <cfabort>
            </cfif>--->
            <cfset structureData  = DeserializeJSON(httpEVVResponse.Filecontent)>
            <cfif httpEVVResponse.responseHeader.Status_Code eq 200>              
            <!---  <cfdump var="#structureData.status#"><cfabort> ---> 
            <cfset return_status = structureData.status >
            <cfif return_status EQ 'SUCCESS'>
                <cfset title = "Powerpath Employee EVV API  Successfuly send to SAN">
                <cfset fromaddress = "info@myhomecarebiz.com">
            <cfelse>
                <cfset title = "Powerpath Employee EVV API Failed due to SAN data return">
                <cfset fromaddress = "error@myhomecarebiz.com">
                <cfset responseStruct = structureData>
                <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>
            </cfif>    
            <cfset UUID = structureData.id />
            <cfquery  name="INSERT_EVV"  datasource="#Application.DataSrc#">
                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>       
            <cfmail to="#sendto_email#" from="#fromaddress#" subject="#title#" type="html">
                    REQUEST: <cfdump var="#serializeJSON(Request.stFields)#"><br>
                    RESPONSE: <cfdump var="#httpEVVResponse#">
            </cfmail> 
            <cfelse>
                <cfset responseStruct = structureData>
                <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="Powerpath Employee EVV API  Error" type="html">
                        REQUEST: <cfdump var="#serializeJSON(Request.stFields)#"><br>
                        RESPONSE: <cfdump var="#httpEVVResponse#">
                </cfmail>            
            </cfif>
            <cfreturn return_status>
            <cfcatch>
                    <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="Powerpath Employee EVV API  Error" type="html">
                        <cfdump var="#cfcatch#">
                    </cfmail> 
            </cfcatch>
        </cftry>
    </cffunction>

    <cffunction name="check_employee_status" 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 --->
        <cfset LOCAL.username = "2n9xzzfv">
        <cfset LOCAL.password = "@$48jnh6{0}G">
        <cfset LOCAL.account = '215035'>
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- 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.username = getagency.EVV_prod_username>
                <cfset LOCAL.password = getagency.EVV_prod_password>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
                <cfset LOCAL.account = getagency.EVV_prod_account>
            <cfelse>
                <cfset LOCAL.username = getagency.EVV_username>
                <cfset LOCAL.password = getagency.EVV_password>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
                <cfset LOCAL.account = getagency.EVV_account>
            </cfif>
        </cfif>
        <cfset LOCAL.authString = toBase64(LOCAL.username & ":" & LOCAL.password)>

        <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#'
            </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://api.sandata.com/interfaces/intake/clients/rest/api/v1.1/status?uuid=#LOCAL.uuid#">
                <cfelse>
                    <cfset LOCAL.statusEndpoint = "https://uat-api.sandata.com/interfaces/intake/clients/rest/api/v1.1/status?uuid=#LOCAL.uuid#">
                </cfif>
                
                <!--- Make API call to Sandata status endpoint --->
                <cfhttp 
                    url="#LOCAL.statusEndpoint#"
                    method="GET" 
                    timeout="100"
                    result="httpStatusResponse">
                    <cfhttpparam name="Content-Type" type="HEADER" value="application/json">
                    <cfhttpparam name="Authorization" type="HEADER" value="Basic #LOCAL.authString#">
                    <cfhttpparam name="account" type="HEADER" value="#LOCAL.account#">
                </cfhttp>

                <cfset return_status = "SUCCESS">
                
                <!--- Send email notification --->
                <cfmail to="#sendto_email#" from="info@myhomecarebiz.com" subject="Arizona Employee Status Check - #GetEmpInfo.Emp_First#, #GetEmpInfo.Emp_Last# (#Employee_ID#)" type="html">
                    <h3>Arizona 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>API Response:</strong></p>
                    <pre>#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="Arizona Employee Status Check Error - #GetEmpInfo.Emp_First#, #GetEmpInfo.Emp_Last# (#Employee_ID#)" type="html">
                    <h3>Arizona 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 in EVV table for this employee</p>
                    <p><strong>Check Time:</strong> #now()#</p>
                </cfmail>
            </cfif>

        <cfcatch>
            <cfset return_status = "Error: #cfcatch.message#">
            
            <!--- Send error email notification --->
            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="Arizona Employee Status Check Error - #GetEmpInfo.Emp_First#, #GetEmpInfo.Emp_Last# (#Employee_ID#)" type="html">
                <h3>Arizona 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>Check Time:</strong> #now()#</p>
                <pre>#cfcatch.detail#</pre>
            </cfmail>
        </cfcatch>
        </cftry>

        <cfreturn return_status>
    </cffunction>

    <cffunction name="check_visit_status" 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">

        <cfset Schedule_ID  = decrypt(#arguments.Schedule_ID#,#application.enckey#,"AES","Hex") />
        
        <!--- Initialize LOCAL variables --->
        <cfset LOCAL.username = "2n9xzzfv">
        <cfset LOCAL.password = "@$48jnh6{0}G">
        <cfset LOCAL.account = '215035'>
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- 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.username = getagency.EVV_prod_username>
                <cfset LOCAL.password = getagency.EVV_prod_password>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
                <cfset LOCAL.account = getagency.EVV_prod_account>
            <cfelse>
                <cfset LOCAL.username = getagency.EVV_username>
                <cfset LOCAL.password = getagency.EVV_password>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
                <cfset LOCAL.account = getagency.EVV_account>
            </cfif>
        </cfif>
        <cfset LOCAL.authString = toBase64(LOCAL.username & ":" & LOCAL.password)>

        <cftry>
            <!--- Get visit information --->
            <cfquery name="GetVisitInfo" datasource="#Application.DataSrc#">
                SELECT pSchedules.*, pPatients.Pt_First, pPatients.Pt_Last, pEmployee.Emp_First, pEmployee.Emp_Last
                FROM #Request.prefix_db_agency#.pSchedules
                JOIN #Request.prefix_db_agency#.pPatients ON pSchedules.Patient_ID = pPatients.Patient_ID
                LEFT JOIN #Request.prefix_db_lookup#.pEmployee ON pSchedules.Emp_ID = pEmployee.Emp_ID
                WHERE pSchedules.Schedule_ID = '#Schedule_ID#'
                AND pSchedules.status = 0
                AND pPatients.status IN (0,1,4)
            </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://api.sandata.com/interfaces/intake/clients/rest/api/v1.1/status?uuid=#LOCAL.uuid#">
                <cfelse>
                    <cfset LOCAL.statusEndpoint = "https://uat-api.sandata.com/interfaces/intake/clients/rest/api/v1.1/status?uuid=#LOCAL.uuid#">
                </cfif>
                
                <!--- Make API call to Sandata status endpoint --->
                <cfhttp 
                    url="#LOCAL.statusEndpoint#"
                    method="GET" 
                    timeout="100"
                    result="httpStatusResponse">
                    <cfhttpparam name="Content-Type" type="HEADER" value="application/json">
                    <cfhttpparam name="Authorization" type="HEADER" value="Basic #LOCAL.authString#">
                    <cfhttpparam name="account" type="HEADER" value="#LOCAL.account#">
                </cfhttp>

                <cfset return_status = "SUCCESS">
                
                <!--- Send email notification --->
                <cfmail to="#sendto_email#" from="info@myhomecarebiz.com" subject="Arizona Visit Status Check - #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last# (#Schedule_ID#)" type="html">
                    <h3>Arizona Visit Status Check Results</h3>
                    <p><strong>Patient Name:</strong> #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last#</p>
                    <p><strong>Employee Name:</strong> #GetVisitInfo.Emp_First#, #GetVisitInfo.Emp_Last#</p>
                    <p><strong>Schedule ID:</strong> #Schedule_ID#</p>
                    <p><strong>Visit Date:</strong> #DateFormat(GetVisitInfo.Visit_Date, "mm/dd/yyyy")#</p>
                    <p><strong>UUID:</strong> #LOCAL.uuid#</p>
                    <p><strong>Status Check Time:</strong> #now()#</p>
                    <p><strong>API Response:</strong></p>
                    <pre>#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="Arizona Visit Status Check Error - #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last# (#Schedule_ID#)" type="html">
                    <h3>Arizona Visit Status Check Error</h3>
                    <p><strong>Patient Name:</strong> #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last#</p>
                    <p><strong>Employee Name:</strong> #GetVisitInfo.Emp_First#, #GetVisitInfo.Emp_Last#</p>
                    <p><strong>Schedule ID:</strong> #Schedule_ID#</p>
                    <p><strong>Error:</strong> No UUID found in EVV table for this visit</p>
                    <p><strong>Check Time:</strong> #now()#</p>
                </cfmail>
            </cfif>

        <cfcatch>
            <cfset return_status = "Error: #cfcatch.message#">
            
            <!--- Send error email notification --->
            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="Arizona Visit Status Check Error - #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last# (#Schedule_ID#)" type="html">
                <h3>Arizona Visit Status Check Error</h3>
                <p><strong>Patient Name:</strong> #GetVisitInfo.Pt_First#, #GetVisitInfo.Pt_Last#</p>
                <p><strong>Employee Name:</strong> #GetVisitInfo.Emp_First#, #GetVisitInfo.Emp_Last#</p>
                <p><strong>Schedule ID:</strong> #Schedule_ID#</p>
                <p><strong>Error:</strong> #cfcatch.message#</p>
                <p><strong>Check Time:</strong> #now()#</p>
                <pre>#cfcatch.detail#</pre>
            </cfmail>
        </cfcatch>
        </cftry>

        <cfreturn return_status>
    </cffunction>

    <cffunction name="check_client_status" 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">

        <cfset Patient_ID  = decrypt(#arguments.Patient_ID#,#application.enckey#,"AES","Hex") />
        
        <!--- Initialize LOCAL variables --->
        <cfset LOCAL.username = "2n9xzzfv">
        <cfset LOCAL.password = "@$48jnh6{0}G">
        <cfset LOCAL.account = '215035'>
        <cfset LOCAL.ProviderID = '2279160425'>
        <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
        
        <!--- 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.username = getagency.EVV_prod_username>
                <cfset LOCAL.password = getagency.EVV_prod_password>
                <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
                <cfset LOCAL.account = getagency.EVV_prod_account>
            <cfelse>
                <cfset LOCAL.username = getagency.EVV_username>
                <cfset LOCAL.password = getagency.EVV_password>
                <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
                <cfset LOCAL.account = getagency.EVV_account>
            </cfif>
        </cfif>
        <cfset LOCAL.authString = toBase64(LOCAL.username & ":" & LOCAL.password)>

        <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://api.sandata.com/interfaces/intake/clients/rest/api/v1.1/status?uuid=#LOCAL.uuid#">
                <cfelse>
                    <cfset LOCAL.statusEndpoint = "https://uat-api.sandata.com/interfaces/intake/clients/rest/api/v1.1/status?uuid=#LOCAL.uuid#">
                </cfif>
                
                <!--- Make API call to Sandata status endpoint --->
                <cfhttp 
                    url="#LOCAL.statusEndpoint#"
                    method="GET" 
                    timeout="100"
                    result="httpStatusResponse">
                    <cfhttpparam name="Content-Type" type="HEADER" value="application/json">
                    <cfhttpparam name="Authorization" type="HEADER" value="Basic #LOCAL.authString#">
                    <cfhttpparam name="account" type="HEADER" value="#LOCAL.account#">
                </cfhttp>

                <cfset return_status = "SUCCESS">
                
                <!--- Send email notification --->
                <cfmail to="#sendto_email#" from="info@myhomecarebiz.com" subject="Arizona Client Status Check - #GetPatientInfo.Pt_First#, #GetPatientInfo.Pt_Last# (#Patient_ID#)" type="html">
                    <h3>Arizona 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>API Response:</strong></p>
                    <pre>#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="Arizona Client Status Check Error - #GetPatientInfo.Pt_First#, #GetPatientInfo.Pt_Last# (#Patient_ID#)" type="html">
                    <h3>Arizona 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 in EVV table for this client</p>
                    <p><strong>Check Time:</strong> #now()#</p>
                </cfmail>
            </cfif>

        <cfcatch>
            <cfset return_status = "Error: #cfcatch.message#">
            
            <!--- Send error email notification --->
            <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="Arizona Client Status Check Error - #GetPatientInfo.Pt_First#, #GetPatientInfo.Pt_Last# (#Patient_ID#)" type="html">
                <h3>Arizona 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>Check Time:</strong> #now()#</p>
                <pre>#cfcatch.detail#</pre>
            </cfmail>
        </cfcatch>
        </cftry>

        <cfreturn return_status>
    </cffunction>


    <cffunction name="visit_creation" access="remote" returnFormat= "plain">
            <cfargument name="Agency_ID" required="no"  default="#session.agencyid#"  hint="Agency_ID">
            <cfargument name="Schedule_ID" required="yes" default="0" hint="Schedule_ID">
            <cfargument name="today_date" required="no" default="#now()#" hint="today_date">
            <cfargument name="GPS_end_time" required="no" default="" hint="GPS_end_time">
            <cfargument name="GPS_end_latitude" required="no" default="" hint="GPS_end_latitude">
            <cfargument name="GPS_end_longitude" required="no" default="" hint="GPS_end_longitude">

            <cfset Sch_ID = decrypt(#arguments.Schedule_ID#,#Application.enckey#,"AES","Hex") />
            
            <!--- Initialize LOCAL variables --->
            <cfset LOCAL.username = "2n9xzzfv">
            <cfset LOCAL.password = "@$48jnh6{0}G">
            <cfset LOCAL.account = '215035'>
            <cfset LOCAL.ProviderID = '2279160425'>
            <cfset sendto_email = "jasmin.s@myhomecarebiz.com,velmurugan@myhomecarebiz.com" />
            
            <!--- 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.username = getagency.EVV_prod_username>
                    <cfset LOCAL.password = getagency.EVV_prod_password>
                    <cfset LOCAL.ProviderID = getagency.EVV_prod_ProviderID>
                    <cfset LOCAL.account = getagency.EVV_prod_account>
                <cfelse>
                    <cfset LOCAL.username = getagency.EVV_username>
                    <cfset LOCAL.password = getagency.EVV_password>
                    <cfset LOCAL.ProviderID = getagency.EVV_ProviderID>
                    <cfset LOCAL.account = getagency.EVV_account>
                </cfif>
            </cfif>
            <cfset LOCAL.authString = toBase64(LOCAL.username & ":" & LOCAL.password)>
            
            <cftry>
                <cfif application.DEV EQ false>
                    <cfset LOCAL.AuthorizationEndpoint = "https://api.sandata.com/interfaces/intake/visits/rest/api/v1.1">
                <cfelse>
                    <cfset LOCAL.AuthorizationEndpoint = "https://uat-api.sandata.com/interfaces/intake/visits/rest/api/v1.1">
                </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,
                    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,
                    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,
                    IFNULL(pPtPayer.Sub_HIC,pSchedules.Schedule_ID) AS Sub_HICs, 
                    pEmployee.*, pAssessments.Assmt_ID,pAuths.*,pPayer.*,pPtPayer.*,Agency.*,pRevenue_Code.HCPCS,pPhysicians.Phys_NPI,pRevenue_Code.HCPCS
                    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.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.Rev_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>
                <cfset currentDate = Now()>
                <cfset formattedDateTime = DateFormat(currentDate, "yyyy-mm-dd") & "T" & TimeFormat(currentDate, "HH:mm:ss") & "Z">
                <cfset Start_Time = DateFormat(GtSched.Visit_Date, "yyyy-mm-dd") & "T" & GtSched.StartTime  & "Z">
                <cfset End_Time = DateFormat(GtSched.Visit_Date, "yyyy-mm-dd") & "T" & GtSched.EndTime  & "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" & GtSched.GPS_start_time  & "Z">
                </cfif>
                <cfif GtSched.GPS_end_time NEQ ''>
                  <cfset Adjust_End_Time = DateFormat(GtSched.GPS_end_date, "yyyy-mm-dd") & "T" & GtSched.GPS_end_time  & "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" & GtSched.StartTime  & "Z">
                        <cfset Adjust_End_Time = DateFormat(GtSched.Visit_Date, "yyyy-mm-dd") & "T" & GtSched.EndTime  & "Z">  
                    </cfif>   
                </cfif>
                <cfset Total_Hours = 0 >
                <cfif GtSched.Total_Units gt 0 >
                    <cfset Total_Hours = (#GtSched.Total_Units#)*(25/100)>
                </cfif>
                <cfset VisitTimeZone = "US/Mountain"> 
                <cfif application.TimeZone  EQ 'CST'>
                    <cfset VisitTimeZone = "US/Central">
                <cfelseif application.TimeZone  EQ 'MST'>
                    <cfset VisitTimeZone = "US/Mountain">
                <cfelseif application.TimeZone  EQ 'PST'>
                    <cfset VisitTimeZone = "US/Pacific">
                <cfelseif application.TimeZone  EQ 'AKST'>
                    <cfset VisitTimeZone = "US/Alaska">
                <cfelseif application.TimeZone  EQ 'HST'>
                    <cfset VisitTimeZone = "US/Hawaii">
                </cfif>

                <cfset PayerID = 'COHCPF'>
                <cfset PayerProgram = 'HCPF'>
                <cfset ProcedureCode = 'LST'>
                <cfset PayerID = 'AZCCCS'>
                <cfset PayerProgram = 'AHCCCS'>
                <cfset ProcedureCode = 'G0151'>
                <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> 

                <cfquery  name="GET_EVV"  datasource="#Application.DataSrc#">
                    SELECT (IFNULL(Max(Seq_ID),0)+1) as seq_id FROM #Request.prefix_db_lookup#.EVV 
                    WHERE API_type = 'visits'               
                </cfquery>
                <cfset Seq_ID = #GET_EVV.seq_id# />
                 <cfset ClientIdentifier = "A" & repeatString("0", 8 - len(#GtSched.Patient_ID#)) & #GtSched.Patient_ID#>

                <cfset Request.stFields = 
                    [
                        {
                            "ProviderIdentification": 
                            {
                                "ProviderID": "#LOCAL.ProviderID#",
                                "ProviderQualifier": "MedicaidID"
                            },
                            "VisitOtherID": "#Sch_ID#",
                            "SequenceID": #Seq_ID#,
                            "EmployeeQualifier": "EmployeeSSN",
                            "EmployeeOtherID": "#EmployeeIdentifier#",
                            "EmployeeIdentifier": "#EmployeeIdentifier#",
                            "GroupCode": "",
                            "ClientIDQualifier": "ClientCustomID",
                            "ClientID": "#ClientIdentifier#",
                            "ClientOtherID": "#ClientIdentifier#",
                            "VisitCancelledIndicator": false,
                            "PayerID": "#PayerID#",
                            "PayerProgram": "#PayerProgram#",
                            "ProcedureCode": "#ProcedureCode#",
                            "Modifier1": "",
                            "Modifier2": "",
                            "Modifier3": "",
                            "Modifier4": "",
                            "VisitTimeZone": "#VisitTimeZone#",
                            "ScheduleStartTime": "#Start_Time#",
                            "ScheduleEndTime": "#End_Time#",
                             "AdjInDateTime": "#Adjust_Start_Time#", 
                            "AdjOutDateTime": "#Adjust_End_Time#",
                            "BillVisit": true,
                            "HoursToBill": "#Total_Hours#",
                            "HoursToPay": "#GtSched.Mi_Pay#",
                            "Memo": "#Trim(GtSched.Memo)#",
                            "ClientVerifiedTimes": true,
                            "ClientVerifiedTasks": true,
                            "ClientVerifiedService": true,
                            "ClientSignatureAvailable": true,
                            "ClientVoiceRecording": true,
                            "Calls": 
                            [
                                {
                                    "CallExternalID": "#GtSched.Schedule_ID#",
                                    "CallDateTime": "#Adjust_Start_Time#",
                                    "CallAssignment": "Time In",
                                    "GroupCode": "",
                                    "CallType": "Other",
                                    "ProcedureCode": "#ProcedureCode#",
                                    "ClientIdentifierOnCall": "#LEFT(GtSched.Sub_HICs,9)#",
                                    "MobileLogin": "123",
                                    "CallLatitude": "#GtSched.GPS_end_latitude#",
                                    "CallLongitude": "#GtSched.GPS_end_longitude#",
                                    "Location": "123",
                                    "TelephonyPIN": 999999999,
                                    "OriginatingPhoneNumber": "9997779999"
                                },
                                 {
                                    "CallExternalID": "#GtSched.Schedule_ID#", 
                                    "CallDateTime": "#Adjust_End_Time#",
                                    "CallAssignment": "Time Out", 
                                    "GroupCode":  "", 
                                    "CallType": "Other",
                                    "ProcedureCode": "#ProcedureCode#", 
                                    "ClientIdentifierOnCall": "#LEFT(GtSched.Sub_HICs,9)#",
                                    "MobileLogin": "123",
                                    "CallLatitude": '#GtSched.GPS_end_latitude#',
                                    "CallLongitude": '#GtSched.GPS_end_longitude#',
                                    "Location": "123",
                                    "TelephonyPIN": 999999999,
                                    "OriginatingPhoneNumber": "9997779999"
                                    }
                            ],
                            "VisitExceptionAcknowledgement": [{
                                "ExceptionID": "5",
                                "ExceptionAcknowledged": true
                                }],

                          
                            "VisitChanges": 
                            [   {
                                    "SequenceID": "#Seq_ID#",
                                    "ChangeMadeBy": "#GtSched.Emp_Email#",
                                    "ChangeDateTime": "#Start_Time#",
                                    "GroupCode": "",
                                    "ReasonCode": "11",
                                    "ChangeReasonMemo": "EVV Vist Date modification",
                                    "ResolutionCode": "5"
                                }
                            ],
                            "VisitTasks": 
                            [
                                {
                                    "TaskID": "321",
                                    "TaskReading": "98.6",
                                    "TaskRefused": false
                                }
                            ]
                        }
                    ] >
                <!--- <cfdump var="#Request.stFields#">
                <cfdump var="#serializeJSON(Request.stFields)#">---> 
                <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="Authorization" type="HEADER" value="Basic #LOCAL.authString#">
                    <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">
                      <!--- <cfdump var="#GtSched#">
                    <cfdump var="#serializeJSON(Request.stFields)#">
                    <cfdump var = "#httpEVVResponse#"> --->
                <cfif httpEVVResponse.responseHeader.Status_Code eq 200>  
                    <cfset structureData  = DeserializeJSON(httpEVVResponse.Filecontent)>
                   <!---  <cfdump var="#structureData.status#"><cfabort> --->
                    <cfset return_status = structureData.status >
                    <cfif return_status EQ 'SUCCESS'>
                        <cfset title = "Powerpath EVV Visit API  Successfuly send to SAN">
                        <cfset fromaddress = "info@myhomecarebiz.com">
                    <cfelse>
                        <cfset title = "Powerpath EVV Visit API Failed due to SAN data return">
                         <cfset fromaddress = "error@myhomecarebiz.com">
                    </cfif>   
                    <cfset responseStruct = structureData>
                    <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="#fromaddress#" subject="#title#" type="html">
                            REQUEST: <cfdump var="#serializeJSON(Request.stFields)#"><br>
                            RESPONSE: <cfdump var="#httpEVVResponse#">
                    </cfmail> 
                    <cfset UUID = structureData.id />
                    <cfquery  name="INSERT_EVV"  datasource="#Application.DataSrc#">
                        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>             
                    
                <cfelse>
                    <cfset structureData  = DeserializeJSON(httpEVVResponse.Filecontent)>
                    <cfset responseStruct = structureData>
                    <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="Powerpath EVV Visit API  Error" type="html">
                            Error: <cfdump var="#return_status#">
                            REQUEST: <cfdump var="#serializeJSON(Request.stFields)#"><br>
                            RESPONSE: <cfdump var="#httpEVVResponse#">
                    </cfmail>            
                </cfif>
                <cfreturn return_status>
                <cfcatch>
                     <cfmail to="#sendto_email#" from="error@myhomecarebiz.com" subject="Powerpath EVV Visit API  Error" type="html">
                        <cfdump var="#cfcatch#">
                    </cfmail> 
                </cfcatch>
            </cftry>

    </cffunction>





</cfcomponent>