<style type="text/css">
    @media print
    {
        .no-print, .no-print *
        {
            display: none !important;
        }
        .print, .print *
        {
            display: block;
        }
    }
    .print, .print *
    {
        display: none;
    }
    .box{
        border: 1px solid grey !important;
    }
    #monthDetailModal .modal-body {
        overflow-x: auto !important;
        -webkit-overflow-scrolling: touch !important;
    }
    #monthDetailModal .modal-content {
        overflow: hidden !important;
    }
    #monthDetailModal .modal-dialog {
        margin: 30px auto !important;
    }
</style>
<?php
$currency_symbol = $this->customlib->getSchoolCurrencyFormat();
?>
<div class="content-wrapper" style="min-height: 946px;">
    <section class="content-header">
        <h1>
            <i class="fa fa-money"></i> <?php echo $this->lang->line('fees_collection'); ?></h1>
    </section>
    <section class="content">

        <!-- Box 1: Fees Group + Class + Section (OLD - unchanged) -->
        <div class="row">
            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-search"></i> <?php echo $this->lang->line('select_criteria'); ?></h3>
                    </div>
                    <form action="<?php echo site_url('studentfee/feesearch') ?>" method="post" accept-charset="utf-8">
                        <div class="box-body">
                            <?php echo $this->customlib->getCSRF(); ?>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label><?php echo $this->lang->line('fees_group'); ?></label><small class="req"> *</small>
                                        <select autofocus="" id="feegroup_id" name="feegroup_id" class="form-control">
                                            <option value=""><?php echo $this->lang->line('select'); ?></option>
                                            <?php foreach ($feesessiongrouplist as $feecategory) { ?>
                                                <optgroup label="<?php echo $feecategory->group_name; ?>">
                                                    <?php if (!empty($feecategory->feetypes)) {
                                                        foreach ($feecategory->feetypes as $fee_key => $fee_value) { ?>
                                                            <option <?php if ($feecategory->id . "-" . $fee_value->id == $fees_group) { echo 'selected="selected"'; } ?> value="<?php echo $feecategory->id . "-" . $fee_value->id; ?>"><?php echo $fee_value->code; ?></option>
                                                        <?php }
                                                    } ?>
                                                </optgroup>
                                            <?php } ?>
                                        </select>
                                        <span class="text-danger"><?php echo form_error('feegroup_id'); ?></span>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label><?php echo $this->lang->line('class'); ?></label><small class="req"> *</small>
                                        <select id="class_id" name="class_id" class="form-control">
                                            <option value=""><?php echo $this->lang->line('select'); ?></option>
                                            <?php foreach ($classlist as $class) { ?>
                                                <option value="<?php echo $class['id'] ?>" <?php if (set_value('class_id') == $class['id']) { echo "selected=selected"; } ?>><?php echo $class['class'] ?></option>
                                            <?php $count++; } ?>
                                        </select>
                                        <span class="text-danger"><?php echo form_error('class_id'); ?></span>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label><?php echo $this->lang->line('section'); ?></label><small class="req"> *</small>
                                        <select id="section_id" name="section_id" class="form-control">
                                            <option value=""><?php echo $this->lang->line('select'); ?></option>
                                        </select>
                                        <span class="text-danger"><?php echo form_error('section_id'); ?></span>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <button type="submit" class="btn btn-sm btn-primary pull-right"><i class="fa fa-search"></i> <?php echo $this->lang->line('search'); ?></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>

                    <?php if (!isset($search_type) || $search_type != 'by_date') { if (isset($student_due_fee)) { ?>
                    <div id="duefee">
                        <div class="box-header ptbnull"></div>
                        <div class="box-header ptbnull">
                            <h3 class="box-title titlefix"><i class="fa fa-users"></i> <?php echo $this->lang->line('student_lists'); ?></h3>
                        </div>
                        <div class="box-body table-responsive">
                            <div class="row print">
                                <div class="col-md-12">
                                    <div class="col-md-4"><b><?php echo $this->lang->line('class'); ?>: </b> <span class="cls"></span></div>
                                    <div class="col-md-4"><b><?php echo $this->lang->line('fees_category'); ?>: </b><span class="fcat"></span></div>
                                    <div class="col-md-4"><b><?php echo $this->lang->line('fees_type'); ?>: </b> <span class="ftype"></span></div>
                                </div>
                            </div>
                            <div class="download_label"><?php echo $this->lang->line('student_lists'); ?></div>
                            <table class="table table-striped table-bordered table-hover example">
                                <thead>
                                    <tr>
                                        <th><?php echo $this->lang->line('admission_no'); ?></th>
                                        <th><?php echo $this->lang->line('roll_no'); ?></th>
                                        <th><?php echo $this->lang->line('student'); ?> <?php echo $this->lang->line('name'); ?></th>
                                        <th><?php echo $this->lang->line('mobileno'); ?></th>
                                        <th><?php echo $this->lang->line('due_date'); ?></th>
                                        <th class="text text-right"><?php echo $this->lang->line('amount'); ?> <span><?php echo "(" . $currency_symbol . ")"; ?></span></th>
                                        <th class="text text-right"><?php echo $this->lang->line('deposit'); ?> <span><?php echo "(" . $currency_symbol . ")"; ?></span></th>
                                        <th class="text text-right"><?php echo $this->lang->line('discount'); ?> <span><?php echo "(" . $currency_symbol . ")"; ?></span></th>
                                        <th class="text text-right"><?php echo $this->lang->line('fine'); ?> <span><?php echo "(" . $currency_symbol . ")"; ?></span></th>
                                        <th class="text text-right"><?php echo $this->lang->line('balance'); ?> <span><?php echo "(" . $currency_symbol . ")"; ?></span></th>
                                        <th class="text text-right">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($student_due_fee)) { ?>
                                        <tr><td colspan="11" class="text-danger text-center"><?php echo $this->lang->line('no_record_found'); ?></td></tr>
                                    <?php } else {
                                        $count = 1;
                                        foreach ($student_due_fee as $student) { ?>
                                            <tr>
                                                <td><?php echo $student['admission_no']; ?></td>
                                                <td><?php echo $student['roll_no']; ?></td>
                                                <td><?php echo $student['firstname'] . " " . $student['lastname']; ?></td>
                                                <td><?php echo $student['mobileno']; ?></td>
                                                <td><?php echo date($this->customlib->getSchoolDateFormat(), $this->customlib->dateyyyymmddTodateformat($student['due_date'])); ?></td>
                                                <td class="text text-right"><?php echo number_format($student['amount'], 2, '.', ''); ?></td>
                                                <td class="text text-right"><?php echo number_format($student['amount_detail'], 2, '.', ''); ?></td>
                                                <td class="text text-right"><?php echo number_format($student['amount_discount'], 2, '.', ''); ?></td>
                                                <td class="text text-right"><?php echo number_format($student['amount_fine'], 2, '.', ''); ?></td>
                                                <td class="text text-right"><?php
                                                    $previous_balance = isset($student['previous_balance']) ? $student['previous_balance'] : 0;
                                                    echo number_format(($student['amount'] - ($student['amount_detail'] + $student['amount_discount'])), 2, '.', '');
                                                ?></td>
                                                <td class="text text-right">
                                                    <a href="tel:<?php echo $student['mobileno']; ?>" class="btn btn-xs btn-success"><i class="fa fa-phone"></i> Call Now</a>
                                                    <button type="button" class="btn btn-xs btn-warning btn-month-detail"
                                                        data-name="<?php echo htmlspecialchars($student['firstname'].' '.$student['lastname']); ?>"
                                                        data-admno="<?php echo $student['admission_no']; ?>"
                                                        data-student-session-id="<?php echo $student['student_session_id']; ?>"
                                                        data-class-id="<?php echo $selected_class_id; ?>"
                                                        data-section-id="<?php echo $selected_section_id; ?>"
                                                        data-feegroup-id="<?php echo $selected_feegroup_id; ?>"
                                                        data-previous-balance="<?php echo number_format($previous_balance, 2, '.', ''); ?>">
                                                        <i class="fa fa-eye"></i> Due Fees
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php } $count++; } ?>
                                </tbody>
                            </table>
                            <div class="row" style="margin:10px 0">
                                <div class="col-md-12">
                                    <button type="button" class="btn btn-success btn-sm" id="downloadCSV"><i class="fa fa-download"></i> Download CSV</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php } } ?>
                </div><!-- /.box box-primary -->
            </div>
        </div>

        <!-- Box 2: Date + Class + Section (NEW) -->
        <div class="row" style="margin-top:15px;">
            <div class="col-md-12">
                <div class="box box-info">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-calendar"></i> Select Criteria (By Date)</h3>
                    </div>
                    <form action="<?php echo site_url('studentfee/feesearch') ?>" method="post" accept-charset="utf-8">
                        <div class="box-body">
                            <?php echo $this->customlib->getCSRF(); ?>
                            <input type="hidden" name="search_type" value="by_date">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Due Date</label><small class="req"> *</small>
                                        <input type="date" name="due_date" id="due_date" class="form-control"
                                            value="<?php echo isset($selected_due_date) ? htmlspecialchars($selected_due_date) : date('Y-m-d'); ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label><?php echo $this->lang->line('class'); ?></label><small class="req"> *</small>
                                        <select id="class_id_date" name="class_id" class="form-control">
                                            <option value=""><?php echo $this->lang->line('select'); ?></option>
                                    <?php
                    $sel_class_date   = isset($selected_class_id) ? $selected_class_id : '';
                    $sel_section_date = isset($selected_section_id) ? $selected_section_id : '';
                    $sel_due_date     = isset($selected_due_date) ? $selected_due_date : date('Y-m-d');
                    foreach ($classlist as $cls) { ?>
                                                <option value="<?php echo $cls['id']; ?>" <?php if($sel_class_date==$cls['id']) echo 'selected'; ?>><?php echo $cls['class']; ?></option>
                            <?php } ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label><?php echo $this->lang->line('section'); ?></label><small class="req"> *</small>
                                        <select id="section_id_date" name="section_id" class="form-control">
                                            <option value=""><?php echo $this->lang->line('select'); ?></option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <button type="submit" class="btn btn-sm btn-info pull-right"><i class="fa fa-search"></i> <?php echo $this->lang->line('search'); ?></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>

                    <?php if (isset($search_type) && $search_type == 'by_date') { ?>
                    <div class="box-body table-responsive">
                        <div class="row" style="margin:0 0 8px 0;">
                            <div class="col-md-12">
                                <button type="button" class="btn btn-warning btn-sm" id="printByDate"><i class="fa fa-print"></i> Print</button>
                            </div>
                        </div>
                        <div class="download_label"><?php echo $this->lang->line('student_lists'); ?></div>
                        <table class="table table-striped table-bordered table-hover example2">
                            <thead>
                                <tr>
                                    <th><?php echo $this->lang->line('admission_no'); ?></th>
                                    <th><?php echo $this->lang->line('roll_no'); ?></th>
                                    <th><?php echo $this->lang->line('student'); ?> <?php echo $this->lang->line('name'); ?></th>
                                    <th><?php echo $this->lang->line('mobileno'); ?></th>
                                    <th><?php echo $this->lang->line('due_date'); ?></th>
                                    <th class="text text-right"><?php echo $this->lang->line('amount'); ?> (<?php echo $currency_symbol; ?>)</th>
                                    <th class="text text-right"><?php echo $this->lang->line('deposit'); ?> (<?php echo $currency_symbol; ?>)</th>
                                    <th class="text text-right"><?php echo $this->lang->line('discount'); ?> (<?php echo $currency_symbol; ?>)</th>
                                    <th class="text text-right"><?php echo $this->lang->line('fine'); ?> (<?php echo $currency_symbol; ?>)</th>
                                    <th class="text text-right"><?php echo $this->lang->line('balance'); ?> (<?php echo $currency_symbol; ?>)</th>
                                    <th class="text text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($student_due_fee)) { ?>
                                    <tr><td colspan="11" class="text-danger text-center"><?php echo $this->lang->line('no_record_found'); ?></td></tr>
                                <?php } else {
                                    foreach ($student_due_fee as $student) {
                                        $balance = $student['amount'] - ($student['amount_detail'] + $student['amount_discount']);
                                        if ($balance <= 0) continue;
                                    ?>
                                    <tr>
                                        <td><?php echo $student['admission_no']; ?></td>
                                        <td><?php echo $student['roll_no']; ?></td>
                                        <td><?php echo $student['firstname'] . ' ' . $student['lastname']; ?></td>
                                        <td><?php echo $student['mobileno']; ?></td>
                                        <td><?php echo !empty($student['due_date']) ? date($this->customlib->getSchoolDateFormat(), $this->customlib->dateyyyymmddTodateformat($student['due_date'])) : '-'; ?></td>
                                        <td class="text text-right"><?php echo number_format($student['amount'], 2, '.', ''); ?></td>
                                        <td class="text text-right"><?php echo number_format($student['amount_detail'], 2, '.', ''); ?></td>
                                        <td class="text text-right"><?php echo number_format($student['amount_discount'], 2, '.', ''); ?></td>
                                        <td class="text text-right"><?php echo number_format($student['amount_fine'], 2, '.', ''); ?></td>
                                        <td class="text text-right"><?php echo number_format($balance, 2, '.', ''); ?></td>
                                        <td class="text text-right">
                                            <a href="tel:<?php echo $student['mobileno']; ?>" class="btn btn-xs btn-success"><i class="fa fa-phone"></i> Call Now</a>
                                            <button type="button" class="btn btn-xs btn-warning btn-month-detail"
                                                data-name="<?php echo htmlspecialchars($student['firstname'].' '.$student['lastname']); ?>"
                                                data-admno="<?php echo $student['admission_no']; ?>"
                                                data-student-session-id="<?php echo $student['student_session_id']; ?>"
                                                data-class-id="<?php echo $selected_class_id; ?>"
                                                data-section-id="<?php echo $selected_section_id; ?>"
                                                data-feegroup-id=""
                                                data-due-date="<?php echo $selected_due_date; ?>"
                                                data-previous-balance="0">
                                                <i class="fa fa-eye"></i> Due Fees
                                            </button>
                                        </td>
                                    </tr>
                                    <?php } } ?>
                            </tbody>
                        </table>
                    </div>
                    <?php } ?>

                </div><!-- /.box box-info -->
            </div>
        </div>

    </section>
