
		<cfquery  name='getagency' datasource='#Application.DataSrc#'>
			  	SELECT   * FROM  #Request.prefix_db_lookup#.Agency
 			  	WHERE   RingCentral_extensionId IS NOT NULL
 			  	AND status = 'active'  
				AND Agency_ID NOT IN (1185,1189)
 		 </cfquery>		

 		<cfloop query="getagency">
 		 <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>
		<cfset accountId = #RingCentral_accountId# />
		<cfset extensionId = #RingCentral_extensionId# />
		<cfset jwtToken = #RingCentral_JWT# /> 

		<!--- 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 = "">
		<!--- <cfdump var="#getagency.Agency_ID#">
		<cfdump var="#loginResponse#"> --->
		<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: Receiving Fax --->
		<cfset baseUrl  = rcServerUrl & "/restapi/v1.0/account/#accountId#/extension/#extensionId#/message-store">
		<cfset faxHeaders = {
		    "Authorization" = "Bearer " & accessToken 
 		}>
 		<cfset dateFrom = dateAdd("d", -2, now())>
		<cfset isoDateFrom = dateFormat(dateFrom, "yyyy-mm-dd") & "T00:00:00.000Z">
 		<cfset queryParams = "direction=Inbound&dateFrom="& #isoDateFrom# >
 		<cfset faxlistURL = "#baseUrl#?#queryParams#">


		<cfhttp url="#faxlistURL#" method="get" result="faxResponse">
		    <cfhttpparam type="header" name="Authorization" value="#faxHeaders['Authorization']#">
		    <cfhttpparam type="header" name="accountId" value="#accountId#">
		    <cfhttpparam type="header" name="extensionId" value="#extensionId#">
		</cfhttp>
		
		<cfif faxResponse.statusCode EQ "200 OK" OR faxResponse.statusCode EQ "201">
		   	<cfset return_message = "success">
		   	<cfset receivedfaxlist = deserializeJSON(faxResponse.Filecontent) />		   
		    <cfset records = receivedfaxlist.records > 		   
 		    <cfloop from= "1" to="#arraylen(records)#" index="i">
		    	<!--- <cfdump var="#receivedfaxlist.records[i]#">--->
		    	<cfset from_fax =  "0">
		    	<cfset from_location =  "">
		    	<cfset coverPageText =  "">
		    	<cfset creationTime =  "">
		    	<cfset formattedDate =  #now()#>
		    	<cfset fax_id = records[i].attachments[1].id >
		    	<cfset fax_content_url = records[i].attachments[1].uri >
		    	<cfset fax_content_type = records[i].attachments[1].contentType >
		    	<cfif  structKeyExists(records[i], "coverPageText")> 
 		    		<cfset coverPageText = records[i].coverPageText  >
 		    	</cfif>
		    	<cfif  structKeyExists(records[i], "from")  AND structKeyExists(records[i].from, "location")> 
 		    		<cfset from_fax =  records[i].from['phoneNumber'] >
 		    	</cfif>
 		    	<cfif  structKeyExists(records[i], "from")  AND structKeyExists(records[i].from, "location")> 
		    		<cfset from_location =  records[i].from['location'] >
		    	</cfif>
		    	<cfif  structKeyExists(records[i], "creationTime")> 
		    		<cfset creationTime = records[i].creationTime  >
		    	</cfif>

		    	 <!--- <cfoutput>
		    		fax_id = #fax_id#  fax_content_url  = #fax_content_url# 
		    		from_fax  = #from_fax# from_location  = #from_location#<br>
		    	</cfoutput> ---> 
		    	 <cfquery name="getexistingfax" datasource="#Application.DataSrc#">
	                    SELECT * FROM #Request.prefix_db_lookup#.Received_faxes 
	                    WHERE fax_id = "#fax_id#"
	                    AND status  < 2
	                    AND fax_content_url  = '#fax_content_url#'
	                    AND file_name IS NOT NULL
						AND fax_id != '2439511825015'
	            </cfquery>
	           
	            <cfif getexistingfax.recordcount EQ 0 >
	            	<!--- Step 3: Getting specific Fax  --->
			    	<cfhttp url="#fax_content_url#" method="get" result="filefaxresponse">
					    <cfhttpparam type="header" name="Authorization" value="#faxHeaders['Authorization']#">
					    <cfhttpparam type="header" name="accountId" value="#accountId#">
					    <cfhttpparam type="header" name="extensionId" value="#extensionId#">
					    <cfhttpparam type="formfield" name="messageId" value="#fax_id#">
					</cfhttp>
					<cfif filefaxresponse.Statuscode EQ '200 OK'>
						<cfset baos =  "#filefaxresponse.Filecontent#">
						<cfset byteArray = baos.toByteArray() />				
	 	           		<cfset original_filename = "fax_" & dateFormat(now(), "yyyymmdd") & "_" & timeFormat(now(), "HHmmssL") & ".pdf">
		           		<cfset path = 'Received_faxes'/>
		           		 <cfif creationTime NEQ ''>
			            	<cfset formattedDate = replace(creationTime, "T", " ", "one")>
							<cfset formattedDate = reReplace(formattedDate, "\.000Z$", "", "one")>
			            </cfif>
						  <cfif getexistingfax.recordcount EQ 0 >
							<cfquery name="insert_receiving" datasource="#Application.DataSrc#" result="insertResult">
									INSERT INTO #Request.prefix_db_lookup#.Received_faxes
									(status, fax_id,Agency_ID, image_downloaded, fax_status, completed_timestamp, originating_fax_number,
										originating_fax_tsid, file_name, coverPageText, fax_content_url,fax_content_type, 
										<cfif creationTime NEQ ''> Fax_received_date,</cfif> 
										Change_by, Date_Change)
									VALUES
									( 0, '#fax_id#', #getagency.Agency_ID#,'YES', 'STORED', #now()#,'#from_fax#', '#from_fax#', 
									'#original_filename#','#coverPageText#','#fax_content_url#','#fax_content_type#',
									<cfif creationTime NEQ ''> '#formattedDate#',</cfif> 
									2,#now()#)
							</cfquery>
			            	<cfset insertedId = insertResult.generatedKey />
							<cffile action="write"  file="s3://#Request.bucket_accesskey#:#Request.bucket_secretkey#@#Request.bucket_name#/#path#/#original_filename#" output="#byteArray#">
		            	<!--- Call API to extract agency_id and order_id from PDF --->
		            	<cfhttp 
		            	    url="https://int-faxapi.myhomecarebiz.com/extract-ids/" 
		            	    method="POST" 
		            	    timeout="600"
		            	    result="extractResponse">
		            	    <cfhttpparam name="file" type="file" file="s3://#Request.bucket_accesskey#:#Request.bucket_secretkey#@#Request.bucket_name#/#path#/#original_filename#">
		            	</cfhttp>
		            	 <cfdump var="#extractResponse#">  
		            	<cfif extractResponse.statusCode EQ "200 OK">
		            	    <cfset extractData = deserializeJSON(extractResponse.fileContent) />
		            	    <cfif structKeyExists(extractData, "agency_id") AND structKeyExists(extractData, "order_id")>
		            	        <cfset agency_id = extractData.agency_id />
		            	        <cfset order_id = extractData.order_id />
		            	        <!--- Only call cron_fax_update when both IDs are valid integers (API returns "Not Found" when absent) --->
		            	        <cfif isNumeric(agency_id) AND isNumeric(order_id) AND val(agency_id) GT 0 AND val(order_id) GT 0>
		            	            <cfset queriesObj = CreateObject("component", "components.queries") />
		            	            <cfset updateResult = queriesObj.cron_fax_update(agency_id, order_id, insertedId) />
		            	            <cflog file="faxLog" text="Fax ID: #fax_id# - Extracted agency_id: #agency_id#, order_id: #order_id#" type="information">
		            	        <cfelse>
		            	            <cflog file="faxLogerror" text="Fax ID: #fax_id# - Skipped update: invalid agency_id (#agency_id#) or order_id (#order_id#) from extract API" type="information">
		            	        </cfif>
		            	    </cfif>
		            	<cfelse>
		            	    <!--- Ignore 502 (Bad Gateway) - skip error log and notification --->
		            	    <cfif FindNoCase("502", extractResponse.statusCode) EQ 0>
		            	        <cflog file="faxLogerror" text="Fax ID: #fax_id# - API extraction failed: #extractResponse.statusCode#" type="information">
		            	        <!--- Send error notification email for API failure --->
		            	        <cftry>
		            	            <cfmail to="velmurugan@myhomecarebiz.com" 
		            	                    from="noreply@myhomecarebiz.com" 
		            	                    subject="OCR API Extraction Failed - Cron Process" 
		            	                    type="html">
		            	                <h3>OCR API Extraction Failed</h3>
		            	                <p><strong>Error Details:</strong></p>
		            	                <ul>
		            	                    <li><strong>Status Code:</strong> #extractResponse.statusCode#</li>
		            	                    <li><strong>Fax ID:</strong> #fax_id#</li>
		            	                    <li><strong>Agency ID:</strong> #getagency.Agency_ID#</li>
		            	                    <li><strong>Agency Name:</strong> #getagency.Agency_Name#</li>
		            	                    <li><strong>Timestamp:</strong> #now()#</li>
		            	                </ul>
		            	                <p><strong>Response Content:</strong></p>
		            	                <pre>#extractResponse.fileContent#</pre>
		            	                <p>Please investigate this API failure and take appropriate action.</p>
		            	            </cfmail>
		            	        <cfcatch>
		            	            <cflog file="faxLogerror" text="Failed to send API error notification email: #CFCATCH.Message#" type="error">
		            	        </cfcatch>
		            	        </cftry>
		            	    </cfif>
		            	</cfif>
						</cfif>
		            	<cflog  file="faxLog"  text="Fax Status: #filefaxresponse.statusCode# - Fax received successfully "   type="information">
		            <cfelse>
		            	<cflog  file="faxLogerror"  text="Fax Status: #filefaxresponse.statusCode# - Error when get file using fax_id - #fax_id#"   type="information">
		            </cfif>
				</cfif>
		    </cfloop> 
		<cfelse>
			failure -<cfdump var="#faxResponse#">	
		    <cflog  file="faxLogerror"  text="Fax Status: #getagency.Agency_Name# - #loginResponse.statusCode# - Error when we send fax - #faxResponse.fileContent#"   type="information">
		</cfif>
	</cfloop>