<cfparam name="url.Pay_Name" default="" />
<cfparam name="url.patient_filter" default="" />
<cfparam name="url.df" default="" />
<cfparam name="url.dt" default="" />
<cfparam name="url.db" default="" />
<cfparam name="url.age_filter" default="" />
<cfparam name="form.amount_filter" default="" />
<cfparam name="url.ID" default="" />
<cfparam name="url.payer_filter" default="" />

<cfquery  name="GetI" datasource="#Application.DataSrc#">
	 SELECT
	 MAX(s.Payment_ID) as Payment_ID,s.PaymentDate,s.Record_Created_By,
		 (select sum(s.Amount) from #Request.prefix_db_agency#.Payments s
		      where s.invoice_id = p.invoice_id  and s.Deleted <> 1
		      <cfif url.df NEQ '' AND url.dt NEQ '' >
		    	 AND  s.PaymentDate >= #CreateODBCDate(url.df)#
		    	 AND  s.PaymentDate <= #CreateODBCDate(url.dt)#
		   </cfif>
		      ) as paid,
		(s.WriteOffAmount) as WriteOffAmount,
			 s.PatientPayer_ID ,
		(select sum(writeoffamount) from #Request.prefix_db_agency#.Payments 
			where invoice_id = p.invoice_id  and Deleted <> 1
			<cfif url.df NEQ '' AND url.dt NEQ ''>
	    	 AND  s.PaymentDate >= #CreateODBCDate(url.df)#
	    	 AND  s.PaymentDate <= #CreateODBCDate(url.dt)#
	   </cfif>
			) as wOff,
	  p.PayerBalance,
	    (select s.PaymentDate from #Request.prefix_db_agency#.Payments s
      WHERE s.invoice_id = p.invoice_id 
      <cfif url.df NEQ '' AND url.dt NEQ '' >
	    	 AND  s.PaymentDate >= #CreateODBCDate(url.df)#
	    	 AND  s.PaymentDate <= #CreateODBCDate(url.dt)#
	   </cfif>
	    AND s.Amount > 0
      and s.deleted <> 1 ORDER BY s.PaymentDate DESC LIMIT 0,1) as paid_date,

	  pa.Patient_ID, pa.Pt_Last,pa.Pt_Agy_ID,
	  a.F177 AS STARTS, a.F178 AS ENDS , a.F26 AS TYPE, pa.Pt_First, pa.Pt_Agy_ID, pa.Status,
	   	 CASE
	    WHEN DATEDIFF(p.DateSent,a.F177) < 30 THEN a.F177
	    WHEN DATEDIFF(p.DateSent,a.F177) >= 30 THEN  DATE_ADD(a.F177, INTERVAL 30 DAY)
    ELSE  a.F177
    END as START,
    CASE
	    WHEN DATEDIFF(p.DateSent,a.F177) < 30 THEN DATE_ADD(a.F177, INTERVAL 29 DAY)
	    WHEN DATEDIFF(p.DateSent,a.F177) >= 30 THEN  DATE_ADD(a.F177, INTERVAL 59 DAY) 
    ELSE  a.F178
    END as END,
		 DATE_FORMAT(pa.Pt_DOB,'%m/%d/%Y') AS DateOfBirth,
      
     (SELECT Date_Deposit FROM #Request.prefix_db_agency#.pDeposit 
     	WHERE pDeposit.Internal_control_number = p.Internal_control_number 
     	AND pDeposit.Status = 0  ORDER BY Date_Deposit DESC LIMIT 0,1) AS Date_Deposit,
	(SELECT Min(Visit_Date) FROM #Request.prefix_db_agency#.pSchedules 
		where Assmt_ID = p.Assmt_ID AND  p.Invoice_ID = pSchedules.Invoice_ID and status = 0 ORDER BY Visit_Date) as MIN,
	(SELECT Max(Visit_Date) FROM #Request.prefix_db_agency#.pSchedules 
		where Assmt_ID = p.Assmt_ID AND  p.Invoice_ID = pSchedules.Invoice_ID and status = 0 ORDER BY Visit_Date) as MAX,

	 		p.Invoice_Id, p.Comment, p.Output as POUT,
	 		DATE_FORMAT(p.DateSent,'%Y-%m-%d') AS DateSent,
	 		DATEDIFF(CURDATE(), p.DateSent) AS age,
		MAX(DATE_FORMAT(s.PaymentDate,'%Y-%m-%d')) AS PaymentDate,
		DATE_FORMAT(p.DateSent,'%m/%d') AS ds,
			(p.InvoiceTotal) as InvoiceTotal,p.PayerBalance,
	 	pr.Pay_ID, pr.Pay_Name, pr.Payer_No, p.Output   AS PayerOutputType,
	  (SELECT Invoice_Id FROM #Request.prefix_db_agency#.Invoices WHERE Assmt_ID = p.Assmt_ID
	AND InvoiceTotal = '0.00' and Deleted <> 1 LIMIT 1) AS FinalBilling
	 from
	#Request.prefix_db_agency#.Payments s 
	 JOIN #Request.prefix_db_agency#.Invoices p on p.Invoice_ID = s.Invoice_ID
	 JOIN #Request.prefix_db_agency#.pPatients pa on pa.patient_id = p.patient_id
	 JOIN #Request.prefix_db_agency#.pPayer pr on pr.Pay_ID = s.patientpayer_id
	LEFT OUTER JOIN #Request.prefix_db_agency#.pAssessments a on p.Assmt_ID = a.Assmt_ID

	 WHERE  p.Agency_Id = '#session.agencyid#'
	 AND pa.Status  IN (#Request.patient_status#) AND (a.status = 0 OR p.Assmt_ID = 0)
	  <cfif url.ID neq ''>
	   AND   pr.Pay_ID = '#url.ID#'
	 </cfif>
	 
	 <cfif url.Output neq ''>
	   AND   p.Output like '#url.Output#'
	 </cfif>

	 <cfif url.df NEQ "">
	  AND   s.PaymentDate >= #CreateODBCDate(url.df)#
	 </cfif>
	 <cfif url.dt NEQ "" >
	   AND   s.PaymentDate <= #CreateODBCDate(url.dt)#
	 </cfif>


	<cfif url.patient_filter NEQ "">
	  AND pa.Patient_ID  =  '#url.patient_filter#'
	 </cfif>

     AND Amount > 0
	 AND s.Deleted <> 1  AND   p.Deleted <> 1
	 AND   p.InvoiceTotal > 0
	    AND  (s.Amount > 0 OR claim_status = 'Paid' 
	  		 OR (p.InvoiceTotal  - (select sum(amount + writeoffamount + Pay_Seq_Amount) from  #Request.prefix_db_agency#.Payments 
	where invoice_id = p.invoice_id and Deleted =0)<= 0 )   
	  	)
	   AND p.Output is not null
	 Group BY p.Invoice_Id
	 ORDER BY Pt_Last, Pt_First ASC
	 
</cfquery>

<div class="portlet box blue">
		<div class="portlet-title">
			<div class="caption">
				<i class="fa fa-gift"></i>Export File
			</div>
			<div class="tools">
				<a class="collapse" href="" data-original-title="" title="">
				</a>
			</div>
			<div class="actions">
			     <a href="javascript:;" class="btn btn-default btn-sm" onclick="history.back();"> Back </a>
		    </div>
		</div>
<div class="portlet-body form">

<cfif GetI.recordcount gt 0>
  <cfset str = """" & "Patient Last Name" & """"
             & "," & """" & "Patient First Name" & """"
           & "," & """" & "MRN" & """"
             & "," & """" & "Payer Name" & """"
             & "," & """" & "Visit Date Start" & """"
             & "," & """" & "Visit Date End" & """"
              & "," & """" & "Invoice ID" & """"
			  & "," & """" & "Date Billed" & """"
			    & "," & """" & "Date Paid" & """"
			   & "," & """" & "Age" & """"
			    & "," & """" & "Paid" & """"
				& "," & """" & "Adjustment" & """"
		
			 & chr(13)
						 & chr(10)
  />
  

<cfoutput query="GetI">
	<cfif paid NEQ 0 >
				<cfset Start_Date = #DateFormat(START,"mm/dd/yyyy")# />
				<cfset End_Date = #DateFormat(END,"mm/dd/yyyy")# />
				<cfif GetI.PayerOutputType eq 'UB82-1500' or GetI.PayerOutputType eq '1500'>
						<cfset Start_Date = #DateFormat(MIN,"mm/dd/yyyy")# />
						<cfset End_Date = #DateFormat(MAX,"mm/dd/yyyy")# />
				<cfelse>
						<cfif POUT eq 'RAP'>
								<cfset Start_Date = #DateFormat(MIN,"mm/dd/yyyy")# />
								<cfset End_Date = #DateFormat(MIN,"mm/dd/yyyy")# />
						<cfelseif GetI.PayerOutputType eq 'Medicare'>
								<cfset Start_Date = #DateFormat(START,"mm/dd/yyyy")# />
								<cfset End_Date = #DateFormat(END,"mm/dd/yyyy")# />
						<cfelse>
							<cfset Start_Date = #DateFormat(MIN,"mm/dd/yyyy")# />
							<cfset End_Date = #DateFormat(MAX,"mm/dd/yyyy")# />
				    </cfif>
				</cfif>  
   <cfset str = str
                      & """" & #Trim(Pt_Last)#& """"
					  & "," & """" & #Trim(Pt_First)# & """"
            & "," & """" & #Trim(Pt_Agy_ID)# & """"
            & "," & """" & #Pay_Name# & """"
                & "," & """" & #DateFormat(Start_Date,"yyyy-mm-dd")# & """"
				& "," & """" & #DateFormat(End_Date,"yyyy-mm-dd")# & """"
        & "," & """" & #Invoice_ID# & """"
         & "," & """" & #DateFormat(DateSent,"yyyy-mm-dd")# & """"
        & "," & """" & #DateFormat(paid_date,"yyyy-mm-dd")# & """"
			  & "," & """" & #age# & """"
			  & "," & """" & #DollarFormat(paid)# & """"
			    & "," & """" & #DollarFormat(wOff)# & """"
				
                & chr(13)
						    & chr(10)
   />
   </cfif>
   </cfoutput>
   <cfset dt = dateFormat(now(), "yyyymmdd") & "_" & timeFormat(now(), "HHmmssL") />
   
    <br /><br />
   <cfset filename= "Paid_Claims_for_"& GetI.Pay_Name &"_"&dt />
   <cffile action="write" file="#application.datapath##filename#.csv" output="#str#">
  <cfoutput><p>  <a href="#application.webdatapath##filename#.csv"> Click Here</a> and choose "Save Target As..." to download the Exported data file and save it to your computer</p>
   <br /><br />
  </cfoutput>
   <cfelse>
 <p> No data could be found based on your search criteria</p>
 <p> Please try again<p>
   </cfif>
</div>
</div>