</div>

<!-- Month Detail Modal -->
<div class="modal fade" id="monthDetailModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document" style="width:95%;max-width:900px;margin-top:30px;margin-left:auto;margin-right:auto;">
    <div class="modal-content" style="overflow:hidden;">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Month Fee Detail</h4>
      </div>
      <div class="modal-body" style="padding:10px;overflow-x:auto;-webkit-overflow-scrolling:touch;">
        <p><strong>Student:</strong> <span id="modal_name"></span> &nbsp; <strong>Adm#:</strong> <span id="modal_admno"></span></p>
        <div class="row" style="margin:0 0 10px 0;">
          <div class="col-sm-4" style="padding:6px;border:1px solid #ddd;background:#fff8e1;">
            <strong>Previous Balance:</strong>
            <span id="modal_previous_balance" class="text-danger pull-right"></span>
          </div>
          <div class="col-sm-4" style="padding:6px;border:1px solid #ddd;background:#f5f5f5;">
            <strong>Current Due:</strong>
            <span id="modal_current_balance" class="pull-right"></span>
          </div>
          <div class="col-sm-4" style="padding:6px;border:1px solid #ddd;background:#e8f5e9;">
            <strong>Total Balance:</strong>
            <span id="modal_grand_balance" class="text-danger pull-right"></span>
          </div>
        </div>
        <div style="overflow-x:auto;-webkit-overflow-scrolling:touch;width:100%;display:block;">
        <table class="table table-bordered table-sm" style="min-width:700px;white-space:nowrap;">
          <thead><tr><th>Month</th><th>Due Date</th><th>Amount</th><th>Deposit</th><th>Discount</th><th>Fine</th><th>Balance</th></tr></thead>
          <tbody id="modal_tbody"></tbody>
          <tfoot><tr><td colspan="6"><strong>Total Balance</strong></td><td id="modal_total_balance" class="text-danger"></td></tr></tfoot>
        </table>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="printMonthDetail"><i class="fa fa-print"></i> Print</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
    var base_url = '<?php echo base_url() ?>';

    function getSectionByClass(class_id, section_id) {
        if (class_id != "" && section_id != "") {
            $('#section_id').html("");
            var div_data = '<option value=""><?php echo $this->lang->line('select'); ?></option>';
            $.ajax({
                type: "GET",
                url: base_url + "sections/getByClass",
                data: {'class_id': class_id},
                dataType: "json",
                success: function (data) {
                    $.each(data, function (i, obj) {
                        var sel = (section_id == obj.section_id) ? "selected=selected" : "";
                        div_data += "<option value=" + obj.section_id + " " + sel + ">" + obj.section + "</option>";
                    });
                    $('#section_id').append(div_data);
                }
            });
        }
    }

    $(document).ready(function () {
        var class_id   = $('#class_id').val();
        var section_id = '<?php echo set_value('section_id') ?>';
        getSectionByClass(class_id, section_id);

        $(document).on('change', '#class_id', function () {
            $('#section_id').html('<option value=""><?php echo $this->lang->line('select'); ?></option>');
            var cid = $(this).val();
            $.ajax({
                type: "GET", url: base_url + "sections/getByClass",
                data: {'class_id': cid}, dataType: "json",
                success: function (data) {
                    $.each(data, function (i, obj) {
                        $('#section_id').append("<option value=" + obj.section_id + ">" + obj.section + "</option>");
                    });
                }
            });
        });

        var date_format = '<?php echo strtr($this->customlib->getSchoolDateFormat(), ['d' => 'dd', 'm' => 'mm', 'Y' => 'yyyy']) ?>';

        // Section load for date form
        var sel_section_date = '<?php echo isset($selected_section_id) ? $selected_section_id : ""; ?>';
        if ($('#class_id_date').val() != '') {
            $.ajax({
                type: 'GET', url: base_url + 'sections/getByClass',
                data: {class_id: $('#class_id_date').val()}, dataType: 'json',
                success: function (data) {
                    $.each(data, function (i, obj) {
                        var sel = (sel_section_date == obj.section_id) ? 'selected' : '';
                        $('#section_id_date').append('<option value=' + obj.section_id + ' ' + sel + '>' + obj.section + '</option>');
                    });
                }
            });
        }
        $(document).on('change', '#class_id_date', function () {
            $('#section_id_date').html('<option value=""><?php echo $this->lang->line('select'); ?></option>');
            var cid = $(this).val();
            if (cid == '') return;
            $.ajax({
                type: 'GET', url: base_url + 'sections/getByClass',
                data: {class_id: cid}, dataType: 'json',
                success: function (data) {
                    $.each(data, function (i, obj) {
                        $('#section_id_date').append('<option value=' + obj.section_id + '>' + obj.section + '</option>');
                    });
                }
            });
        });
    });
