<cfdump var="#FORM#">

<!--- send_fax.cfm --->
<cfparam name="form.redirect" default="communicationlog">
<cfparam name="form.faxmemo" default="">

<cfif form.redirect EQ 'unsentorders'>
	<cfset redirect_url= "../dashboard/index.cfm?page=dashboard&cat&rpt=unsent_orders" />
<cfelse>
	<cfset redirect_url= "../agencyadmin/index.cfm?page=agency&rpt=communication_log" />
</cfif>

<cfif form.faxmemo EQ '' >
	<cfset fax_covermessage =  "Communication sent" />
<cfelse>
	<cfset fax_covermessage =  #form.faxmemo# />
</cfif>


<cfparam name="Get485phy.Phys_Fax" default="">

<cfif FORM.Emp_ID NEQ 'other'>
	<cfquery name="Get485phy" datasource="#Application.DataSrc#">
		SELECT * FROM  #Request.prefix_db_lookup#.pPhysicians
		WHERE Emp_ID IN (#FORM.Emp_ID#) AND status =0 
	</cfquery>
</cfif>
<!--- Page specific code, such as queries and variable settings should go here --->
<cfquery  name="GetComm" datasource="#Application.DataSrc#">
     SELECT c.Comm_Id, c.CommSub_Id, c.Patient_Id, c.Employee_Id
       ,c.Comm_Date, c.Memo, c.Resolved, c.Record_Created_By
       ,c.Followup_Desc, c.Followup_Memo
       ,cs.CommSub_Id, cs.Subject
       ,e.Emp_Id, e.Emp_Last AS Last_Name, e.Emp_First AS First_Name
       ,a.Agency_Id, a.Agency_Name, a.Agency_Contact_Phone
      FROM  #Request.prefix_db_agency#.Communication c 
      JOIN #Request.prefix_db_agency#.CommunicationSubjects cs ON  cs.CommSub_Id = c.CommSub_Id
      JOIN #Request.prefix_db_lookup#.Agency a ON a.Agency_Id = c.Agency_Id
      LEFT OUTER JOIN #Request.prefix_db_lookup#.pEmployee e ON  e.Emp_Id = c.Employee_Id
      WHERE c.Comm_Id = '#FORM.comm_id#' 
      AND   c.Agency_Id = '#session.AgencyId#'
</cfquery>

<cfquery  name="GetPatient" datasource="#Application.DataSrc#">
    SELECT p.Patient_ID, p.Pt_Last AS Last_Name_M0040, p.Pt_First AS First_Name_M0040, p.Pt_DOB  
    FROM #Request.prefix_db_agency#.pPatients p
    WHERE  p.Patient_Id = '#GetComm.Patient_Id#'
</cfquery>

<cfquery  name="GetDoc" datasource="#Application.DataSrc#">
	 SELECT py.Phys_ID
	       ,e.Emp_Last AS DocLName, e.Emp_First AS DocFName
	       ,e.Emp_Street1 AS Address1, e.Emp_City AS City, e.Emp_State AS State, e.Emp_Zip AS Zip, e.Emp_Telephone as phone
	 FROM   #Request.prefix_db_lookup#.pPhysicians py, #Request.prefix_db_lookup#.pEmployee e
	 WHERE  py.Emp_ID = '#GetComm.Employee_Id#'
	 AND    e.Emp_ID = py.Emp_ID
</cfquery>

<cfquery  name="GetI" datasource="#Application.DataSrc#">
	 SELECT Emp_First AS FIRST, Emp_Last AS LAST 
	 FROM #Request.prefix_db_lookup#.pEmployee
	 WHERE  Emp_ID = '#GetComm.Record_Created_By#'
	 AND    Emp_Type != 'Physician'
</cfquery>


<cfif Get485phy.Phys_Fax NEQ '' OR FORM.Emp_ID EQ 'other'>
		
		
		<cfset LOCAL.subject = "Sending Communication files for patient #GetPatient.First_Name_M0040#, #GetPatient.Last_Name_M0040#" />
		<cfset LOCAL.Heading = "Communication sent" />
		<cfset LOCAL.FileType = "application/pdf" />
		<cfdocument format="pdf" name="gettingfile" orientation = "portrait" overwrite = "yes"  >
			<cfoutput>
			 <div id="printreport"  style="font-size:14px;">
			  <b>#getComm.Agency_Name# memo...</b>
			   <br><br>
			  <table style='font-size:14px;' cellspacing='2' cellpadding='2'>
			   <tr>
			     <td>&nbsp;</td>
			     <td>&nbsp;</td>
			   </tr>
			   <cfif getPatient.RecordCount gt 0>
				 <tr>
				  <td><b>Patient:</b></td>
					<td>#getPatient.First_Name_M0040# #getPatient.Last_Name_M0040#<br>DOB: #DateFormat(getPatient.Pt_DOB,"mm/dd/yyyy")#</td>
				 </tr>
			   <tr>
			     <td>&nbsp;</td>
			     <td>&nbsp;</td>
			   </tr>
			   </cfif>
				 <tr>
					<td valign='top'><b>Subject:</b></td>
					<td>#GetComm.Subject#</td>
				 </tr>
			   <tr>
			     <td>&nbsp;</td>
			     <td>&nbsp;</td>
			   </tr>
				 <tr>
					<td valign='top' nowrap='nowrap'><b>Submitted By:</b>&nbsp;</td>
					<td>#GetI.FIRST# #GetI.LAST#</td>
				 </tr>
			   <tr>
			     <td>&nbsp;</td>
			     <td>&nbsp;</td>
			   </tr>
			   <tr>
			    <td valign='top'><b>Date:</b></td>
			    <td>#DateFormat(GetComm.Comm_Date,"mm/dd/yyyy")#</td>
			   </tr>
				 <cfif GetDoc.Phys_ID gt 0>
			   <tr>
			     <td>&nbsp;</td>
			     <td>&nbsp;</td>
			   </tr>
			   <tr>
			    <td valign='top'><b>Physician:</b></td>
			    <td>#GetDoc.DocFName# #GetDoc.DocLName#<br>#GetDoc.Address1#<br>#GetDoc.City#, #GetDoc.State# #GetDoc.Zip#<br>#GetDoc.phone#</td>
			   </tr>
			   </cfif>
			   <tr>
			     <td>&nbsp;</td>
			     <td>&nbsp;</td>
			   </tr>
			   <tr>
			    <td valign='top'><b>Agency Rep:</b></td>
			    <td>#GetComm.First_Name# #GetComm.Last_Name# &nbsp; <b>Rep Phone: </b>#GetComm.Agency_Contact_Phone#</td>
			   </tr>
			   <tr>
			     <td>&nbsp;</td>
			     <td>&nbsp;</td>
			   </tr>
			   <tr>
			     <td valign='top'><b>Memo:</b></td>
			     <td>#GetComm.Memo#</td>
			   </tr>
			   <tr>
			     <td>&nbsp;</td>
			     <td>&nbsp;</td>
			   </tr>
			   <tr>
			     <td valign='top'><b>Follow-up Action:</b></td>
			     <td>#GetComm.Followup_Desc#</td>
			   </tr>
			   <tr>
			     <td>&nbsp;</td>
			     <td>&nbsp;</td>
			   </tr>
			   <tr>
			     <td valign='top'><b>Follow-up Memo:</b></td>
			     <td>#GetComm.Followup_Memo#</td>
			   </tr>
			  </table>
			 </div>
			</cfoutput>
			 <br/>
			<div style="font-size:12px; text-align:right;">This memo is for your records.</div>
		</cfdocument>



	

	<!--- Set the function & Fax Service Response Parameters --->
	<cfset LOCAL.TheReturnedData                    = "">
	<cfset LOCAL.TheValidToken                      = "">
	<cfset LOCAL.returnFaxSendResult                = StructNew()>
	<cfset LOCAL.returnFaxSendResult.ErrorMessage   = "">
	<cfset LOCAL.returnFaxSendResult.ValidFax       = "">
	<cfset LOCAL.returnFaxSendResult.FaxProcessTime = "">
	<!--- <cfset LOCAL.ToFaxNumber = #ValueList(Get485phy.Phys_Fax,",")# />
	<cfset LOCAL.ToName = #ValueList(Get485phy.Phys_First,",")# />  --->
	<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>

	<cfif FORM.Emp_ID EQ 'other'>
		<cfset LOCAL.ToFaxNumber =   #FORM.otherfaxnumber# />
		<cfset LOCAL.ToName =  #FORM.otherfaxnumber# /> 
	<cfelse>
		<cfset LOCAL.ToFaxNumber = #Get485phy.Phys_Fax# />
		<cfset LOCAL.ToName = #Get485phy.Phys_First# /> 
	</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">
 		<cfscript>
	       	   //request.myPdf = fileReadBinary(getfilename);
	      	  // request.myPdf = toBase64( request.myPdf );
	           //request.myPdf = toBinary( request.myPdf );
	           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" : "#LOCAL.subject#",
	                    "message" : "#LOCAL.Heading#",
	                    "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="#LOCAL.FileType#">
	        <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>
	            		<cfquery name="Comm" datasource="#Application.DataSrc#">
			                UPDATE #Request.prefix_db_agency#.Communication 
			                SET  send_fax = 1, 
			                fax_sent_date =  #now()# 
			                WHERE Comm_ID = <cfqueryparam VALUE="#FORM.comm_id#"  cfsqltype="cf_sql_integer" >
			          </cfquery>
	                   <!---  Fax sent sucessfully  --->	        
	                   	<cflocation url="#redirect_url#&message=Successfully send Fax to #LOCAL.ToName#" addtoken="no">
	            </cfoutput>
	            <cfcatch>
	                 <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#">
	                <cflocation url="#redirect_url#&message=failure due to FAX send API error" addtoken="no">
	            </cfcatch>
	        </cftry>                
	    <cfelse>
            <!--- ERROR: add failed FAX service call to error log statement --->
            <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#">
            <cflocation url="#redirect_url#&message=failure due to FAX send API error" addtoken="no">
	    </cfif>	 
	</cfif>
<cfelse>
		<cflocation url="#redirect_url#&message=Failure due to physician Fax number is unavailable" addtoken="no">
</cfif>