<cfparam name="url.SID" default="0">
<cfset Request.username = "2n9xzzfv">
<cfset Request.password = "@$48jnh6{0}G">
<cfif URL.SID NEQ 0 >
   <cfset URL.SID   = decrypt(#URL.SID#,#application.enckey#,"AES","Hex") />
</cfif>
<!--- Combine username and password with colon and encode in Base64 --->
<cfset authString = toBase64(Request.username & ":" & Request.password)>
<cfset LOCAL.account  = '215035'>
<cfset LOCAL.AuthorizationEndpoint = "https://uat-api.sandata.com/interfaces/intake/visits/rest/api/v1.1">
<cfset application.ProviderID = '2279160425' >

<cfquery name="getemployee" datasource="#Application.DataSrc#">
	SELECT * FROM  #Request.prefix_db_lookup#.pEmployee
	WHERE Emp_ID = '#session.employeeid#'  
</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,
	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.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.StartTime,pSchedules.EndTime,pSchedules.Date_Create AS CallDateTime_old,
	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="#url.SID#" 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()> <!--- Get current date and time --->
<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 = DateFormat(Previous_Day, "yyyy-mm-dd") & "T" & GtSched.StartTime  & "Z">
<cfset Adjust_End_Time = DateFormat(Previous_Day, "yyyy-mm-dd") & "T" & GtSched.EndTime  & "Z">
<cfset Total_Hours = 0 >
<cfif GtSched.Total_Units gt 0 >
    <cfset Total_Hours = (#GtSched.Total_Units#)*(25/100)>
</cfif>



		<cfset Request.stFields = 
    [{
        "ProviderIdentification": {
            "ProviderID": "#application.ProviderID#",
            "ProviderQualifier": "MedicaidID"
        },
        "VisitOtherID": "93776",
        "SequenceID": "#GtSched.Emp_ID#",
        "EmployeeQualifier": "EmployeeCustomID",
        "EmployeeCustomID": "#GtSched.Loc_ID#",
        "EmployeeOtherID": "#GtSched.EmployeeIdentifier#",
        "EmployeeIdentifier": "#GtSched.EmployeeIdentifier#",
        "GroupCode": "",
        "ClientIDQualifier": "ClientMedicaidID",
        "ClientID": "111111111",
        "ClientOtherID": "111111111",
        "VisitCancelledIndicator": false,
        "PayerID": "COHCPF",
        "PayerProgram": "HCPF",
        "ProcedureCode": "BHSVC",
        "Modifier1": "", 
        "Modifier2": "",
        "Modifier3": "", 
        "Modifier4": "",
        "VisitTimeZone": "US/Mountain",
        "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": "123456789", 
            "CallDateTime": "#GtSched.CallDateTime#",
            "CallAssignment": "Time In",
            "GroupCode": "",
            "CallType": "Other",
            "ProcedureCode": "BHSVC", 
            "ClientIdentifierOnCall": "111111111",
            "MobileLogin": "",
            "CallLatitude": "#GtSched.Sch_Latitude#",
            "CallLongitude": "#GtSched.Sch_Longitude#",
            "Location": "123",
            "TelephonyPIN": 999999999,
            "OriginatingPhoneNumber": "9997779999"
        }],
        "VisitExceptionAcknowledgement": [{
            "ExceptionID": "15",
            "ExceptionAcknowledged": false
        }],
        "VisitChanges": [{
            "SequenceID": "110",
            "ChangeMadeBy": "#GtSched.Emp_Email#",
            "ChangeDateTime": "#formattedDateTime#",
            "GroupCode": "",
            "ReasonCode": "11",
            "ChangeReasonMemo": "EVV Visit Start",
            "ResolutionCode": "A"
        }],
        "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     =  "10"
	        result      = "httpEVVResponse">
	        <cfhttpparam name="Content-Type"  type="HEADER" value="application/json">
	        <cfhttpparam name="Authorization" type="HEADER" value="Basic #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,'__.___')>
	    <cfdump var="#httpEVVResponse#"><cfabort> 
	    <cfif httpEVVResponse.responseHeader.Status_Code eq 201>  
	    	<!---  <cfdump var="#httpEVVResponse#"> --->
	    </cfif>