<cfparam name="url.payer" default="" />
<cfparam name="url.df" default="" />
<cfparam name="url.dt" default="" />
<cfparam name="form.payer" default="#url.payer#" />
<cfparam name="form.df" default="#url.df#" />
<cfparam name="form.dt" default="#url.dt#" />
<cfparam name="form.adj_type" default="" />

<cfset dfVal = (IsDate(form.df) AND NOT IsNumeric(form.df)) ? DateFormat(form.df, "yyyy-mm-dd") : "" />
<cfset dtVal = (IsDate(form.dt) AND NOT IsNumeric(form.dt)) ? DateFormat(form.dt, "yyyy-mm-dd") : "" />
<cfset adjLive = billingLock.isLive() />

<cfquery name="getAdjPayers" datasource="#Application.DataSrc#">
    SELECT Pay_ID, Pay_Name
    FROM #Request.prefix_db_agency#.pPayer
    WHERE Status = 0
    ORDER BY Pay_Name
</cfquery>

<cfif adjLive>
    <cfquery name="getAdjustments" datasource="#Application.DataSrc#">
        SELECT * FROM (
            <cfif form.adj_type NEQ "payment">
                SELECT 'Invoice' AS adj_kind, i.Invoice_ID AS rec_id, i.Invoice_ID AS inv_id, i.adjusted_from_id,
                    src.DateSent AS orig_date, src.lock_date AS orig_lock_date, src.ContractTotal AS orig_amount,
                    i.DateSent AS new_date, i.ContractTotal AS new_amount, 0 AS new_writeoff, i.lock_date AS new_lock_date,
                    i.Record_Created_Date AS created_date,
                    CONCAT(IFNULL(emp.Emp_Last, ''), ', ', IFNULL(emp.Emp_First, '')) AS created_by,
                    py.Pay_ID, py.Pay_Name, p.Patient_ID, p.Pt_Last, p.Pt_First, p.Pt_Agy_ID
                FROM #Request.prefix_db_agency#.Invoices i
                LEFT JOIN #Request.prefix_db_agency#.Invoices src ON src.Invoice_ID = i.adjusted_from_id
                LEFT JOIN #Request.prefix_db_agency#.pPayer py ON py.Pay_ID = i.PatientPayer_ID
                LEFT JOIN #Request.prefix_db_agency#.pPatients p ON p.Patient_ID = i.Patient_ID AND p.Status IN (#Request.patient_status#)
                LEFT JOIN #Request.prefix_db_lookup#.pEmployee emp ON emp.Emp_ID = i.Record_Created_By
                WHERE i.Agency_ID = <cfqueryparam value="#session.AgencyId#" cfsqltype="cf_sql_integer">
                AND i.Deleted <> 1
                AND i.adjusted_from_id > 0
            </cfif>
            <cfif form.adj_type EQ "">
                UNION ALL
            </cfif>
            <cfif form.adj_type NEQ "invoice">
                SELECT 'Payment' AS adj_kind, pm.Payment_ID AS rec_id, pm.Invoice_ID AS inv_id, pm.adjusted_from_id,
                    src.PaymentDate AS orig_date, src.lock_date AS orig_lock_date, src.Amount AS orig_amount,
                    pm.PaymentDate AS new_date, pm.Amount AS new_amount, IFNULL(pm.WriteOffAmount, 0) AS new_writeoff, pm.lock_date AS new_lock_date,
                    pm.Record_Created_Date AS created_date,
                    CONCAT(IFNULL(emp.Emp_Last, ''), ', ', IFNULL(emp.Emp_First, '')) AS created_by,
                    py.Pay_ID, py.Pay_Name, p.Patient_ID, p.Pt_Last, p.Pt_First, p.Pt_Agy_ID
                FROM #Request.prefix_db_agency#.Payments pm
                JOIN #Request.prefix_db_agency#.Invoices i ON i.Invoice_ID = pm.Invoice_ID
                LEFT JOIN #Request.prefix_db_agency#.Payments src ON src.Payment_ID = pm.adjusted_from_id
                LEFT JOIN #Request.prefix_db_agency#.pPayer py ON py.Pay_ID = i.PatientPayer_ID
                LEFT JOIN #Request.prefix_db_agency#.pPatients p ON p.Patient_ID = i.Patient_ID AND p.Status IN (#Request.patient_status#)
                LEFT JOIN #Request.prefix_db_lookup#.pEmployee emp ON emp.Emp_ID = pm.Record_Created_By
                WHERE i.Agency_ID = <cfqueryparam value="#session.AgencyId#" cfsqltype="cf_sql_integer">
                AND pm.Deleted <> 1
                AND pm.adjusted_from_id > 0
            </cfif>
        ) adj
        WHERE 1 = 1
        <cfif Val(form.payer) GT 0>
            AND adj.Pay_ID = <cfqueryparam value="#Val(form.payer)#" cfsqltype="cf_sql_integer">
        </cfif>
        <!--- Undated copies always show: they still need a date before they count anywhere --->
        <cfif dfVal NEQ "">
            AND (adj.new_date IS NULL OR DATE(adj.new_date) >= <cfqueryparam value="#dfVal#" cfsqltype="cf_sql_date">)
        </cfif>
        <cfif dtVal NEQ "">
            AND (adj.new_date IS NULL OR DATE(adj.new_date) <= <cfqueryparam value="#dtVal#" cfsqltype="cf_sql_date">)
        </cfif>
        ORDER BY adj.created_date DESC, adj.rec_id DESC
    </cfquery>
