<cfcomponent displayname="Fax Functions" hint="I Return Fax Information" output="false">
	<cfparam name="client.Loc_ID" default = "0">
   <cffunction name="init" displayname="Initialize Component" access="public" returntype="Fax" hint="I initialize and return the Fax object.">
		<cfreturn this>
	</cffunction>
    
   	<cffunction name="send_fax"  returntype="any" access="public" output="false" >
	    <cfargument name="fax_number" required="yes" hint="fax_number">	    
	    <cfargument name="filename" required="yes" hint="filename">	 
	    <cfargument name="coverpage" required="yes" hint="coverpage">	
	    <cfset return_message = "failure">	
	    <cfscript>
		    // Configuration variables (replace with actual values or use environment variables)
		    rcServerUrl = "https://platform.ringcentral.com"; // or sandbox URL: https://platform.devtest.ringcentral.com
		    clientId = "9xFJiZjs9OadyVZU6hJuUT";
		    clientSecret = "9mtfvdcTU0HcWzcPDv9lNCA89E19RDznlcHPy3wEys7L";
		    jwtToken = "eyJraWQiOiI4NzYyZjU5OGQwNTk0NGRiODZiZjVjYTk3ODA0NzYwOCIsInR5cCI6IkpXVCIsImFsZyI6IlJTMjU2In0.eyJhdWQiOiJodHRwczovL3BsYXRmb3JtLnJpbmdjZW50cmFsLmNvbS9yZXN0YXBpL29hdXRoL3Rva2VuIiwic3ViIjoiMzIzNzgwMTAxNSIsImlzcyI6Imh0dHBzOi8vcGxhdGZvcm0ucmluZ2NlbnRyYWwuY29tIiwiZXhwIjozODkzMDY0OTE4LCJpYXQiOjE3NDU1ODEyNzEsImp0aSI6Imh4bEltSERnVE1xWTJoNmFqOVNzNHcifQ.dPhhHIboyGGvxXNjTOpbRrMtWS50Rs3o8HBS28oSMdjGlJZN59Iw5uZcfF4IMhGvPGszDFtI7RXdIfDnkMgDxFKPXOuBvo_x9Pi5oLM1FFKW9v3vHT9fgUuE3DOp9NQB1mKM8woTuTorTf6Ey8ersZtFpGQ1hb9DdFiWhyzDdr3p86hPrR0bd9A76ckRhsJJNoFzIiW6ButFKw-8kPNUYQWZPudta1lAodI6XcRSzvgr2cav-KinvEvxoNOBoUCfiq7yLr7q1Yd_FhCCHSrnwaRfCpmmZe8DyUzLyXGXtQY_qVne9uIm-s4qJ9Ls1fU01CKlRq73QNfnYWpfln8FQg"; // JWT used for login
		    accountId = "3237801015";
		    extensionId = "3237801015";
		</cfscript>
		<cfquery  name='getagency' datasource='#Application.DataSrc#'>
			  	SELECT   * FROM  #Request.prefix_db_lookup#.Agency
 			  	WHERE  Agency_ID = '#session.AgencyId#'
 			  	AND  RingCentral_extensionId IS NOT NULL
 		 </cfquery>		

		<cfif  getagency.recordcount GT 0>
			<cfset accountId = getagency.RingCentral_accountId />
			<cfset extensionId = getagency.RingCentral_extensionId />
			<!--- <cfset clientId = getagency.RingCentral_ClientId />
			<cfset clientSecret = getagency.RingCentral_ClientSecret /> --->
			<cfset jwtToken = getagency.RingCentral_JWT /> 
		</cfif> 
		<!--- Step 1: Authenticate using JWT --->
		<cfset loginUrl = rcServerUrl & "/restapi/oauth/token">
		<cfset loginHeaders = {
		    "Authorization" = "Basic " & toBase64(clientId & ":" & clientSecret),
		    "Content-Type" = "application/x-www-form-urlencoded"
		}>
		<cfset loginBody = "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=" & jwtToken>

		<cfhttp url="#loginUrl#" method="post" result="loginResponse">
		    <cfhttpparam type="header" name="Authorization" value="#loginHeaders['Authorization']#">
		    <cfhttpparam type="header" name="Content-Type" value="#loginHeaders['Content-Type']#">
		    <cfhttpparam type="body" value="#loginBody#">
		</cfhttp>

		<cfset accessToken = "">
		<!--- <cfif CGI.REMOTE_ADDR EQ '103.143.7.161' OR CGI.REMOTE_ADDR EQ '157.51.4.55'>
		 <cfdump var="#loginResponse#">
		</cfif>--->
		<cfif loginResponse.statusCode EQ "200 OK">
		    <cfset authData = deserializeJson(loginResponse.fileContent)>
		    <cfset accessToken = authData.access_token>
		<cfelse>
		    <cfoutput>Login failed: #loginResponse.statusCode#</cfoutput>
		    <cflog  file="faxLogerror"  text="Fax Status: #loginResponse.statusCode# - Error when we get accessToken"   type="information">
		    <cfabort>
		</cfif>

		<!--- Step 2: Send Fax --->
		<cfset faxUrl = rcServerUrl & "/restapi/v1.0/account/#accountId#/extension/#extensionId#/fax">
		<cfset faxHeaders = {
		    "Authorization" = "Bearer " & accessToken,
		    "Content-Type" = "multipart/form-data"
		}>

		<cfhttp url="#faxUrl#" method="post" result="faxResponse">
		    <cfhttpparam type="header" name="Authorization" value="#faxHeaders['Authorization']#">
		    <cfhttpparam type="header" name="Content-Type" value="#faxHeaders['Content-Type']#">
		    <cfhttpparam type="header" name="accountId" value="#accountId#">
		    <cfhttpparam type="header" name="extensionId" value="#extensionId#">
		    <!--- Attach file --->
		    <cfhttpparam type="file" name="attachment" file="#arguments.filename#" mimetype="application/pdf">
		    <!--- Fax recipient --->
		    <cfhttpparam type="formfield" name="to" value="#arguments.fax_number#">
			<cfhttpparam type="formfield" name="coverIndex" value="0">
		    <!---<cfhttpparam type="formfield" name="coverPageText" value="#arguments.coverpage#"> --->
		</cfhttp>

		<cfif faxResponse.statusCode EQ "200 OK" OR faxResponse.statusCode EQ "201">
		   	<cfset return_message = "success">
		    <cflog  file="faxLog"  text="Fax Status: #faxResponse.statusCode# - Fax send successfully to #arguments.fax_number# with cover page of - #arguments.coverpage#"   type="information">
		<cfelse>
		    <cflog  file="faxLogerror"  text="Fax Status: #loginResponse.statusCode# - Error when we send fax - #faxResponse.fileContent#"   type="information">
		    <cfdump var="#faxResponse#">
		    <cfabort>
		</cfif>
		<cfreturn return_message>		
	</cffunction>


	<cffunction name="send_fax_old"  returntype="any" access="public" output="false" >
	    <cfargument name="fax_number" required="yes" hint="fax_number">	    
	    <cfargument name="filename" required="yes" hint="filename">	 
	    <cfargument name="coverpage" required="yes" hint="coverpage">

	    	<cfset return_message = "failure">	
	    	<cfset LOCAL.TheReturnedData                    = "">
			<cfset LOCAL.TheValidToken                      = "">
			<cfset LOCAL.returnFaxSendResult                = StructNew()>
			<cfset LOCAL.returnFaxSendResult.ErrorMessage   = "">
			<cfset LOCAL.returnFaxSendResult.ValidFax       = "">
			<cfset LOCAL.returnFaxSendResult.FaxProcessTime = "">
			<cfquery name="Get485_phys" datasource="#Application.DataSrc#">
				SELECT * FROM  #Request.prefix_db_lookup#.pPhysicians
				WHERE Phys_Fax = '#arguments.fax_number#' AND status =0 
			</cfquery>
			<cfif Get485_phys.recordcount gt 0>
				<cfset LOCAL.ToFaxNumber = #Get485_phys.Phys_Fax# />
				<cfset LOCAL.ToName = #Get485_phys.Phys_First# /> 
			<cfelse>
				<cfset LOCAL.ToFaxNumber = #arguments.fax_number# />
				<cfset LOCAL.ToName = #arguments.fax_number# />
			</cfif>

		    <cfquery  name='getTimeZone' datasource='#Application.DataSrc#'>
		   			SELECT *, '' as CODING_WIZARD   FROM #Request.prefix_db_lookup#.Agency 
		   			WHERE Agency_Id =  #session.agencyid#
		    </cfquery>
		    <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 ===================== ---> 
			<cfif LEN(trim(request.oAuthAccessToken.ValidToken)) NEQ 0>
		   	 	<cfset LOCAL.AuthorizationEndpoint = "https://api.securedocex.com/faxes">
			    <cfset binaryData = fileReadBinary(arguments.filename)>
				<cfset request.myPdf = toBase64(binaryData)>
				<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" : "#coverpage#",
				                    "message" : "#coverpage# ",
				                    "retry_options":{
				                         "non_billable":4,
				                         "billable":10,
				                         "human_answer":1
				                     }
				                }
				            }
				        }
				 >
	    	    <!--- Make web service call to the REST service to send 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,'__.___')>
			    <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">
				        	<cfset return_message = "success"> 
				        	<cflog  file="faxLog"  text="Fax Status: #faxResponse.statusCode# - Fax send successfully to #arguments.fax_number# with cover page of - #arguments.coverpage#"   type="information">
			            <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#">
			                <cflog  file="faxLogerror"  text="#LOCAL.returnFaxSendResult.ErrorMessage#"   type="information">
			            </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#">
		            <cflog  file="faxLogerror"  text="#LOCAL.returnFaxSendResult.ErrorMessage#"   type="information">
			    </cfif>	 
	    	</cfif>
			<cfreturn return_message>		
	</cffunction>
</cfcomponent>