<!--- send_fax.cfm --->
<cfparam name="url.redirect" default="">
<cfparam name="FORM.Emp_ID" default="">
<cfparam name="form.faxmemo" default="">
<cfif isDefined('form.Event_ID')>
	<cfset url.Event_ID =  form.Event_ID />	
	<cfset url.ID = form.Event_ID />
</cfif>

<cfquery name="Get_phys" datasource="#Application.DataSrc#">
		SELECT * FROM  #Request.prefix_db_lookup#.pPhysicians
		WHERE Emp_ID = '#FORM.Emp_ID#' AND status =0 
</cfquery>
<cfquery  name="GetEvent" datasource="#Application.DataSrc#">
		SELECT 
		    Event.Event_ID, 
		    Event.EventSub_ID, 
		    Event.Patient_ID, 
		    Event.Employee_ID,
		    Event.who_observed,
		    Event.MD_notified,
		    Event.injury, 
		    Event.Event_Date, 
		    Event.Memo, 
		    Event.Resolved, 
		    Event.Record_Created_By,
		    Event.Followup_Desc, 
		    Event.Followup_Memo, 
		    pEmployee.Emp_ID, 
		    pEmployee.Emp_Last, 
		    pEmployee.Emp_First, 
		    EventSubjects.EventSub_ID, 
		    EventSubjects.Subject, 
		    pPatients.Patient_ID,
		    pPatients.Pt_Last,
		    pPatients.Pt_First, 
		    pPhysicians.Phys_ID, 
		    e1.Emp_Last AS LastName, 
		    e1.Emp_First AS FirstName, 
		    e1.Emp_Street1, 
		    e1.Emp_City, 
		    e1.Emp_State, 
		    e1.Emp_Zip, 
		    e1.Emp_Telephone AS Telephone1, 
		    Agency.Agency_ID, 
		    Agency.Agency_Name, 
		    Agency.Agency_Contact_Phone
		FROM 
		    #Request.prefix_db_agency#.Event
		JOIN 
		    #Request.prefix_db_lookup#.pEmployee ON Event.Employee_ID = pEmployee.Emp_ID  
		JOIN 
		    #Request.prefix_db_agency#.pPatients ON Event.Patient_ID = pPatients.Patient_ID AND pPatients.Status IN (0,1,4)
		JOIN 
		    #Request.prefix_db_agency#.EventSubjects ON Event.EventSub_ID = EventSubjects.EventSub_ID
		JOIN 
		    #Request.prefix_db_lookup#.Agency ON Event.Agency_ID = Agency.Agency_ID
		JOIN 
		    #Request.prefix_db_lookup#.pPhysicians ON pPhysicians.Phys_ID = (SELECT Render_Phys_ID FROM #Request.prefix_db_agency#.pAdmit WHERE Patient_ID = pPatients.Patient_ID AND status = 0)
		LEFT JOIN 
		    #Request.prefix_db_lookup#.pEmployee e1 ON pPhysicians.Emp_ID = e1.Emp_ID
		WHERE 
		    Event.Event_ID = #url.ID#
		    AND Event.Agency_ID = #session.AgencyID#
		ORDER BY 
		    Event.Event_Date DESC;
</cfquery>


<cfif form.faxmemo EQ '' >
	<cfset fax_covermessage =  'Incidences Fax' />
<cfelse>
	<cfset fax_covermessage =  #form.faxmemo# />
</cfif>