</cfif>

<cfoutput>
<div class="portlet box blue">
    <div class="portlet-title">
        <div class="caption">
            <i class="fa fa-gear"></i> Billing Adjustments
        </div>
        <div class="actions">
            <a href="javascript:;" class="btn btn-default btn-sm" onclick="history.back();"> Back </a>
            <a title="" data-original-title="" href="javascript:;" class="btn btn-icon-only btn-default btn-sm fullscreen"></a>
        </div>
    </div>
    <div class="portlet-body form">
        <form name="form1" action="index.cfm?page=agency&cat=BillingReports&rpt=billing_adjustments" method="post" style="margin:0; padding:0;">
            <div class="form-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Bill / Payment Date FROM&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TO</label>
                            <div class="input-group input-large date-picker input-daterange" data-date-format="mm/dd/yyyy">
                                <input type="text" class="form-control" name="df" value="#DateFormat(dfVal, 'mm/dd/yyyy')#" />
                                <span class="input-group-addon"> to </span>
                                <input type="text" class="form-control" name="dt" value="#DateFormat(dtVal, 'mm/dd/yyyy')#" />
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                            </div>
                            <span class="help-block">Copies with no date entered yet are always listed.</span>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Payer</label>
                            <select name="payer" class="form-control">
                                <option value="">All payers</option>
                                <cfloop query="getAdjPayers">
                                    <option value="#getAdjPayers.Pay_ID#" <cfif Val(form.payer) EQ getAdjPayers.Pay_ID>selected</cfif>>#getAdjPayers.Pay_Name#</option>
                                </cfloop>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Type</label>
                            <select name="adj_type" class="form-control">
                                <option value="">Invoices &amp; payments</option>
                                <option value="invoice" <cfif form.adj_type EQ "invoice">selected</cfif>>Invoices</option>
                                <option value="payment" <cfif form.adj_type EQ "payment">selected</cfif>>Payments</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group" style="margin-top:25px;">
                            <input type="submit" value="Search" class="btn blue">
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="portlet box blue">
    <div class="portlet-title">
        <div class="caption">
            <i class="fa fa-list"></i> Adjustment Copies of Locked Invoices and Payments
        </div>
    </div>
    <div class="portlet-body flip-scroll">
        <cfif NOT adjLive>
            <p>Month locking is not set up for this agency yet (the ##10745 migration has not been run), so there are no adjustments.</p>
        <cfelseif getAdjustments.recordCount EQ 0>
            <p>No billing adjustments found.</p>
        <cfelse>
            <table class="table table-striped table-bordered table-hover" id="Datatab">
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Adjustment</th>
                        <th>Copied From</th>
                        <th>Payer</th>
                        <th>Patient</th>
                        <th>Original Date / Amount</th>
                        <th>New Date</th>
                        <th>New Amount</th>
                        <th>Status</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                    <cfloop query="getAdjustments">
                        <cfif getAdjustments.adj_kind EQ "Invoice">
                            <cfset adjLink = "index.cfm?page=agency&cat=BillingReports&rpt=Invoice-Edit&inv=#getAdjustments.rec_id#" />
                            <cfset origLink = "index.cfm?page=agency&cat=BillingReports&rpt=Invoice-Edit&inv=#getAdjustments.adjusted_from_id#" />
                        <cfelse>
                            <cfset adjLink = "index.cfm?page=agency&cat=BillingReports&rpt=apply_payment&inv=#getAdjustments.inv_id#&payId=#getAdjustments.rec_id#" />
                            <cfset origLink = "index.cfm?page=agency&cat=BillingReports&rpt=apply_payment&inv=#getAdjustments.inv_id#&payId=#getAdjustments.adjusted_from_id#" />
                        </cfif>
                        <tr>
                            <td>#getAdjustments.adj_kind#</td>
                            <td><a href="#adjLink#">###getAdjustments.rec_id#</a><cfif getAdjustments.adj_kind EQ "Payment"><br><small>Invoice ###getAdjustments.inv_id#</small></cfif></td>
                            <td><a href="#origLink#">###getAdjustments.adjusted_from_id#</a></td>
                            <td>#getAdjustments.Pay_Name#</td>
                            <td>
                                <cfif Val(getAdjustments.Patient_ID) GT 0>
                                    <cfset en_patid = encrypt(getAdjustments.Patient_ID, application.enckey, "AES", "Hex") />
                                    <a href="../patientadmin_new/index.cfm?page=patient&ID=#en_patid#&cat=GeneralInformation">#getAdjustments.Pt_Last#, #getAdjustments.Pt_First#</a> (#getAdjustments.Pt_Agy_ID#)
                                </cfif>
                            </td>
                            <td>
                                #DateFormat(getAdjustments.orig_date, "mm/dd/yyyy")# / #DollarFormat(Val(getAdjustments.orig_amount))#
                                <cfif IsDate(getAdjustments.orig_lock_date)><br><small>locked #DateFormat(getAdjustments.orig_lock_date, "mm/dd/yyyy")#</small></cfif>
                            </td>
                            <td>
                                <cfif IsDate(getAdjustments.new_date)>
                                    #DateFormat(getAdjustments.new_date, "mm/dd/yyyy")#
                                <cfelse>
                                    <span class="font-red"><b>Date not entered</b></span>
                                </cfif>
                            </td>
                            <td>
                                #DollarFormat(Val(getAdjustments.new_amount))#
                                <cfif Val(getAdjustments.new_writeoff) NEQ 0><br><small>write-off #DollarFormat(getAdjustments.new_writeoff)#</small></cfif>
                            </td>
                            <td>
                                <cfif IsDate(getAdjustments.new_lock_date)>
                                    Locked (#DateFormat(getAdjustments.new_lock_date, "mm/dd/yyyy")#)
                                <cfelseif IsDate(getAdjustments.new_date)>
                                    Open &ndash; locks #DateFormat(billingLock.monthLockDate(getAdjustments.new_date), "mm/dd/yyyy")#
                                <cfelse>
                                    Open &ndash; enter a date
                                </cfif>
                            </td>
                            <td>#DateFormat(getAdjustments.created_date, "mm/dd/yyyy")#<cfif Len(Replace(getAdjustments.created_by, ", ", ""))><br><small>#getAdjustments.created_by#</small></cfif></td>
                        </tr>
                    </cfloop>
                </tbody>
            </table>
        </cfif>
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        if ($.fn.dataTable) {
            $("##Datatab").dataTable({ "sPaginationType": "full_numbers", "aaSorting": [] });
        }
    });
</script>
</cfoutput>
