<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="" />
<cfparam name="url.Output" 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.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,pr.Output, 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
	  <cfif url.payer_filter neq ''>
	   AND   pr.Pay_ID = '#url.payer_filter#'
	 </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
	   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>
	
<cfquery  name='Getallschedules' datasource='#Application.DataSrc#'>
	 SELECT  pSchedules.Schedule_ID, pSchedules.Total_Units,pSchedules.Invoice_ID,pSchedules.Visit_Date,pSchedules.Skill,
	 pSchedules.Total_Eclaim,
	  pRevenue_Code.Measure, pRevenue_Code.EClaim_Price ,
	   vp.Visit_Pay_ID, vp.Schedule_ID as vp_Schedule_ID ,vp.Payment_ID, IFNULL(vp.payment,0) AS payment, 
	   IFNULL(vp.write_offamount,0) AS write_offamount,IFNULL(vp.second_write_offamount,0) AS second_write_offamount,
	   IFNULL(vp.third_write_offamount,0) AS third_write_offamount, IFNULL(vp.fourth_write_offamount,0) AS fourth_write_offamount,
	   vp.write_offcode, vp.write_offcodesecond, vp.second_write_offcode,vp.second_write_offcodesecond, 
	   vp.third_write_offcode, 
 vp.third_write_offcodesecond, vp.fourth_write_offcode, vp.fourth_write_offcodesecond 
	 FROM   #Request.prefix_db_agency#.pSchedules
	 JOIN  #Request.prefix_db_agency#.Invoices ON  Invoices.Invoice_Id = pSchedules.Invoice_ID
	  JOIN #Request.prefix_db_agency#.pRevenue_Code ON pRevenue_Code.Rev_CodeID = pSchedules.Rev_ID
	  LEFT OUTER JOIN #Request.prefix_db_agency#.Visits_payments vp ON  vp.Schedule_ID = pSchedules.Schedule_ID 
	  AND vp.Status = 0 
	 WHERE  pSchedules.Status = 0 AND Invoices.Deleted <> 1 
	 <!--- AND   pSchedules.Invoice_ID  IN (#ValueList(GetI.Invoice_ID)#) --->
	 AND vp.Payment_ID IN ( SELECT Payment_ID FROM #Request.prefix_db_agency#.Payments
		 WHERE  Invoice_ID  IN (#ValueList(GetI.Invoice_ID)#)
	 		AND Deleted <> 1 
	  <cfif url.df NEQ '' AND url.dt NEQ '' >
	    	 AND  PaymentDate >= #CreateODBCDate(url.df)#
	    	 AND  PaymentDate <= #CreateODBCDate(url.dt)#
	   </cfif> )
	 GROUP BY vp.Visit_Pay_ID
</cfquery>
  <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)
  />
  
<cfset Request.adjustments_total = 0 >

<cfoutput query="GetI">
		<cfquery  name='Getschedule' dbtype="query">
			SELECT * FROM Getallschedules
			WHERE Invoice_ID = '#GetI.Invoice_ID#'
		</cfquery>

		<cfset Request.adjustments =  '0.00' />
		
		<cfif GetI.Output NEQ 'Medicare'>
			<cfset Request.amt_Paid = paid />
			<!--- <cfset Request.adjustments =  Request.adjustments  + wOff /> --->	
			 <cfloop query='Getschedule'>
			 	<cfset Request.adjustments =  Request.adjustments  + write_offamount + second_write_offamount + 
			 	   + third_write_offamount + fourth_write_offamount />	
				<!--- <cfif write_offcode NEQ 'PR'>
					<cfset Request.adjustments =  Request.adjustments  + write_offamount />							
				</cfif>
				<cfif second_write_offcode NEQ 'PR'>
					<cfset Request.adjustments =  Request.adjustments + second_write_offamount />							
				</cfif>
				<cfif third_write_offcode NEQ 'PR'>
					<cfset Request.adjustments =  Request.adjustments + third_write_offamount />							
				</cfif>
				<cfif fourth_write_offcode NEQ 'PR'>
					<cfset Request.adjustments =  Request.adjustments + fourth_write_offamount/>							
				</cfif>--->
			</cfloop> 
			<cfelse>
				<cfset Request.adjustments =  Request.adjustments  + wOff />			
		</cfif>
	<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(Request.adjustments)# & """"
				
                & chr(13)
						    & chr(10)
   />
   	<cfset Request.adjustments_total = Request.adjustments_total +  Request.adjustments>
   </cfif>

   </cfoutput>

    <cfset str = str
            & """" & ""& """"
					  & "," & """" & "" & """"
            & "," & """" & "" & """"
            & "," & """" & "" & """"
	        & "," & """" &"" & """"
					& "," & """" & "" & """"
	        & "," & """" & ""& """"
	        & "," & """" & "" & """"
	        & "," & """" &"" & """"
				  & "," & """" & "" & """"
				  & "," & """" & "Adjustment Total" & """"
				    & "," & """" & #DollarFormat(Request.adjustments_total)# & """"
				
                & chr(13)
						    & chr(10)
   />

   <cfset dt = DateFormat(Now(), "yyyy-mm-dd") />
    <br /><br />
   <cffile action="write" file="#application.datapath##session.AgencyId#_#dt#.csv" output="#str#">
  <cfoutput><p>  <a href="#application.webdatapath##session.AgencyId#_#dt#.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>