<cfif Get_phys.Phys_Fax NEQ '' OR FORM.Emp_ID EQ 'other'>
	<!--- Set the function & Fax Service Response Parameters --->
	<cfset path = 'Mediprocity/agency_'&#session.AgencyId#&'/'& #url.Event_ID# & '.pdf'  />
	<cfset LOCAL.TheReturnedData                    = "">
	<cfset LOCAL.TheValidToken                      = "">
	<cfset LOCAL.returnFaxSendResult                = StructNew()>
	<cfset LOCAL.returnFaxSendResult.ErrorMessage   = "">
	<cfset LOCAL.returnFaxSendResult.ValidFax       = "">
	<cfset LOCAL.returnFaxSendResult.FaxProcessTime = "">
	
	<!--- Set variables for fax cover template --->
	<cfset LOCAL.subject = "Request Incidences ordersign for #GetEvent.Pt_First#, #GetEvent.Pt_Last#" />
	<cfset LOCAL.Heading = fax_covermessage />
	<cfset LOCAL.ToName = "" />
	
	<cfif FORM.Emp_ID EQ 'other'>
		<cfset LOCAL.ToFaxNumber =   #FORM.otherfaxnumber# />
		<cfset LOCAL.ToName =  #FORM.otherfaxnumber# /> 
	<cfelse>		
		<cfset LOCAL.ToFaxNumber = #Get_phys.Phys_Fax# />
		<cfset LOCAL.ToName = #Get_phys.Phys_First# /> 
		<!--- Set physician details for fax cover --->
		<cfset LOCAL.Physician_First_Name = Get_phys.Phys_First />
		<cfset LOCAL.Physician_Last_Name = Get_phys.Phys_Last />
		<cfset LOCAL.Physician_Credentials = Get_phys.Phys_Credentials />
	</cfif>
	
	<!--- Get agency information for fax cover --->
	<cfquery name="formagency" datasource="#Application.DataSrc#">
		SELECT Agency_Name, Agency_Address1, Agency_City, Agency_State, Agency_Zip, 
		       Agency_Contact_Phone, Agency_Fax
		FROM #Request.prefix_db_lookup#.Agency 
		WHERE Agency_ID = #session.AgencyID#
	</cfquery>
	
	<!--- Check if logo exists --->
	<cfset Request.logo_exists = false />
	<cfset Request.logo_path = "" />
	<cfif FileExists("#Application.DataPath#agency_#session.AgencyID#_logo.png")>
		<cfset Request.logo_exists = true />
		<cfset Request.logo_path = "#Application.DataPath#agency_#session.AgencyID#_logo.png" />
	</cfif>

	<cfif len(getTimeZone.FAX_APINumber) gt 0 AND len(getTimeZone.FAX_userid) gt 0>
		<cfset LOCAL.FromFaxNumber = #getTimeZone.FAX_APINumber# />
		<cfset LOCAL.user_ID = #getTimeZone.FAX_userid# />
		<cfset LOCAL.FAX_ClientID = #getTimeZone.FAX_ClientID# />
		<cfset LOCAL.FAX_ClientSecret = #getTimeZone.FAX_ClientSecret# />
	<cfelse>
		<cfset LOCAL.FromFaxNumber = "12074820034" />
		<cfset LOCAL.user_ID = "920bd222-3c5e-4976-b768-e42e69c18281" />
		<cfset LOCAL.FAX_ClientID = "e53f4e48-4995-43b3-b3e0-d4ef2d9247ae" />
		<cfset LOCAL.FAX_ClientSecret =  "rPCENt3yMs3zNV/B" />
	</cfif>

	<cfset request.oAuthAccessToken = CreateObject("component","components.general.oAuth").GetAccessToken(
	                OauthServerCallTimeOuts = '5',
	                TheClientID             =  #LOCAL.FAX_ClientID#,
	                TheClientSecret         =  #LOCAL.FAX_ClientSecret#,
	                OauthTokenEndpoint      = 'https://api.securedocex.com/tokens',
	                OauthGrantType          =  'client_credentials') >
	 
	<!--- ERROR: capture any oAuth service errors --->
	<cfif LEN(trim(request.oAuthAccessToken.ErrorMessage)) NEQ 0>
	    <cfset LOCAL.returnFaxSendResult.ErrorMessage = request.oAuthAccessToken.ErrorMessage>
	</cfif>
	<!--- ====================== END: CAPTURING OAUTH SERVICE CALL ===================== ---> 
	        
	<!--- ====================== BEGIN: Fax SERVICE CALL ===================== ---> 
	<!--- if valid access token exists, make Fax service call --->
	<cfif LEN(trim(request.oAuthAccessToken.ValidToken)) NEQ 0>
		<cfset LOCAL.AuthorizationEndpoint = "https://api.securedocex.com/faxes">
		<cfset CrLf = Chr(13) & Chr(10) />
		<!--- Incidence PDF creation with fax cover --->
		<cfset Request.print = "no">
		<cfdocument format="pdf" name="gettingfile" orientation = "portrait" overwrite = "yes">
			<!--- Include the fax cover template --->
			<cfinclude template="../patientadmin_new/patient/fax_cover_template.cfm">
			
			<!--- Add the incidence details below the cover page --->
			<cfinclude template ="event_form_printer.cfm">
		</cfdocument>
		<!--- Incidence PDF creation End --->
 		<cfscript>
	        request.myPdf = toBase64( gettingfile );
	    </cfscript>

	    <cfset Request.stFields = 
	       {        
	            "destinations": [
	                {
	                    "fax_number" : "#LOCAL.ToFaxNumber#",
	                    "to_name" : "#LOCAL.ToName#",
	                    "to_company": "#session.agencyname#"
	                }
	            ],
	            "documents": [
	                {
	                    "document_content": "#request.myPdf#",
	                    "document_type": "PDF"
	                }
	            ],
	            
	           "fax_options" : 
	           {
	                        "image_resolution" : "FINE",
	                        "include_cover_page" : "true",
	                        "custom_CallerID" : "18189785900",
	                        "header_options": {
	                        "line_1":["${CSID}", "${DATE_TIME2}", "${FAX_ID}", "Page: ${CURRENT_PAGE} / ${TOTAL_PAGE}"]
	                    },
	                "custom_CSID" : "MyHomeCareBiz",
	                "cover_page_options" : 
	                {
	                    "from_name" : "#session.display#",
	                    "subject" : "Request Incidences ordersign for #GetEvent.Pt_First#, #GetEvent.Pt_Last#",
	                    "message" : "#fax_covermessage# ",
	                    "retry_options":{
	                         "non_billable":4,
	                         "billable":10,
	                         "human_answer":1
	                     }
	                }
	            }
	        }
	    >

		<!--- Make web service call to the REST service to retrieve the Fax --->
	    <cfset LOCAL.RestStartTime  = GetTickCount()>
	    <cfhttp 
	        url         = #LOCAL.AuthorizationEndpoint#
	        method      = "POST" 
	        timeout     =  "10"
	        result      = "httpFaxResponse">
	        <cfhttpparam name="Content-Type"  type="HEADER" value="application/pdf">
	        <cfhttpparam name="Authorization" type="HEADER" value="#request.oAuthAccessToken.ValidToken#">
	        <cfhttpparam name="user-id" type="HEADER" value="#LOCAL.user_ID#">
	        <cfhttpparam type="body" value="#serializeJSON(Request.stFields)#">
	        <!--- <cfhttpparam type="formfield" name="documents" value="#serializeJSON(documents)#">
	        <cfhttpparam type="formfield" name="destinations" value="#serializeJSON(destinations)#"> --->
	    </cfhttp>
		<cfset LOCAL.RestEndTime = GetTickCount()>
	    <cfset LOCAL.returnFaxSendResult.FaxProcessTime = NumberFormat((LOCAL.RestEndTime - LOCAL.RestStartTime)/1000,'__.___')>
	     <!--- <cfdump var="#httpFaxResponse#"><cfabort> --->
	    <cfif httpFaxResponse.responseHeader.Status_Code eq 201>             
	        <cftry>
	            <!--- set the FAX into the return struct --->
	            <cfset LOCAL.Faxresponse ="#deserializeJSON(httpFaxResponse.Filecontent)#" />
	            <cfset LOCAL.returnFaxSendResult.fax_id = LOCAL.Faxresponse[1].fax_id>
	            <cfset LOCAL.returnFaxSendResult.destination_fax_number = LOCAL.Faxresponse[1].destination_fax_number>
	            <cfset LOCAL.returnFaxSendResult.ValidFax       = "Yes">
	            <cfoutput>
	                   <!---  Fax sent sucessfully  --->
	                   <cfquery name="GetV" datasource="#Application.DataSrc#">
	                   		UPDATE #Request.prefix_db_agency#.Event_to 
	                   		 SET   Date_Sent = #now()#
							WHERE Event_ID = '#url.Event_ID#'
						</cfquery>
	                   <cfif url.redirect eq 'unsentorders'>
	                   		<cflocation url="/dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders&message=Successfully send Fax to #LOCAL.ToName#" addtoken="no">
	                    <cfelse>
	                   		<cflocation url="/dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders&message=Successfully send Fax to #LOCAL.ToName#" addtoken="no">
	                    </cfif>
	            </cfoutput>
	            <cfcatch>
	            	<cfparam name="CFCATCH.Message" default="">
	                <cfset LOCAL.returnFaxSendResult.ValidFax       = "No">
	                <!--- ERROR: add general CFCATCH error to error log statement --->
	                <cfset LOCAL.returnFaxSendResult.ErrorMessage = LOCAL.returnFaxSendResult.ErrorMessage & "FAX SEND SERVICE: Error when we get response |CFCATCH MESSAGE: #CFCATCH.Message#|CFCATCH DETAIL: #CFCATCH.Detail#|CFC | Fax Number #LOCAL.ToFaxNumber# | Return code: #httpFaxResponse.responseHeader.Status_Code#">
	                <cfif url.redirect eq 'unsentorders'>
	                	<cflocation url="/dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders&message=failure due to FAX send API error" addtoken="no">
	                <cfelse>
	                	<cflocation url="/dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders&message=failure due to FAX send API error" addtoken="no">
	                </cfif>
	            </cfcatch>
	        </cftry>                
	    <cfelse>
            <!--- ERROR: add failed FAX service call to error log statement --->
            <cfparam name="CFCATCH.Message" default="">
             <cfparam name="CFCATCH.Detail" default="">
            <cfset LOCAL.returnFaxSendResult.ValidFax       = "No">
            <cfset LOCAL.returnFaxSendResult.ErrorMessage = LOCAL.returnFaxSendResult.ErrorMessage & "FAX SEND SERVICE: Error when we send fax to the customer |CFCATCH MESSAGE: #CFCATCH.Message#|CFCATCH DETAIL: #CFCATCH.Detail#|CFC | Fax Number: #LOCAL.ToFaxNumber#  | Return code: #httpFaxResponse.responseHeader.Status_Code#">
            <cfif url.redirect eq 'unsentorders'>
	            <cflocation url="/dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders&message=failure due to FAX send API error" addtoken="no">
	        <cfelse>
            	<cflocation url="/dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders&message=failure due to FAX send API error" addtoken="no">
            </cfif>
	    </cfif>	 
	</cfif>
<cfelse>
		<cfif url.redirect eq 'unsentorders'>
	        <cflocation url="/dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders&message=Failure due to physician Fax number is unavailable" addtoken="no">
	    <cfelse>
			<cflocation url="/dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders&message=Failure due to physician Fax number is unavailable" addtoken="no">
		</cfif>
</cfif>