</script>

<script type="text/javascript">
$(document).ready(function () {

    $(document).on('click', '.btn-month-detail', function () {
        var name               = $(this).data('name');
        var admno              = $(this).data('admno');
        var student_session_id = $(this).data('student-session-id');
        var class_id           = $(this).data('class-id');
        var section_id         = $(this).data('section-id');
        var feegroup_id        = $(this).data('feegroup-id');
        var previous_balance   = parseFloat($(this).data('previous-balance')) || 0;
        var due_date           = $(this).data('due-date') || '';

        $('#modal_name').text(name);
        $('#modal_admno').text(admno);
        $('#modal_previous_balance').text(previous_balance.toFixed(2));
        $('#modal_current_balance').text('0.00');
        $('#modal_grand_balance').text(previous_balance.toFixed(2));
        $('#modal_tbody').html('<tr><td colspan="7" class="text-center">Loading...</td></tr>');
        $('#monthDetailModal').modal('show');

        $.ajax({
            type: 'POST', url: base_url + 'studentfee/getStudentMonthDetail',
            data: { feegroup_id: feegroup_id, class_id: class_id, section_id: section_id, student_session_id: student_session_id, due_date: due_date },
            dataType: 'json',
            success: function (res) {
                var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
                var html = '', totalBalance = 0;
                if (res.status === 'success' && res.data.length > 0) {
                    $.each(res.data, function (i, row) {
                        var monthName = row.due_date ? (months[new Date(row.due_date).getMonth()] + ' ' + new Date(row.due_date).getFullYear()) : (row.fee_code || '-');
                        totalBalance += parseFloat(row.balance);
                        html += '<tr><td>' + monthName + ' (' + row.fee_code + ' - ' + (row.fee_group_name || '') + ')</td><td>' + (row.due_date || '-') + '</td><td>' + parseFloat(row.amount).toFixed(2) + '</td><td>' + parseFloat(row.deposit).toFixed(2) + '</td><td>' + parseFloat(row.discount).toFixed(2) + '</td><td>' + parseFloat(row.fine).toFixed(2) + '</td><td class="text-danger"><strong>' + parseFloat(row.balance).toFixed(2) + '</strong></td></tr>';
                    });
                } else {
                    html = '<tr><td colspan="7" class="text-center text-success">No pending balance</td></tr>';
                }
                var currentBalance = Math.max(totalBalance - previous_balance, 0);
                $('#modal_tbody').html(html);
                $('#modal_current_balance').text(currentBalance.toFixed(2));
                $('#modal_grand_balance').text(totalBalance.toFixed(2));
                $('#modal_total_balance').text(totalBalance.toFixed(2));
            },
            error: function () {
                $('#modal_tbody').html('<tr><td colspan="7" class="text-danger text-center">Error loading data</td></tr>');
            }
        });
    });

    $('#printMonthDetail').on('click', function () {
        var win = window.open('', '_blank');
        win.document.write('<html><head><title>Month Fee Detail</title><link rel="stylesheet" href="' + base_url + 'backend/bootstrap/css/bootstrap.min.css"><style>body{padding:20px;}</style></head><body>');
        win.document.write('<h4>Month Fee Detail</h4><p><strong>Student:</strong> ' + $('#modal_name').text() + ' &nbsp; <strong>Adm#:</strong> ' + $('#modal_admno').text() + '</p>');
        win.document.write('<p><strong>Previous Balance:</strong> ' + $('#modal_previous_balance').text() + ' &nbsp; <strong>Current Due:</strong> ' + $('#modal_current_balance').text() + ' &nbsp; <strong>Total Balance:</strong> ' + $('#modal_grand_balance').text() + '</p>');
        win.document.write($('#monthDetailModal .modal-body table')[0].outerHTML);
        win.document.write('</body></html>');
        win.document.close();
        setTimeout(function(){ win.print(); }, 500);
    });

    $('#printByDate').on('click', function () {
        var win = window.open('', '_blank');
        var date = '<?php echo isset($selected_due_date) ? htmlspecialchars($selected_due_date) : ""; ?>';
        win.document.write('<html><head><title>Due Fee Report</title><link rel="stylesheet" href="' + base_url + 'backend/bootstrap/css/bootstrap.min.css"><style>body{padding:20px;}th,td{white-space:nowrap;}</style></head><body>');
        win.document.write('<h4>Due Fee Report &mdash; Date: ' + date + '</h4>');
        win.document.write(document.querySelector('table.example2').outerHTML);
        win.document.write('</body></html>');
        win.document.close();
        setTimeout(function(){ win.print(); }, 500);
    });

    $('#downloadCSV').on('click', function () {
        var rows = [], headers = [];
        $('table.example thead tr th').each(function () { headers.push('"' + $(this).text().trim() + '"'); });
        rows.push(headers.join(','));
        $('table.example tbody tr').each(function () {
            var tds = $(this).find('td'), cols = [];
            tds.each(function (i) { if (i < tds.length - 1) cols.push('"' + $(this).text().trim() + '"'); });
            if (cols.length > 0) rows.push(cols.join(','));
        });
        var blob = new Blob([rows.join('\n')], { type: 'text/csv;charset=utf-8;' });
        var a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = 'fee_balance_report.csv';
        document.body.appendChild(a); a.click(); document.body.removeChild(a);
    });

});
</script>
