<cfset myarray[1] = "empty value"> 
<cfquery name="Agency" datasource="#Application.DataSrc#">
	SELECT agency_id from #Request.prefix_db_lookup#.Agency where status='active' ORDER BY agency_id
</cfquery>
<cfset myarray=arraynew(1)>
<cfloop query="Agency">
    <cfset myarray[CurrentRow]=agency_id>
</cfloop>
<cfset doninsert =  1 >
<cfset session.employeeid  = 0 >
<cfset billingSFTP = createObject("component", "components.billing.billing_sftp") />
<!--- Do not delete eligibility files on stage/dev servers. --->
<cfset isNonProdServer = (
	CGI.SERVER_NAME EQ "127.0.0.1" OR CGI.SERVER_NAME EQ "localhost"
	OR CGI.SERVER_NAME EQ "52.23.186.30" OR CGI.SERVER_NAME EQ "dev.myhomecarebiz.com"
	OR CGI.SERVER_NAME EQ "98.87.35.139" OR CGI.SERVER_NAME EQ "devsecure.myhomecarebiz.com"
	OR CGI.SERVER_NAME EQ "54.175.136.41" OR CGI.SERVER_NAME EQ "stagesecure.myhomecarebiz.com"
) />
<cfloop array="#billingSFTP.getImportConnections()#" index="importConn">
<cfset objFTPProperties = importConn.connection />
<cfftp action="open" connection="objConnection" attributeCollection="#objFTPProperties#" >
<cfftp connection="objConnection" action="listdir" directory="/outgoing/" name="dirlist" stoponerror="Yes"> 
<h3>The current directory is <cfoutput>#dirlist.recordCount#</cfoutput>
 <!--- <cfdump var="#dirlist#" >--->
<cfset name2=ArrayNew(1) />
<cfset reading_filepath = "/var/www/Upload/eligibility/" />

<!--- Ensure the directory exists before downloading files --->
<cftry>
	<!--- Check and create parent directory first --->
	<cfset parentDir = "/var/www/Upload/" />
	<cfif NOT directoryExists(parentDir)>
		<cfdirectory action="create" directory="#parentDir#" mode="775">
	</cfif>
	<!--- Check and create eligibility directory --->
	<cfif NOT directoryExists(reading_filepath)>
		<cfdirectory action="create" directory="#reading_filepath#" mode="775">
	</cfif>
	<cfcatch type="any">
		<!--- Log error if directory creation fails --->
		<cflog file="eligibility_import" type="Error" 
			text="Failed to create directory #reading_filepath#; Error: #cfcatch.Message# #cfcatch.Detail#">
		<!--- Send email notification about directory creation failure --->
		<cftry>
			<cfmail to="velmurugan@myhomecarebiz.com,melissa@myhomecarebiz.com" 
					from="error@myhomecarebiz.com" 
					subject="#Application.ServerName# - Eligibility Import Directory Creation Error" 
					type="html">
				<h3 style="color: red;">Directory Creation Error</h3>
				<p><strong>Error:</strong> Failed to create directory #reading_filepath#</p>
				<p><strong>Error Message:</strong> #cfcatch.Message#</p>
				<p><strong>Error Detail:</strong> #cfcatch.Detail#</p>
				<p><strong>Timestamp:</strong> #DateFormat(Now(), 'mm/dd/yyyy')# #TimeFormat(Now(), 'HH:mm:ss')#</p>
			</cfmail>
			<cfcatch></cfcatch>
		</cftry>
	</cfcatch>
</cftry>
<cfset counts = #dirlist.recordCount# - 1 />
<cfset split_delimiter = "*" >

