<cfcomponent  displayname="API Functions" hint="I Return API Information" output="true">
    <!--- Add CORS headers here --->
    <cfheader name="Access-Control-Allow-Origin" value="*">
    <cfheader name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE">
    <cfheader name="Access-Control-Allow-Headers" value="Content-Type, Authorization">
    <cfset application.enckey = "54kczhzgHTj4a8n+SRZPyg==" >

    <cffunction name="checkusers" access="remote"  returnformat="JSON" >
            <cfargument name="username" required="yes" hint="User name">
            <cfargument name="password" required="yes" hint="Password">
            <cfset  encryptedpassword =  #encrypt(arguments.password, "WTq8zYcZfaWVvMncigHqwQ==", "AES", "Base64")# />

            <cfquery name="getemps"  datasource="#Application.DataSrc#">
                    SELECT pEmployee.*,Agency.Agency_Login FROM  hhapowerpath.pEmployee
                    JOIN hhapowerpath.Agency ON Agency.Agency_ID = pEmployee.Loc_ID
                    WHERE pEmployee.Username =  <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.username#" >
                    AND pEmployee.Password = <cfqueryparam cfsqltype="cf_sql_varchar" value="#encryptedpassword#">
                    AND pEmployee.Emp_Type = 'Employee'
                    AND pEmployee.Status = 0
            </cfquery> 
            <cfset Emp_key  = "" >
             <cfset response = [] />
            <cfif getemps.recordcount gt 0> 
                <cfoutput query="getemps">
                 <cfset  Emp_key  = encrypt(#getemps.Emp_ID#,#application.enckey#,"AES","Hex") /> 
                    <cfset obj = { "Emp_ID" = Emp_ID, "Emp_First" = Emp_First, "Emp_Last" = Emp_Last,
                                 "Agency_ID" = Loc_ID, "Agency_Login" = Agency_Login,
                                  "Emp_key" = Emp_key,"success": true, "message": "Login successful"  
                      } />
                    <cfset arrayAppend(response, obj) />
                </cfoutput>
            <cfelse>
                 <cfset obj = { "success": false, "message": "Invalid username or password" 
                      } />
                <cfset arrayAppend(response, obj) />
             </cfif>  
            <cfreturn #serializeJSON(response)#>              
    </cffunction>
    
    <cffunction name="getpatients" access="remote"  returnformat="JSON" >
            <cfargument name="Emp_ID" required="yes" hint="Emp_ID">
            <cfargument name="Emp_key" required="yes" hint="Emp_key">
            <cfargument name="Agency_ID" required="yes" hint="Agency_ID">
            <cfset Empkey   = #arguments.Emp_key#>
            <cfset Request.prefix_db_agency = 'agency_'& Agency_ID />
            <cfquery name="checkDBExistence" datasource="#Application.DataSrc#">
                SELECT SCHEMA_NAME   FROM information_schema.schemata 
                WHERE SCHEMA_NAME = '#Request.prefix_db_agency#';
            </cfquery>
            <cftry>
                <cfset Empkey   = decrypt(#arguments.Emp_key#,#application.enckey#,"AES","Hex") />
                <cfcatch>
                </cfcatch>
            </cftry>
            <cfset response = [] />
            <cfif Empkey EQ arguments.Emp_ID AND checkDBExistence.recordcount gt 0>
                <cfquery name="getpats"  datasource="#Application.DataSrc#">
                        SELECT * FROM #Request.prefix_db_agency#.pPatients
                        WHERE Loc_ID =  <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.Agency_ID#" >
                        AND Status IN (0,1,4)
                </cfquery> 
                    <cfif getpats.recordcount gt 0 >
                        <cfoutput query="getpats">
                            <cfset obj = { "Patient_ID" = Patient_ID, "Pt_Agy_ID" = Pt_Agy_ID,
                                          "Pt_First" = Pt_First, "Pt_Middle" = Pt_Middle,"Pt_Last" = Pt_Last,
                                          "Pt_Street" = Pt_Street,"Pt_City" = Pt_City,"Pt_State" = Pt_State,
                                          "Pt_Phone" = Pt_Phone,"Pt_Zip" = Pt_Zip,"Pt_DOB" = Pt_DOB,"Pt_Race" = Pt_Race,"Agency_ID" = #arguments.Agency_ID#, "Emp_key" = arguments.Emp_key, "Emp_ID" = arguments.Emp_ID, "success": true
                              } />
                            <cfset arrayAppend(response, obj) />
                        </cfoutput>
                    <cfelse>
                         <cfset obj = { "Patient_ID" = "", "Pt_Agy_ID" = "",
                                          "Pt_First" = "", "Pt_Middle" = "","Pt_Last" = "",
                                          "Pt_Street" = "","Pt_City" = "","Pt_State" = "",
                                          "Pt_Phone" = "","Pt_Zip" = "","Pt_DOB" = "","Pt_Race" = "",
                                         "Agency_ID" = arguments.Agency_ID, "Emp_key" = arguments.Emp_key, 
                                         "Emp_ID" = arguments.Emp_ID,"success": true 
                              } />
                            <cfset arrayAppend(response, obj) />
                    </cfif>
            <cfelse>
                 <cfset obj = { "success": false, "message": "Invalid username or password" 
                      } />
                <cfset arrayAppend(response, obj) />
             </cfif> 
            <cfreturn #serializeJSON(response)#>              
    </cffunction>



    <cffunction name="getschedules" access="remote"  returnformat="JSON" >
            <cfargument name="Emp_ID" required="yes" hint="Emp_ID">
            <cfargument name="Emp_key" required="yes" hint="Emp_key">
            <cfargument name="Agency_ID" required="yes" hint="Agency_ID">
            <cfargument name="Patient_ID" required="no" default="0" hint="Patient_ID">
            <cfargument name="Visit_Date" required="no" default="" hint="Patient_ID">
            <cfargument name="Schedule_ID" required="no" default="0" hint="Schedule_ID">

            <cfset Empkey   = #arguments.Emp_key#>
            <cfset Request.prefix_db_agency = 'agency_'& Agency_ID />
            <cfquery name="checkDBExistence" datasource="#Application.DataSrc#">
                SELECT SCHEMA_NAME   FROM information_schema.schemata 
                WHERE SCHEMA_NAME = '#Request.prefix_db_agency#';
            </cfquery>
            <cftry>
                <cfset Empkey   = decrypt(#arguments.Emp_key#,#application.enckey#,"AES","Hex") />
                <cfcatch>
                </cfcatch>
            </cftry>
            <cfset response = [] />
             <cfset today_date = #DateFormat(now(),"yyyy-mm-dd")# />
            <cfif Empkey EQ arguments.Emp_ID AND checkDBExistence.recordcount gt 0>
                <cfset Request.prefix_db_agency = 'agency_'& Agency_ID />
                <cfquery name="getsch"  datasource="#Application.DataSrc#">
                        SELECT pSchedules.*, pPatients.Pt_First,pPatients.Pt_Middle,pPatients.Pt_Last 
                         FROM #Request.prefix_db_agency#.pSchedules
                        JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pSchedules.Patient_ID
                        AND pPatients.Status = 0 
                         JOIN #Request.prefix_db_agency#.pAssessments ON pAssessments.Patient_ID = pSchedules.Patient_ID
                        AND pAssessments.Status = 0 
                        JOIN #Request.prefix_db_agency#.pAuths  ON pSchedules.Auth_ID = pAuths.Auth_ID AND pAuths.status = 0
                        JOIN  #Request.prefix_db_agency#.pRevenue_Code ON pRevenue_Code.Rev_CodeID = pAuths.Rev_ID AND pRevenue_Code.status = 0
                        JOIN  #Request.prefix_db_agency#.pAdmit ON pAdmit.Admit_ID = pAssessments.Admit_ID AND  pAdmit.status =0
                        WHERE pSchedules.Status = 0 
                        AND pSchedules.Missed = 0
                        <cfif arguments.Patient_ID NEQ 0 >
                            AND pSchedules.Patient_ID =  #arguments.Patient_ID#
                        </cfif>
                        <cfif arguments.Visit_Date NEQ "" AND isdate(arguments.Visit_Date)>
                            AND pSchedules.Visit_Date =  '#DateFormat(arguments.Visit_Date,"yyyy-mm-dd")#'
                        <cfelse>
                           <!--- AND pSchedules.Visit_Date =  '#DateFormat(today_date,"yyyy-mm-dd")#'  --->
                        </cfif>
                        <cfif arguments.Schedule_ID NEQ 0>
                            AND pSchedules.Schedule_ID =  '#arguments.Schedule_ID#'
                        </cfif>
                        AND pSchedules.Emp_ID =  #arguments.Emp_ID#
                        GROUP BY  pSchedules.Schedule_ID
                  </cfquery> 
                    <cfif getsch.recordcount gt 0 >
                        <cfoutput query="getsch">
                            <cfif Visit_Type NEQ ''>
                                <cfset skills = '#Skill#' >
                            <cfelse>
                                <cfset skills = '#Skill#' >
                            </cfif>
                            <cfset obj = { "Schedule_ID" = getsch.Schedule_ID,"Patient_ID" = getsch.Patient_ID, 
                                          "Pt_First" = Pt_First, "Pt_Middle" = Pt_Middle,"Pt_Last" = Pt_Last,
                                          "Visit_Date" = '#DateFormat(getsch.Visit_Date,"yyyy-mm-dd")#',"Notes" = Notes,"StartTime" = '#TimeFormat(getsch.StartTime)#',
                                          "EndTime" = '#TimeFormat(getsch.EndTime)#',"Skill" = #skills#,
                                           "GPS_start_time" = '#TimeFormat(getsch.GPS_start_time)#',
                                           "GPS_end_time" = '#TimeFormat(getsch.GPS_end_time)#',
                                           "pgnotesdraft" = #pgnotesdraft#,
                                           "GPS_start_latitude" = '#GPS_start_latitude#',
                                           "GPS_start_longitude"  ='#GPS_start_longitude#',
                                           "GPS_end_latitude" = '#GPS_end_latitude#',
                                           "GPS_end_longitude"  ='#GPS_end_longitude#',
                                           "Agency_ID" = #arguments.Agency_ID#, "Emp_key" = arguments.Emp_key, "Emp_ID" = arguments.Emp_ID, "success": true
                              } />
                            <cfset arrayAppend(response, obj) />
                        </cfoutput>
                    <cfelse>
                         <cfset obj = { "Schedule_ID" = "", "Patient_ID" = "", "Pt_Agy_ID" = "",
                                        "Pt_First" = "" , "Pt_Middle" = "","Pt_Last" = "",
                                          "Visit_Date" = "","Notes" = "","StartTime" = "",
                                          "EndTime" = "","Skill" = "", "Agency_ID" = #arguments.Agency_ID#, 
                                          "Emp_key" = arguments.Emp_key, 
                                         "Emp_ID" = arguments.Emp_ID,"success": true 
                              } />
                            <cfset arrayAppend(response, obj) />
                    </cfif>
            <cfelse>
                 <cfset obj = { "success": false, "message": "Invalid username or password" 
                      } />
                <cfset arrayAppend(response, obj) />
             </cfif> 
            <cfreturn #serializeJSON(response)#>              
    </cffunction>



    <cffunction name="update_schedules" access="remote"  returnformat="JSON" >
            <cfargument name="Emp_ID" required="yes" hint="Emp_ID">
            <cfargument name="Emp_key" required="yes" hint="Emp_key">
            <cfargument name="Agency_ID" required="yes" hint="Agency_ID">
            <cfargument name="Schedule_ID" required="yes" default="0" hint="Schedule_ID">
            <cfargument name="Patient_ID" required="no" default="0" hint="Patient_ID">
            <cfargument name="GPS_start_time" required="no" default="0" hint="GPS_start_time">
            <cfargument name="GPS_end_time" required="no" default="0" hint="GPS_end_time">
            <cfargument name="GPS_start_latitude" required="no" default="0" hint="GPS_start_latitude">
            <cfargument name="GPS_start_longitude" required="no" default="0" hint="GPS_start_longitude">
            <cfargument name="GPS_end_latitude" required="no" default="0" hint="GPS_end_latitude">
            <cfargument name="GPS_end_longitude" required="no" default="0" hint="GPS_end_longitude">
            <cfargument name="today_date" required="no" default="0" hint="2025-02-19">

            <cfset Empkey   = #arguments.Emp_key#>
            <cfset encrypted_empkey = #arguments.Emp_key#>
            <cfset Request.prefix_db_agency = 'agency_'& Agency_ID />
            <cfquery name="checkDBExistence" datasource="#Application.DataSrc#">
                SELECT SCHEMA_NAME   FROM information_schema.schemata 
                WHERE SCHEMA_NAME = '#Request.prefix_db_agency#';
            </cfquery>
            <cftry>
                <cfset Empkey   = decrypt(#arguments.Emp_key#,#application.enckey#,"AES","Hex") />
                <cfcatch>
                </cfcatch>
            </cftry>
            <cfset response = [] />
            <cfset today_date = #DateFormat(today_date,"yyyy-mm-dd")# />
            <cfif Empkey EQ arguments.Emp_ID AND checkDBExistence.recordcount gt 0>
                <cfset Request.prefix_db_agency = 'agency_'& Agency_ID />
                <cfquery name="get_sched"  datasource="#Application.DataSrc#">
                         SELECT pSchedules.* FROM  #Request.prefix_db_agency#.pSchedules
                         WHERE pSchedules.Status = 0
                         AND pSchedules.Schedule_ID =  '#arguments.Schedule_ID#'
                </cfquery>
                <cfif left(get_sched.Visit_Type,1) EQ 1 AND arguments.GPS_start_longitude NEQ ''>
                    <cfquery name="update_pat_latitude"  datasource="#Application.DataSrc#">
                             UPDATE   #Request.prefix_db_agency#.pPatients
                             SET Pt_Longitude = '#arguments.GPS_start_longitude#',
                                 Pt_Latitude = '#arguments.GPS_start_latitude#'
                             WHERE pPatients.Status IN (0,1,4)
                             AND Patient_ID = '#get_sched.Patient_ID#'
                    </cfquery>
                </cfif>

                <cfquery name="get_patients"  datasource="#Application.DataSrc#">
                         SELECT pSchedules.*,pPatients.* FROM  #Request.prefix_db_agency#.pSchedules
                         JOIN  #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pSchedules.Patient_ID
                         AND pPatients.Status IN (0,1,4)
                         WHERE pSchedules.Status = 0
                         AND pSchedules.Schedule_ID =  '#arguments.Schedule_ID#'
                </cfquery>
                <!--- <cfdump var="#get_patients#">--->
                <cfset Pt_Longitude = get_patients.Pt_Longitude />
                <cfset Pt_Latitude = get_patients.Pt_Latitude />
                <cfset update_gps =  0 >
                <cfset request.message =  "" >
                <cfset threshold = 0.1>
                <cfif arguments.GPS_start_latitude NEQ '' >
                    <cfset diff_latitude = abs(Pt_Latitude - arguments.GPS_start_latitude)> 
                    <cfset diff_longitude = abs(Pt_Longitude - arguments.GPS_start_longitude)> 
                    <cfif diff_latitude LTE threshold  AND  diff_longitude LTE threshold > 
                        <cfset request.message = "GPS start Latitude and Longitude recorded successfully!">
                        <cfset update_gps =  1 >
                    <cfelse>
                         <cfset request.message = "Your current GPS location is not the same as the patient address. We are unable to initiate EVV.<br>visit_latitude:" & #arguments.GPS_start_latitude# &
                        "<br>visit_longitude:"& #arguments.GPS_start_longitude# & "<br>Pt_Latitude:" & #Pt_Latitude# &  "<br>Pt_Longitude:" & #Pt_Longitude# />
                    </cfif>
                <cfelseif arguments.GPS_end_latitude NEQ ''> 
                    <cfset diff_latitude = abs(Pt_Latitude - arguments.GPS_end_latitude)> 
                    <cfset diff_longitude = abs(Pt_Longitude - arguments.GPS_end_longitude)>                     
                    <cfif diff_latitude LTE threshold  AND  diff_longitude LTE threshold > 
                         <cfset request.message = "GPS End Latitude and Longitude recorded successfully!">
                        <cfset update_gps =  1 >
                    <cfelse>
                         <cfset request.message = "Your current GPS location is not the same as the patient address. We are unable to initiate EVV.<br>visit_latitude:" & #arguments.GPS_start_latitude# &
                        "<br>visit_longitude:"& #arguments.GPS_start_longitude# & "<br>Pt_Latitude:"& #Pt_Latitude# &  "<br>Pt_Longitude:"& #Pt_Longitude# />
                    </cfif>
                </cfif>
                
                <cfif update_gps EQ 1 >
                    <cfquery name="updateSch"  datasource="#Application.DataSrc#">
                            UPDATE #Request.prefix_db_agency#.pSchedules
                            SET 
                                <cfif arguments.GPS_start_time NEQ ''>
                                    GPS_start_time = '#GPS_start_time#',
                                    GPS_start_date = '#today_date#',
                                </cfif>
                                 <cfif arguments.GPS_start_latitude NEQ ''>
                                    GPS_start_latitude = '#GPS_start_latitude#',
                                </cfif>
                                <cfif arguments.GPS_start_longitude NEQ ''>
                                    GPS_start_longitude = '#GPS_start_longitude#',
                                </cfif>

                                <!--- <cfif arguments.GPS_end_time NEQ ''>
                                    GPS_end_time = '#GPS_end_time#',
                                    GPS_end_date = '#today_date#',
                                </cfif>
                                 <cfif arguments.GPS_end_latitude NEQ ''>
                                    GPS_end_latitude = '#GPS_end_latitude#',
                                </cfif>
                                 <cfif arguments.GPS_end_longitude NEQ ''>
                                    GPS_end_longitude = '#GPS_end_longitude#',
                                </cfif>  --->
                                Change_by = #arguments.Emp_ID#,
                                Date_Change = #now()#
                            WHERE Status = 0
                            AND pSchedules.Schedule_ID =  '#arguments.Schedule_ID#'
                    </cfquery>
                    <cfif arguments.GPS_end_time NEQ ''>
                        <cfset sandata_response  = call_SAN('#arguments.Emp_ID#','#encrypted_empkey#','#arguments.Agency_ID#','#arguments.Schedule_ID#','#today_date#','#GPS_end_time#','#arguments.GPS_end_latitude#','#arguments.GPS_end_longitude#') />
                        <cfif sandata_response NEQ 'Success'>
                            <cfset request.message =  "We did not able to send data into SAN.So please contact your admin." >
                        <cfelse>
                            <cfquery name="updateSch"  datasource="#Application.DataSrc#">
                                UPDATE #Request.prefix_db_agency#.pSchedules
                                SET 
                                    <cfif arguments.GPS_end_time NEQ ''>
                                        GPS_end_time = '#GPS_end_time#',
                                        GPS_end_date = '#today_date#',
                                    </cfif>
                                     <cfif arguments.GPS_end_latitude NEQ ''>
                                        GPS_end_latitude = '#GPS_end_latitude#',
                                    </cfif>
                                     <cfif arguments.GPS_end_longitude NEQ ''>
                                        GPS_end_longitude = '#GPS_end_longitude#',
                                    </cfif> 
                                    Change_by = #arguments.Emp_ID#,
                                    Date_Change = #now()#
                                WHERE Status = 0
                                AND pSchedules.Schedule_ID =  '#arguments.Schedule_ID#'
                            </cfquery>
                        </cfif>
                    </cfif>
                </cfif>
                 <cfset obj = { "success": true, "message": "#request.message#" 
                      } />
                <cfset arrayAppend(response, obj) />
            <cfelse>
                 <cfset obj = { "success": false, "message": "Invalid username or password" 
                      } />
                <cfset arrayAppend(response, obj) />
             </cfif> 
            <cfreturn #serializeJSON(response)#>   
    </cffunction>

    <cffunction name="call_SAN" access="private" returnFormat= "plain">
        <cfargument name="Emp_ID" required="yes" hint="Emp_ID">
        <cfargument name="Emp_key" required="yes" hint="Emp_key">
        <cfargument name="Agency_ID" required="yes" hint="Agency_ID">
        <cfargument name="Schedule_ID" required="yes" default="0" hint="Schedule_ID">
        <cfargument name="today_date" required="yes" default="0" hint="today_date">
        <cfargument name="GPS_end_time" required="yes" default="0" hint="GPS_end_time">
        <cfargument name="GPS_end_latitude" required="yes" default="0" hint="GPS_end_latitude">
        <cfargument name="GPS_end_longitude" required="yes" default="0" hint="GPS_end_longitude">

        <cfset LOCAL.username = "2n9xzzfv">
        <cfset LOCAL.password = "@$48jnh6{0}G">
        <cfset LOCAL.authString = toBase64(LOCAL.username & ":" & LOCAL.password)>
        <cfset LOCAL.account  = '215035'>
        <cfset LOCAL.AuthorizationEndpoint = "https://uat-api.sandata.com/interfaces/intake/visits/rest/api/v1.1">
        <cfset LOCAL.ProviderID = '2279160425' >
        <cfquery name="getagency" datasource="#Application.DataSrc#">
            SELECT * FROM  #Request.prefix_db_lookup#.Agency
            WHERE Agency_ID = '#arguments.Agency_ID#'  
        </cfquery>
        <cfif len(getagency.EVV_username) gt 0>
            <cfset LOCAL.username = getagency.EVV_username>
        </cfif>
        <cfif len(getagency.EVV_password) gt 0>
            <cfset LOCAL.password = getagency.EVV_password>
            <cfset LOCAL.authString = toBase64(LOCAL.username & ":" & LOCAL.password)>
        </cfif>
        <cfif len(getagency.EVV_account) gt 0>
            <cfset  LOCAL.account = getagency.EVV_account>
        </cfif>
        <cfif len(getagency.EVV_link) gt 0>
            <cfset  LOCAL.AuthorizationEndpoint = getagency.EVV_link>
        </cfif>
        <cfif len(getagency.EVV_ProviderID) gt 0>
            <cfset  LOCAL.ProviderID = getagency.EVV_ProviderID>
        </cfif>





        <cftry>
        <cfquery name="getemployee" datasource="#Application.DataSrc#">
            SELECT * FROM  #Request.prefix_db_lookup#.pEmployee
            WHERE Emp_ID = '#arguments.Emp_ID#'  
        </cfquery>
        <cfset employee_custom_id = "#getemployee.Emp_Custom_1#" >

        <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.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="#arguments.Schedule_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 arguments.GPS_end_time NEQ ''>
            <cfset Adjust_End_Time = DateFormat(arguments.today_date, "yyyy-mm-dd") & "T" & arguments.GPS_end_time  & "Z">
        </cfif>
        <cfif getemployee.Username EQ 'MTe7753m'>
            <cfset Adjust_Start_Time = DateFormat(Previous_Day, "yyyy-mm-dd") & "T" & GtSched.GPS_start_time  & "Z">
            <cfset Adjust_End_Time = DateFormat(Previous_Day, "yyyy-mm-dd") & "T" & GtSched.GPS_start_time  & "Z">     
        </cfif>
        <cfset Total_Hours = 0 >
        <cfif GtSched.Total_Units gt 0 >
            <cfset Total_Hours = (#GtSched.Total_Units#)*(25/100)>
        </cfif>
        <cfset VisitTimeZone = "US/Eastern">
        <!--- <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 VisitTimeZone = "US/Mountain">
        <cfif CGI.REMOTE_ADDR EQ '103.143.7.161'>
              <cfset VisitTimeZone = "America/Chicago">   
        </cfif>--->

        <cfset PayerID = 'COHCPF'>
        <cfset PayerProgram = 'HCPF'>
        <cfset ProcedureCode = 'BHSVC'>

        <cfset Request.stFields =[{
                "ProviderIdentification": {
                    "ProviderID": "#LOCAL.ProviderID#",
                    "ProviderQualifier": "MedicaidID"
                },
                "VisitOtherID": "1233",
                "SequenceID": "#GtSched.Emp_ID#",
                "EmployeeQualifier": "EmployeeCustomID",
                "EmployeeCustomID": "#GtSched.Loc_ID#",
                "EmployeeOtherID": "#GtSched.EmployeeIdentifier#",
                "EmployeeIdentifier": "#GtSched.EmployeeIdentifier#",
                "EmployeeLastName": "#GtSched.Emp_Last#",
                "EmployeeFirstName": "#GtSched.Emp_First#",
                "GroupCode": "",
                "ClientIDQualifier": "ClientMedicaidID",
                "ClientID": "#GtSched.Sub_HICs#",
                "ClientOtherID": "#GtSched.Sub_HICs#",
                "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": "",
                "CallLatitude": "#GtSched.GPS_start_latitude#",
                "CallLongitude": "#GtSched.GPS_start_longitude#",
                "Location": "123",
                "TelephonyPIN": 999999999,
                "OriginatingPhoneNumber": "9997779999"
                },
                {
                "CallExternalID": "#GtSched.Schedule_ID#", 
                "CallDateTime": "#Adjust_End_Time#",
                "CallAssignment": "Time Out", 
                "GroupCode": "null", 
                "CallType": "Other",
                "ProcedureCode": "#ProcedureCode#", 
                "ClientIdentifierOnCall": "#LEFT(GtSched.Sub_HICs,9)#",
                "MobileLogin": "",
                "CallLatitude": '#arguments.GPS_end_latitude#',
                "CallLongitude": '#arguments.GPS_end_longitude#',
                "Location": "123",
                "TelephonyPIN": 999999999,
                "OriginatingPhoneNumber": "9997779999"
                }],
                "VisitChanges": [{
                    "SequenceID": "110",
                    "ChangeMadeBy": "#GtSched.Emp_Email#",
                    "ChangeDateTime": "#formattedDateTime#",
                    "GroupCode": "",
                    "ReasonCode": "11",
                    "ChangeReasonMemo": "EVV Visit Start",
                    "ResolutionCode": "A"
                }]
                
            }]
        >
        <!--- <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">
        <!--- <cfif CGI.REMOTE_ADDR EQ '103.143.7.161'>
            <cfdump var="#serializeJSON(Request.stFields)#">
            <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 = "Mobile Application API  Successfuly send to SAN">
                <cfset fromaddress = "info@myhomecarebiz.com">
            <cfelse>
                <cfset title = "Mobile Application API Failed due to SAN data return">
                 <cfset fromaddress = "error@myhomecarebiz.com">
            </cfif>           
            <cfmail to="velmurugan@myhomecarebiz.com,melissa@myhomecarebiz.com" from="#fromaddress#" subject="#title#" type="html">
                    REQUEST: <cfdump var="#serializeJSON(Request.stFields)#"><br>
                    RESPONSE: <cfdump var="#httpEVVResponse#">
            </cfmail> 
        <cfelse>
            <cfmail to="velmurugan@myhomecarebiz.com,melissa@myhomecarebiz.com" from="error@myhomecarebiz.com" subject="Mobile Application API  Error" type="html">
                    REQUEST: <cfdump var="#serializeJSON(Request.stFields)#"><br>
                    RESPONSE: <cfdump var="#httpEVVResponse#">
            </cfmail>            
        </cfif>
        <cfreturn return_status>

        <cfcatch>
                 <cfmail to="velmurugan@myhomecarebiz.com,melissa@myhomecarebiz.com" from="error@myhomecarebiz.com" subject="Error on Mobile APP API" type="html">
                    <cfdump var="#cfcatch#">
                </cfmail> 
        </cfcatch>
    </cftry>

    </cffunction>


    <cffunction name="update_all_schedules" access="remote"  returnformat="JSON" >
            <cfargument name="Emp_ID" required="yes" hint="Emp_ID">
            <cfargument name="Emp_key" required="yes" hint="Emp_key">
            <cfargument name="Agency_ID" required="yes" hint="Agency_ID">
            <cfargument name="Schedules_data" required="yes" default="0" hint="Schedules_data">
            <cfdump var="#arguments#">
            <cfset schjson=  serializeJSON(arguments.Schedules_data) />
            <cfset dataArray = deserializeJSON(arguments.Schedules_data)>
            <cfoutput>
                <cfloop array="#dataArray#" index="record">
                    Type: #record.type#<br>
                    Emp_ID: #record.Emp_ID#<br>
                    Agency_ID: #record.Agency_ID#<br>
                    Date: #record.date#<br>
                    Time: #record.time#<br>
                    Lat: #record.lat#<br>
                    Lng: #record.lng#<br>
                    <hr>
                </cfloop>
            </cfoutput>
            <cfabort>
            <cfset Empkey   = #arguments.Emp_key#>
            <cfset encrypted_empkey = #arguments.Emp_key#>
            <cfset Request.prefix_db_agency = 'agency_'& Agency_ID />
            <cfquery name="checkDBExistence" datasource="#Application.DataSrc#">
                SELECT SCHEMA_NAME   FROM information_schema.schemata 
                WHERE SCHEMA_NAME = '#Request.prefix_db_agency#';
            </cfquery>
            <cftry>
                <cfset Empkey   = decrypt(#arguments.Emp_key#,#application.enckey#,"AES","Hex") />
                <cfcatch>
                </cfcatch>
            </cftry>
            <cfset response = [] />
            <cfset today_date = #DateFormat(now(),"yyyy-mm-dd")# />
            <cfif Empkey EQ arguments.Emp_ID AND checkDBExistence.recordcount gt 0>
                <cfset Request.prefix_db_agency = 'agency_'& Agency_ID />



                <cfquery name="get_sched"  datasource="#Application.DataSrc#">
                         SELECT pSchedules.* FROM  #Request.prefix_db_agency#.pSchedules
                         WHERE pSchedules.Status = 0
                         AND pSchedules.Schedule_ID =  '#arguments.Schedule_ID#'
                </cfquery>
                <cfif left(get_sched.Visit_Type,1) EQ 1>
                    <cfquery name="update_pat_latitude"  datasource="#Application.DataSrc#">
                             UPDATE   #Request.prefix_db_agency#.pPatients
                             SET Pt_Longitude = '#arguments.GPS_start_longitude#',
                                 Pt_Latitude = '#arguments.GPS_start_latitude#'
                             WHERE pPatients.Status IN (0,1,4)
                             AND Patient_ID = '#get_sched.Patient_ID#'
                    </cfquery>
                </cfif>
                <cfquery name="get_patients"  datasource="#Application.DataSrc#">
                         SELECT pSchedules.*,pPatients.* FROM  #Request.prefix_db_agency#.pSchedules
                         JOIN  #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pSchedules.Patient_ID
                         AND pPatients.Status IN (0,1,4)
                         WHERE pSchedules.Status = 0
                         AND pSchedules.Schedule_ID =  '#arguments.Schedule_ID#'
                </cfquery>
                <!--- <cfdump var="#get_patients#">--->
                <cfset Pt_Longitude = get_patients.Pt_Longitude />
                <cfset Pt_Latitude = get_patients.Pt_Latitude />
                <cfset update_gps =  1 >
                <cfset request.message =  "" >
                <cfset threshold = 0.1>

                
               
                 <cfset obj = { "success": true, "message": "#request.message#" 
                      } />
                <cfset arrayAppend(response, obj) />
            <cfelse>
                 <cfset obj = { "success": false, "message": "Invalid username or password" 
                      } />
                <cfset arrayAppend(response, obj) />
             </cfif> 
            <cfreturn #serializeJSON(response)#>   
    </cffunction>



    <cffunction name="getallschedules" access="remote"  returnformat="JSON" >
            <cfargument name="Emp_ID" required="yes" hint="Emp_ID">
            <cfargument name="Emp_key" required="yes" hint="Emp_key">
            <cfargument name="Agency_ID" required="yes" hint="Agency_ID">
            <cfargument name="Patient_ID" required="no" default="0" hint="Patient_ID">
            <cfargument name="Visit_Date" required="no" default="" hint="Patient_ID">
            <cfargument name="Schedule_ID" required="no" default="0" hint="Schedule_ID">

            <cfset Empkey   = #arguments.Emp_key#>
            <cfset Request.prefix_db_agency = 'agency_'& Agency_ID />
            <cfquery name="checkDBExistence" datasource="#Application.DataSrc#">
                SELECT SCHEMA_NAME   FROM information_schema.schemata 
                WHERE SCHEMA_NAME = '#Request.prefix_db_agency#';
            </cfquery>
            <cftry>
                <cfset Empkey   = decrypt(#arguments.Emp_key#,#application.enckey#,"AES","Hex") />
                <cfcatch>
                </cfcatch>
            </cftry>
            <cfset response = [] />
             <cfset today_date = #DateFormat(now(),"yyyy-mm-dd")# />
            <cfif Empkey EQ arguments.Emp_ID AND checkDBExistence.recordcount gt 0>
                <cfset Request.prefix_db_agency = 'agency_'& Agency_ID />
                <cfquery name="getsch"  datasource="#Application.DataSrc#">
                        SELECT pSchedules.*, pPatients.Pt_First,pPatients.Pt_Middle,pPatients.Pt_Last 
                         FROM #Request.prefix_db_agency#.pSchedules
                        JOIN #Request.prefix_db_agency#.pPatients ON pPatients.Patient_ID = pSchedules.Patient_ID
                        AND pPatients.Status = 0 
                        WHERE pSchedules.Status = 0 
                        AND pSchedules.Missed = 0
                        <!---AND pSchedules.Emp_ID =  #arguments.Emp_ID# --->
                  </cfquery> 
                    <cfif getsch.recordcount gt 0 >
                        <cfoutput query="getsch">
                            <cfif Visit_Type NEQ ''>
                                <cfset skills = '#Skill#' >
                            <cfelse>
                                <cfset skills = '#Skill#' >
                            </cfif>
                            <cfset obj = { "Schedule_ID" = getsch.Schedule_ID,"Patient_ID" = getsch.Patient_ID, 
                                          "Pt_First" = Pt_First, "Pt_Middle" = Pt_Middle,"Pt_Last" = Pt_Last,
                                          "Visit_Date" = '#DateFormat(getsch.Visit_Date,"yyyy-mm-dd")#',"Notes" = Notes,"StartTime" = '#TimeFormat(getsch.StartTime)#',
                                          "EndTime" = '#TimeFormat(getsch.EndTime)#',"Skill" = #skills#,
                                           "GPS_start_time" = '#TimeFormat(getsch.GPS_start_time)#',
                                           "GPS_end_time" = '#TimeFormat(getsch.GPS_end_time)#',
                                           "pgnotesdraft" = #pgnotesdraft#,
                                           "GPS_start_latitude" = '#GPS_start_latitude#',
                                           "GPS_start_longitude"  ='#GPS_start_longitude#',
                                           "GPS_end_latitude" = '#GPS_end_latitude#',
                                           "GPS_end_longitude"  ='#GPS_end_longitude#',
                                           "Agency_ID" = #arguments.Agency_ID#, "Emp_key" = arguments.Emp_key, "Emp_ID" = arguments.Emp_ID, "success": true
                              } />
                            <cfset arrayAppend(response, obj) />
                        </cfoutput>
                    <cfelse>
                         <cfset obj = { "Schedule_ID" = "", "Patient_ID" = "", "Pt_Agy_ID" = "",
                                        "Pt_First" = "" , "Pt_Middle" = "","Pt_Last" = "",
                                          "Visit_Date" = "","Notes" = "","StartTime" = "",
                                          "EndTime" = "","Skill" = "", "Agency_ID" = #arguments.Agency_ID#, 
                                          "Emp_key" = arguments.Emp_key, 
                                         "Emp_ID" = arguments.Emp_ID,"success": true 
                              } />
                            <cfset arrayAppend(response, obj) />
                    </cfif>
            <cfelse>
                 <cfset obj = { "success": false, "message": "Invalid username or password" 
                      } />
                <cfset arrayAppend(response, obj) />
             </cfif> 
            <cfreturn #serializeJSON(response)#>              
    </cffunction>


</cfcomponent>
