 <cfparam name="form.allinvoice_ids" default="0">

<cfset Enc_tempDeposit_ID   = #URL.tempDeposit_ID# />
<cfif url.tempDeposit_ID NEQ '0'>
    <cfset URL.tempDeposit_ID   = decrypt(#URL.tempDeposit_ID#,#application.enckey#,"AES","Hex") />
</cfif>

<cfquery  name="getdeptemp" datasource="#Application.DataSrc#">
    SELECT pDeposit_temp.*,pPayer.Pay_Name FROM #Request.prefix_db_lookup#.pDeposit_temp
    JOIN #Request.prefix_db_agency#.pPayer ON  pDeposit_temp.Payer_ID = pPayer.Pay_ID 
    WHERE pDeposit_temp.Status = 0
    AND pDeposit_temp.Dep_ID =  <cfqueryparam value = "#URL.tempDeposit_ID#" CFSQLType ="cf_sql_integer">
</cfquery>

<cfif form.allinvoice_ids  NEQ 0 >
    <cfset client.Invoice_ID =  "" >
    <!--- Prevent duplicate EFT# (Remit_No) once before processing claims (not per-claim; same EFT# applies to all claims in this remittance) --->
    <cfif form.finalsubmit EQ 1>
        <cfquery name="checkDuplicateRemitFinal" datasource="#Application.DataSrc#">
            SELECT Dep_ID FROM #Request.prefix_db_agency#.pDeposit
            WHERE Remit_No = <cfqueryparam value="#Trim(getdeptemp.Remit_No)#" cfsqltype="cf_sql_varchar">
            AND Status = 0
        </cfquery>
        <cfif checkDuplicateRemitFinal.recordCount GT 0>
            <cfset session.remittance_error = "A remittance with this EFT## (Remit No) already exists. This remittance was not saved to avoid a duplicate." />
            <cflocation url="/agencyadmin/index.cfm?page=agency&cat=BillingReports&rpt=remitt_claim_selections&tempDeposit_ID=#Enc_tempDeposit_ID#" addtoken="no">
        </cfif>
    </cfif>
    <cfloop list="#form.allinvoice_ids#" index="invoiceid">   
        <cfif  invoiceid NEQ 0 >
            <cfset variables.Invoiceid =  FORM["Invoices_"&invoiceid] />     
            <cfif variables.Invoiceid  NEQ 0>
                <cfset variables.Reimbursment =  FORM["Reimbursment_"&invoiceid] />  
                <cfquery  name="getinvoices" datasource="#Application.DataSrc#">
                    SELECT Invoice_ID,Internal_Control_number  FROM #Request.prefix_db_agency#.Invoices
                    WHERE deleted = 0
                    AND Invoice_ID =  <cfqueryparam value = "#variables.Invoiceid#" CFSQLType ="cf_sql_integer">
                </cfquery>
                 <cfquery  name="getsched" datasource="#Application.DataSrc#">
                    SELECT  * FROM #Request.prefix_db_agency#.pSchedules
                    WHERE (pSchedules.NOA = #variables.Invoiceid# OR pSchedules.Invoice_ID = #variables.Invoiceid#)
                    AND pSchedules.Status = 0
                    GROUP BY  pSchedules.Schedule_ID
                </cfquery>


                <cfif form.finalsubmit EQ 1 >
                    <!---  Insertion of pDeposit --->
                    <cfquery  name='pDeposittempInsert' datasource='#Application.DataSrc#'>
                        INSERT INTO #Request.prefix_db_agency#.pDeposit
                        ( Status, Payer_ID, Date_Create, Date_Deposit, Date_Check, Deposit_Type, Check_Total,Total_Provider,Remit_No, 
                          Internal_Control_number, <!--- HCPCS, SVC04, SVC03, Writeoff_Amount, Visit_Date,---> Pay_Name, 
                          Net_Total, Record_Created_Date, Record_Created_By, Record_Modified_Date, Record_Modified_By)
                        VALUES(
                          <cfqueryparam cfsqltype="cf_sql_integer" value="0">,
                          <cfqueryparam cfsqltype="cf_sql_integer" value="#getdeptemp.Payer_ID#">,
                          <cfqueryparam cfsqltype="cf_sql_date" value="#getdeptemp.Date_Create#">,
                          <cfqueryparam cfsqltype="cf_sql_date" value="#getdeptemp.Date_Deposit#">,
                          <cfqueryparam cfsqltype="cf_sql_date" value="#getdeptemp.Date_Check#">,
                          'Check',
                          <cfqueryparam cfsqltype="CF_SQL_FLOAT" value="#getdeptemp.Check_Total#">,
                           <cfqueryparam cfsqltype="CF_SQL_FLOAT" value="#getdeptemp.Total_Provider#">,
                          <cfqueryparam cfsqltype="cf_sql_varchar" value="#getdeptemp.Remit_No#">,
                          <cfqueryparam cfsqltype="cf_sql_varchar" value="#getinvoices.Internal_Control_number#">,
                          <cfqueryparam cfsqltype="cf_sql_varchar" value="#getdeptemp.Pay_Name#">,
                          <cfqueryparam cfsqltype="CF_SQL_FLOAT" value="#variables.Reimbursment#">,
                          <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                          <cfqueryparam value = "#session.employeeid#" CFSQLType ="CF_SQL_INTEGER">,
                          <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                          <cfqueryparam value = "#session.employeeid#" CFSQLType ="CF_SQL_INTEGER">
                          )        
                    </cfquery>
                    <cfset total_writeoffamount =  '0.00' />  
                    <cfloop query = "getsched">
                        <cfset variables.Schedule_ID = #getsched.Schedule_ID# />
                        <cfset variables.payment         =  FORM["payment_"& variables.Schedule_ID] />
                        <cfset variables.write_offamount =  FORM["write_offamount_"& variables.Schedule_ID] />
                        <cfset variables.write_offcode   =  FORM["write_offcode_"& variables.Schedule_ID] />
                        <cfset variables.Reason_WriteOff =  FORM["Reason_WriteOff_"& variables.Schedule_ID] /> 
                        <cfif  variables.payment EQ ''>
                             <cfset variables.payment  = '0.00'  />  
                        </cfif>
                        <cfif  variables.write_offamount EQ ''>
                             <cfset variables.write_offamount  = '0.00'  />  
                        </cfif>
                         <cfif  variables.Reason_WriteOff EQ ''>
                             <cfset variables.Reason_WriteOff  = '0.00'  />  
                        </cfif>
                        <cfset total_writeoffamount =  total_writeoffamount  + variables.write_offamount />
                    </cfloop>

                     <!---  Insertion of Payments --->
                    <cfquery  name='insert' datasource='#Application.DataSrc#'>
                          INSERT INTO #Request.prefix_db_agency#.Payments (
                               invoice_id, patientpayer_id, paymentdate, amount, paymentmethod, comments, writeoffamount,EFT_Amount,EFT_No, 
                               Claim, writeofftype,Record_Created_By,Record_Created_Date,Record_Modified_By,Record_Modified_Date

                            ) VALUES (
                              <cfqueryparam cfsqltype="cf_sql_varchar" value="#getinvoices.Invoice_ID#">
                              ,<cfqueryparam cfsqltype="cf_sql_varchar" value="#getdeptemp.Payer_ID#">
                              ,<cfqueryparam cfsqltype="cf_sql_date" value="#getdeptemp.Date_Deposit#">
                              ,<cfqueryparam cfsqltype="CF_SQL_FLOAT" value="#variables.Reimbursment#">
                              ,'Check'
                              ,'Updated by new remittance'
                              ,'#total_writeoffamount#'
                              ,0.00
                              ,<cfqueryparam cfsqltype="cf_sql_varchar" value="#getdeptemp.Remit_No#">
                              ,<cfqueryparam cfsqltype="cf_sql_varchar" value="#getinvoices.Internal_Control_number#">
                              ,NULL
                              ,'#Session.EmployeeId#'
                                ,#now()#
                                ,'#Session.EmployeeId#'
                                ,#now()#
                            ) 
                    </cfquery>
                    <cfset COOKIE["Reimbursment_"&invoiceid] = "0.00" />
                    <cfset client.Invoice_ID = 0 />
                <cfelse>
                     <cfset COOKIE["Reimbursment_"&invoiceid] = variables.Reimbursment />
                     <cfset client.Invoice_ID = listappend(client.Invoice_ID,invoiceid)/>
                </cfif>

                <!--- Insertion of pSchedules --->
               
                <cfset form.Record_Creation_Date = "#Now()#" />
                <cfset form.Record_Created_By = #session.employeeid# />
                <cfset form.Record_Mod_Date = #Now()# />
                <cfset form.Record_Mod_By = #session.employeeid# />
                <cfloop query = "getsched">
                    <cfset variables.Schedule_ID = #getsched.Schedule_ID# />
                    <cfset variables.payment         =  FORM["payment_"& variables.Schedule_ID] />
                    <cfset variables.write_offamount =  FORM["write_offamount_"& variables.Schedule_ID] />
                    <cfset variables.write_offcode   =  FORM["write_offcode_"& variables.Schedule_ID] />
                    <cfset variables.Reason_WriteOff =  FORM["Reason_WriteOff_"& variables.Schedule_ID] /> 
                    <cfif  variables.payment EQ ''>
                         <cfset variables.payment  = '0.00'  />  
                    </cfif>
                    <cfif  variables.write_offamount EQ ''>
                         <cfset variables.write_offamount  = '0.00'  />  
                    </cfif>
                     <cfif  variables.Reason_WriteOff EQ ''>
                         <cfset variables.Reason_WriteOff  = '0.00'  />  
                    </cfif>
                     <cftry>  
                        <!--- <cfquery name="InsertingpSchedules"  datasource="#Application.DataSrc#"  result="result">
                           INSERT INTO #Request.prefix_db_agency#.pSchedules
                            (Schedule_ID, Patient_ID, Assmt_ID, Auth_ID, PtPayer_ID, Rev_ID, Emp_ID, Pay_ID, Invoice_ID,
                             HCPCS_ID, CMSOrder_ID, Skill, Followup_visit, Visit_Type, Visit_no, Status, Nonbillable, Missed,
                             NOA, Visit_Date, StartTime, EndTime, Total_Units, Total_Eclaim, Export_Date, EClaimed, Total_EPay,
                             Mi_Pay, Mileage, Travel, Paperwork, Progress_Note, pgnotesdraft, Notes, Supervision, Initial_visit, 
                             total_visits, severity_problem, severity_goal, increment_problem, increment_this_visit, result_this_visit, 
                             total_goal, increment_goal, increment_goal_this_visit, goal_result_this_visit, total_increment, total_result, 
                             prn_visit, prn_reason, homebound, Schedules_Dup, Sch_Longitude, Sch_Latitude, Amt_Paid, Amt_WriteOff, Reason_WriteOff,
                             payment, write_offamount, write_offcode, write_offcodesecond, patient_sign, sign_datetime, Date_Create, Created_by,
                             Date_Change, Change_by)    

                            SELECT  
                             Schedule_ID, Patient_ID, Assmt_ID, Auth_ID, PtPayer_ID, Rev_ID, Emp_ID, Pay_ID, Invoice_ID,
                             HCPCS_ID, CMSOrder_ID, Skill, Followup_visit, Visit_Type, Visit_no, Status, Nonbillable, Missed,
                             NOA, Visit_Date, StartTime, EndTime, Total_Units, Total_Eclaim, Export_Date, EClaimed, Total_EPay,
                             Mi_Pay, Mileage, Travel, Paperwork, Progress_Note, pgnotesdraft, Notes, Supervision, Initial_visit, 
                             total_visits, severity_problem, severity_goal, increment_problem, increment_this_visit, result_this_visit, 
                             total_goal, increment_goal, increment_goal_this_visit, goal_result_this_visit, total_increment, total_result, 
                             prn_visit, prn_reason, homebound, Schedules_Dup, Sch_Longitude, Sch_Latitude, Amt_Paid, Amt_WriteOff, '#variables.Reason_WriteOff#',
                             '#variables.payment#', '#variables.write_offamount#', '#variables.write_offcode#', write_offcodesecond, patient_sign, sign_datetime, 
                             <cfqueryparam VALUE="#form.Record_Creation_Date#"  cfsqltype="cf_sql_timestamp">,
                             <cfqueryparam VALUE="#form.Record_Created_By#"  cfsqltype="cf_sql_integer">,
                             <cfqueryparam VALUE="#form.Record_Mod_Date#"  cfsqltype="cf_sql_timestamp">,
                             <cfqueryparam VALUE="#form.Record_Mod_By#"  cfsqltype="cf_sql_integer"> 
                             FROM #Request.prefix_db_agency#.pSchedules 
                             WHERE  AutoSchedule_ID = <cfqueryparam VALUE="#AutoSchedule_ID#"  cfsqltype="cf_sql_integer">                   
                        </cfquery>
                        <cfquery name="update_pSchedules" datasource="#Application.DataSrc#"  result="result">
                           UPDATE #Request.prefix_db_agency#.pSchedules SET 
                           Status   = <cfqueryparam VALUE="3"  cfsqltype="cf_sql_integer">,      
                           Date_Change = <cfqueryparam VALUE="#form.Record_Mod_Date#"  cfsqltype="cf_sql_timestamp">,
                           Change_by = <cfqueryparam VALUE="#form.Record_Mod_By#"  cfsqltype="cf_sql_integer">
                           WHERE  Patient_ID = <cfqueryparam VALUE="#Patient_ID#"  cfsqltype="cf_sql_integer">
                           AND AutoSchedule_ID = <cfqueryparam VALUE="#AutoSchedule_ID#"  cfsqltype="cf_sql_integer">
                           AND Status = 0
                        </cfquery> --->
                         <cfquery name="getcurrentschd" datasource="#Application.DataSrc#">
                          SELECT * FROM #Request.prefix_db_agency#.pSchedules 
                           WHERE AutoSchedule_ID = <cfqueryparam VALUE="#AutoSchedule_ID#"  cfsqltype="cf_sql_integer">
                           AND Status = 0
                        </cfquery>
                        <cfscript>
                             pgcfc = CreateObject("Component", "components.general.progressnotes");
                             retiredschedules = pgcfc.retire_schedules(#getcurrentschd.Schedule_ID#); 
                        </cfscript>
                        <cfcatch>
                                <h1>You may be giving wrong data in the visit form, so error occured while updating the schedule visit. 
                                So please go back and correct it or contact your admin.</h2><cfabort>
                        </cfcatch>
                    </cftry> 
                </cfloop>

            </cfif>    
        </cfif>
    </cfloop>
    <cfif CGI.REMOTE_ADDR EQ '121.200.49.65'>
        <!--- <cfabort> --->
    </cfif>
     <cfif form.finalsubmit EQ 1 >
        <cflocation url="/agencyadmin/index.cfm?aMenu=billing&page=agency&cat=BillingReports&rpt=remittance_manager" addtoken="no">
     <cfelse>
        <cflocation url="/agencyadmin/index.cfm?page=agency&cat=BillingReports&rpt=add_reimbursement_amountnew&tempDeposit_ID=#Enc_tempDeposit_ID#" addtoken="no">
     </cfif>
<cfelse>
     <h3>Something wen wrong. So please click  <a href="javascript:;" onclick="history.back();"> here</a> to back</h3>
</cfif>