<!--- Process only recent files (last 3 days) --->
<cfset eligibilityFileCutoffDate = DateAdd("d", -2, Now())>
	<div class="portlet box blue">
				<div class="portlet-title">
					<div class="caption">
						<i class="fa fa-gear"></i>Eligibility Claims
					</div>
					<div class="tools">
						<a class="collapse" href="javascript:;" data-original-title="" title="">
						</a>
					</div>
				</div>
				<div class="portlet-body flip-scroll">
					<table class="table table-bordered table-striped table-condensed flip-content" border="1">
						<thead class="flip-content" >
							<tr>
								<th>Patient</th>
								<th>Pay_ID</th>
								<th>Primary Start</th>
								<th>Pri End</th>
								<th>Part A</th>
								<th>Part B</th>
								<th>Plan Type</th>
								<th>Plan Program</th>
								<th>Policy Number</th>
								<th>Ded Amt</th>
								<th>Dedt In</th>
								<th>Dedt Out</th>
								<th>Deduct Remain</th>
								<th>Deduct Met</th>
								<th>OP Amt</th>
								<th>OP IN</th>
								<th>OP Out</th>
								<th>OP Remaing</th>
								<th>OP Amt</th>
								<th>Copay Amt</th>
								<th>Copay In</th>
								<th>Copay Out</th>
								<th>Coins</th>
								<th>Coins IN</th>
								<th>Coins Out</th>
								<th>Rejection Error</th>
							</tr>
						</thead>
	                    <tbody style="text-align:center;">                         
                      		<cfoutput> 
							    <cfloop from="1" to="#dirlist.recordCount#" index="k">
							     	<cfset filepath = "/Upload/eligibility/" />
									<cfset name2 = #dirlist.name[k]# />
										<cfset processFileByDate = 0>
										<cfset fileYYMMDD = "">
										<cfset remotfiledate = #dirlist.lastmodified[k]#   /> 
 										<cfset fileYYMMDD = #DateFormat (remotfiledate,"yymmdd")#>
										<cfif Len(fileYYMMDD) EQ 6>
											<cfset fileDate = CreateDate("20" & Left(fileYYMMDD,2), Mid(fileYYMMDD,3,2), Right(fileYYMMDD,2))>
											<cfif fileDate GTE eligibilityFileCutoffDate>
												<cfset processFileByDate = 1>
											</cfif>
 										</cfif>
 									<cfset filepath2 = filepath&name2 >
									<cfset valueWithoutElg = Replace(name2, "elg", "", "all")>
									<cfset splitArray = ListToArray(valueWithoutElg, "-")>
									<!--- Extract the first element (which is '1150') --->
									<cfset agency_number = splitArray[1]>
									<cfif NOT billingSFTP.shouldProcessAgencyFile(agency_number, importConn.dedicatedAgencyId)>
										<cfcontinue />
									</cfif>
									<cfset Request.prefix_db_agency = 'agency_'& agency_number>
									<!--- <cfset Request.prefix_db_agency = 'agency_1150'>--->
									<cfif processFileByDate EQ 1 AND (Right(name2,4) eq  '.271' OR Right(name2,4) eq  '.277' OR  name2  EQ 'elg1150-2501261201722.270.48234901.271')>
										<cftry>
											<cfftp action="getfile"  remotefile="/outgoing/#name2#" localfile="#reading_filepath##name2#"
													failIfExists="no" timeout="300" connection="objConnection" />  
											<cffile action="read"  variable="fileContent" file="#reading_filepath##name2#" >					              		
											<!--- Process the file --->
											/outgoing/#name2#<br>
											 <cfinclude template = "/dashboard/eligibility_file_reading.cfm"> 
											<!--- Delete the file after processing (skip on stage/dev) --->
											<cfif NOT isNonProdServer>
												<cffile action="delete" file="#reading_filepath##name2#">
											</cfif>
										<cfcatch type="any">
											<!--- Log FTP/file operation errors --->
											<cflog file="eligibility_import" type="Error" 
												text="Failure processing file #name2#; Error: #cfcatch.Message# #cfcatch.Detail#; File: #cfcatch.TagContext[1].template# Line: #cfcatch.TagContext[1].line#">
											<cftry>
												<cfmail to="velmurugan@myhomecarebiz.com"
													from="error@myhomecarebiz.com"
													subject="#Application.ServerName# - Eligibility Import File Processing Error"
													type="html">
													<p><strong>File:</strong> #name2#</p>
													<p><strong>Error Message:</strong> #cfcatch.Message#</p>
													<p><strong>Error Detail:</strong> #cfcatch.Detail#</p>
													<p><strong>Location:</strong> #cfcatch.TagContext[1].template# (Line #cfcatch.TagContext[1].line#)</p>
													<p><strong>Time:</strong> #DateFormat(Now(), 'mm/dd/yyyy')# #TimeFormat(Now(), 'HH:mm:ss')#</p>
												</cfmail>
												<cfcatch></cfcatch>
											</cftry>
											<!--- Try to delete file if it was partially downloaded (skip on stage/dev) --->
											<cfif NOT isNonProdServer>
												<cftry>
													<cfif fileExists("#reading_filepath##name2#")>
														<cffile action="delete" file="#reading_filepath##name2#">
													</cfif>
													<cfcatch></cfcatch>
												</cftry>
											</cfif>
										</cfcatch>
										</cftry>
									
									</cfif>
									
		                        </cfloop>
					    	</cfoutput> 
					    </tbody>
					</table>
				</div>
			</div>

			<cfif NOT isNonProdServer>
			    <cfloop from="1" to="#dirlist.recordCount#" index="k">
			     	<cfset filepath = "/Upload//" />
					<cfset name2 = #dirlist.name[k]# />
					<cfset filepath2 = filepath&name2 >
					<cfset valueWithoutElg = Replace(name2, "elg", "", "all")>
					<cfset splitArray = ListToArray(valueWithoutElg, "-")>
					<cfset agency_number = arrayLen(splitArray) ? splitArray[1] : "" />
					<cfif NOT billingSFTP.shouldProcessAgencyFile(agency_number, importConn.dedicatedAgencyId)>
						<cfcontinue />
					</cfif>
					<cfif (Right(name2,4) eq  '.271')>
						<cfftp Connection="objConnection" Action="Remove" Item="/outgoing/#name2#">  
					</cfif>
			 	</cfloop>
			</cfif>
<cfftp action="close" connection="objConnection" >
</cfloop>