<style type="text/css">
    .nav-tabs-custom>.nav-tabs>li.active {
        border-top-color: #faa21c;
    }
</style>
<divd?php
$currency_symbol = $this->customlib->getSchoolCurrencyFormat();
?>
<div class="content-wrapper" style="min-height: 946px;">
    <section class="content-header">
        <h1>
            <i class="fa fa-line-chart"></i> <?php echo $this->lang->line('reports'); ?> <small> </small>   </h1>
											<a href="<?php  echo base_url(); ?>uniformreport" class="col-md pull-right">Uniform Report</a>
								<b style="padding-left:5px;padding-right:5px;"class="pull-right"> | </b>												 
								 <a href="<?php  echo base_url(); ?>admin/payroll/payrollreport" class="col-md pull-right">Payroll Report</a> 
								 <b style="padding-left:5px;padding-right:5px;"class="pull-right"> | </b>
								 <a href="<?php  echo base_url(); ?>admin/transaction/searchtransaction" class="col-md pull-right">Transaction Report</a>	
								 <b style="padding-left:5px;padding-right:5px;"class="pull-right"> | </b>
								 <a href="<?php  echo base_url(); ?>admin/transaction/studentacademicreport" class="col-md pull-right">Balance Fees Report</a>	
								 <b style="padding-left:5px;padding-right:5px;"class="pull-right"> | </b>
								 <a href="<?php  echo base_url(); ?>studentfee/reportbyname" class="col-md pull-right">Fee Statement</a>	
								 <b style="padding-left:5px;padding-right:5px;"class="pull-right"> | </b>
								 <a href="<?php  echo base_url(); ?>admin/users/admissionreport" class="col-md pull-right">Learner History</a>	
								 <b style="padding-left:5px;padding-right:5px;"class="pull-right"> | </b>
								 <a href="<?php  echo base_url(); ?>student/studentreport" class="col-md pull-right">Learner Report</a>
                                 <a href="<?php  echo base_url(); ?>admin/transaction/searchtransaction" class="col-md pull-right">Fees Summary Report</a>	
								 <b style="padding-left:5px;padding-right:5px;"class="pull-right"> | </b>
    </section>
    <!-- Main content -->
    <section class="content">
        <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('outstanding_fees'); ?></h3>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-12">
                                <form role="form" action="<?php echo site_url('admin/outstanding/searchtransaction') ?>" method="post" class="form-horizontal">
                                    <?php echo $this->customlib->getCSRF(); ?> 
                                    <div class="form-group">
                                    <div class="col-sm-4">
                                        <label>Report Type</label>
                                        <select id="report_type" name="report_type" class="form-control" onchange="document.getElementById('reportForm').submit()">
                                            <option value="summary" <?= ($report_type == 'summary') ? 'selected' : '' ?>>Summary</option>
                                            <option value="detailed" <?= ($report_type == 'detailed') ? 'selected' : '' ?>>Detailed</option>
                                        </select>
                                    </div>

                                        <div class="col-sm-4">
                                            <label><?php echo $this->lang->line('date_from'); ?></label>
                                            <input autofocus="" id="datefrom" name="date_from" placeholder="" type="text" class="form-control date"  value="<?php echo set_value('date_from', date($this->customlib->getSchoolDateFormat())); ?>" readonly="readonly"/>
                                            <span class="text-danger"><?php echo form_error('class_id'); ?></span>
                                        </div>
                                        <div class="col-sm-4">
                                            <label><?php echo $this->lang->line('date_to'); ?></label>
                                            <input id="dateto" name="date_to" placeholder="" type="text" class="form-control date"  value="<?php echo set_value('date_to', date($this->customlib->getSchoolDateFormat())); ?>" readonly="readonly"/>
                                        </div>
                                </div>  
                                    <div class="form-group">
                                        <div class="col-sm-12">
                                            <button type="submit" name="search" value="search_filter" class="btn btn-primary btn-sm checkbox-toggle pull-right"><i class="fa fa-search"></i> <?php echo $this->lang->line('search'); ?></button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <?php
                if (isset($feelist)) { ?>
                    <div class="box bozero">
                        <h3 class="titless pull-left"><i class="fa fa-money"></i> <?php echo $exp_title; ?></h3>
                        <div class="nav-tabs-custom">    
                            <ul class="nav nav-tabs pull-right">  
                                <?php if ($this->module_lib->hasActive('fees_collection')) { ?>                     
                                    <li class="active"><a href="#tab_students" data-toggle="tab"><?php echo $this->lang->line('fees_collection_details'); ?></a></li>
                                <?php } ?>                  
                            </ul>
                            <div class="box-body table-responsive">     
                                <div class="tab-content">
                                    <div class="tab-pane active table-responsive" id="tab_students">
                                        <div class="download_label"><?php echo $exp_title; ?></div>
                                <div>
                                    <?php if ($report_type == 'summary') { ?>
                                        <!-- Summary Report -->
                                        <table class="table table-striped table-bordered" style="width: 100%; margin: 0 auto;">
                                        <thead>
                                            <tr>
                                                <th style="width:20%;">Date</th>
                                                <th style="width:25%;">Student Name</th>
                                                <th style="width:20%;">Class</th>      
                                                <th style="width:25%; text-align:right;">Owing Balance (USD)</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $grand_total_invoiced = 0;
                                            $grand_total_paid = 0;
                                            $grand_total_balance = 0;  
                                            // Group fees by student
                                            $students = [];
                                            foreach ($feelist as $fee) {
                                                if ($fee['is_total_row'] == 1) continue;
                                                
                                                $studentId = $fee['student_session_id'];
                                                if (!isset($students[$studentId])) {
                                                    $students[$studentId] = [
                                                        'name' => $fee['firstname'] . ' ' . $fee['lastname'],
                                                        'class' => $fee['class_name'] . ' ' . $fee['section_name'],
                                                        'invoiced' => 0,
                                                        'discount' => 0,
                                                        'paid' => 0,
                                                        'latest_date' => '',
                                                        'invoices' => []
                                                    ];
                                                }
                                                
                                                // Get the original paid amount
                                                $original_paid = isset($fee['amount_paid']) ? (float)$fee['amount_paid'] : 0;
                                                
                                                // Get payment mode (assuming it's available in $fee)
                                                $payment_mode = $fee['payment_mode'] ?? 'USD'; // Default to USD if not specified
                                                
                                                // Convert the amount if needed
                                                if ($payment_mode !== 'USD' && $original_paid > 0) {
                                                    // Fetch the exchange rate for the payment mode
                                                    $this->db->select('foreign_rate');
                                                    $this->db->from('bank_rates');
                                                    $this->db->where('foreign_currency', $payment_mode);
                                                    $query_rate = $this->db->get();
                                                    $rate = $query_rate->row();
                                                    
                                                    $foreign_rate = $rate->foreign_rate ?? 1; // Default to 1 if no rate found
                                                    
                                                    // Convert to USD equivalent
                                                    $paid = $original_paid / $foreign_rate;
                                                } else {
                                                    $paid = $original_paid; // No conversion needed for USD
                                                }  
                                                $students[$studentId]['invoiced'] += $fee['fee_amount'];
                                                $students[$studentId]['paid'] += $paid;
                                                $students[$studentId]['discount'] += $fee['amount_discount'];
                                                
                                                // Track latest date
                                                if (empty($students[$studentId]['latest_date']) || 
                                                    strtotime($fee['created_at']) > strtotime($students[$studentId]['latest_date'])) {
                                                    $students[$studentId]['latest_date'] = $fee['created_at'];
                                                }
                                                
                                                // Track individual invoices for reference
                                                $students[$studentId]['invoices'][] = [
                                                    'invoice_number' => $fee['invoice_number'],
                                                    'amount' => $fee['fee_amount'],
                                                    'paid' => $paid,
                                                    'discount' => $fee['amount_discount'],
                                                    'date' => $fee['created_at']
                                                ];
                                            }
                                            
                                            // Display each student's summary only if balance > 0
                                                foreach ($students as $studentId => $student):
                                                    // First calculate the balance
                                                    $balance = $student['invoiced'] - ($student['paid'] + $student['discount']);
                                                    
                                                    // Skip students with balance <= 0 (using a small epsilon to account for floating point precision)
                                                    if ($balance == 0 || $balance < 0) continue; // Using 0.009 to account for rounding differences
                                                    
                                                    $date = date('m-d-Y', strtotime($student['latest_date']));
                                                    
                                                    // Only add to grand totals if we're actually displaying this student
                                                    $grand_total_invoiced += $student['invoiced'];
                                                    $grand_total_paid += $student['paid'];
                                                    $grand_total_balance += $balance;
                                                ?>
                                            <tr>
                                                <td><?= htmlspecialchars($date) ?></td>
                                                <td><?= htmlspecialchars($student['name']) ?></td>
                                                <td><?= htmlspecialchars($student['class']) ?></td>
                                                <td style="text-align:right;"><?= number_format($balance, 2) ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                            
                                            <!-- Grand Total Row -->
                                            <tr style="font-weight:bold; background-color:#f5f5f5;">
                                                <td></td>
                                                <td></td>
                                                <td>GRAND TOTAL</td>
                                                <td style="text-align:right;"><?= number_format( $grand_total_balance, 2) ?></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                        
                                        <!-- Summary Print Button -->
                                        <div class="text-right" style="margin-top: 20px;">
                                            <button id="printStatementBtwn" class="btn btn-info printInv"  
                                                    data-date_from="<?= htmlspecialchars($date_from2) ?>"  
                                                    data-date_to="<?= htmlspecialchars($date_to2) ?>"                          
                                                    data-report_type="<?= htmlspecialchars($report_type) ?>" 
                                                    title="<?= htmlspecialchars($this->lang->line('print')) ?>">
                                                <i class="fa fa-print"></i> Print Statement
                                            </button>
                                        </div>
                                    <?php } else { ?>
                                        <!-- Detailed Report -->
                                        <div>
                                         <?php
                                            // Initialize variables
                                            $groupedData = array();
                                            $processedInvoices = array();
                                            $grandTotalSales = 0;
                                            $grandTotalPaid = 0;
                                            $grandTotalBalance = 0;
                                            // First, fetch all exchange rates at once to minimize database queries
                                            $this->db->select('foreign_currency, foreign_rate');
                                            $exchangeRatesQuery = $this->db->get('bank_rates');
                                            $exchangeRates = array();
                                            foreach ($exchangeRatesQuery->result() as $rate) {
                                                $exchangeRates[$rate->foreign_currency] = $rate->foreign_rate;
                                            }
                                            // Group data by student
                                            foreach ($feelist as $rows) {
                                                // Skip the grand total row and duplicates
                                                if (($rows['is_total_row'] ?? false) || isset($processedInvoices[$rows['id']])) {
                                                    continue;
                                                }
                                                $processedInvoices[$rows['id']] = true;
                                                
                                                $studentKey = $rows['student_session_id'] ?? $rows['id'];
                                                if (!isset($groupedData[$studentKey])) {
                                                    $groupedData[$studentKey] = array(
                                                        'name' => ($rows['firstname'] ?? '') . ' ' . ($rows['lastname'] ?? ''),
                                                        'class' => $rows['class_name'] ?? 'N/A',
                                                        'section' => $rows['section_name'] ?? 'N/A',
                                                        'transactions' => array(),
                                                        'total_invoiced' => 0,
                                                        'total_paid' => 0,
                                                        'total_discount' => 0,
                                                        'total_balance' => 0
                                                    );
                                                }
                                                
                                                $amount = $rows['fee_amount'] ?? 0;
                                                $amount_discount = $rows['amount_discount'];
                                                $original_paid = $rows['amount_paid'] ?? 0;
                                                $payment_mode = $rows['payment_mode'] ?? 'USD'; // Default to USD if not specified                                               
                                                // Convert payment to USD if needed
                                                if ($payment_mode !== 'USD' && $original_paid > 0) {
                                                    $foreign_rate = $exchangeRates[$payment_mode] ?? 1;
                                                    $paid = $original_paid / $foreign_rate;
                                                } else {
                                                    $paid = $original_paid;
                                                }
                                                $balance = $amount - ($paid + $amount_discount);
                                                if ($balance == 0 || $balance < 0) continue; 
                                        
                                                $groupedData[$studentKey]['transactions'][] = array(
                                                    'date' => $rows['created_at'],
                                                    'invoice_number' => $rows['invoice_number'],
                                                    'fee_group_name' => $rows['fee_group_name'],
                                                    'discount' => $rows['amount_discount'],
                                                    'amount' => $amount,
                                                    'paid' => $paid,
                                                    'discount' =>$amount_discount,
                                                    'balance' => $balance,
                                                    'payment_mode' => $payment_mode,
                                                    'original_paid' => $original_paid
                                                );                                               
                                                $groupedData[$studentKey]['total_invoiced'] += $amount;
                                                $groupedData[$studentKey]['total_paid'] += $paid;
                                                $groupedData[$studentKey]['total_balance'] += $balance;
                                                $groupedData[$studentKey]['total_discount'] += $amount_discount; 
                                                $grandTotalSales += $amount;
                                                $grandTotalPaid += $paid;
                                                $grandTotalDiscount += $amount_discount;
                                                $grandTotalBalance += $balance;
                                            }
                                            // Remove students with zero or negative balance
                                            foreach ($groupedData as $key => $studentData) {
                                                if ($studentData['total_balance'] <= 0) {
                                                    unset($groupedData[$key]);
                                                }
                                            }
                                           
                                           foreach ($groupedData as $studentId => $studentData): ?>
                                                
                                                <div class="student-section" style="margin-top: 30px; page-break-inside: avoid;">
                                                    <!-- Student Header -->
                                                    <h4 style="margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 8px;">
                                                        <strong>Student:</strong> <?= htmlspecialchars($studentData['name']) ?>
                                                        &nbsp; | &nbsp;
                                                        <strong>Class:</strong> <?= htmlspecialchars($studentData['class']) ?>
                                                        &nbsp; | &nbsp;
                                                        <strong>Section:</strong> <?= htmlspecialchars($studentData['section']) ?>
                                                    </h4>

                                                    <!-- Student's Fees Table -->
                                                    <table class="table table-striped table-bordered" style="width: 100%; margin-bottom: 15px;">
                                                        <thead>
                                                            <tr>
                                                                <th style="width: 15%;">Date</th>
                                                                <th style="width: 20%;">Fee Group</th>
                                                                <th style="width: 10%;">Invoice#</th>
                                                                <th style="width: 13%;" class="text-right">Amount (USD)</th>
                                                                <th style="width: 13%;" class="text-right">Amount Paid (USD)</th>
                                                                <th style="width: 13%;" class="text-right">Discount (USD)</th>
                                                                <th style="width: 18%;" class="text-right">Owing Balance (USD)</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($studentData['transactions'] as $txn): ?>
                                                                <tr>
                                                                    <td><?= date($this->customlib->getSchoolDateFormat(), strtotime($txn['date'])) ?></td>
                                                                    <td><?= htmlspecialchars($txn['fee_group_name']) ?></td>
                                                                    <td><?= htmlspecialchars($txn['invoice_number']) ?></td>
                                                                    <td class="text-right"><?= number_format($txn['amount'], 2) ?></td>
                                                                    <td class="text-right"><?= number_format($txn['paid'], 2) ?></td>
                                                                    <td class="text-right"><?= number_format($txn['discount'], 2) ?></td>
                                                                    <td class="text-right"><?= number_format($txn['balance'], 2) ?></td>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                        <tfoot>
                                                            <tr style="font-weight: bold; background-color: #f5f5f5;">
                                                                <td colspan="3" class="text-right">Student Totals:</td>
                                                                <td class="text-right"><?= number_format($studentData['total_invoiced'], 2) ?></td>
                                                                <td class="text-right"><?= number_format($studentData['total_paid'], 2) ?></td>
                                                                 <td class="text-right"><?= number_format($studentData['total_discount'], 2) ?></td>
                                                                <td class="text-right"><?= number_format($studentData['total_balance'], 2) ?></td>
                                                            </tr>
                                                        </tfoot>
                                                    </table>                
                                            <!-- Student Total -->
                                            <div style="text-align: center; margin-top: 8px;">
                                                <p>
                                                    <strong>Closing Balance For <?php echo htmlspecialchars($studentData['name']); ?>:
                                                    USD <?= number_format($studentData['total_balance'], 2) ?></strong>
                                                </p>
                                            </div>
                                                </div>
                                        <?php endforeach; ?>   
                                            <!-- Grand Total Section -->
                                            <div style="margin-top: 30px;">
                                                <table class="table table-bordered" style="width: 100%;">
                                                    <tr style="background-color: #e0e0e0; font-weight: bold;">
                                                    <td style="width: 15%;"></td>
                                                    <td style="width: 15%;"></td>
                                                    <td style="width: 15%;" class="text-right">GRAND TOTAL:</td>
                                                    <td style="width: 13%;" class="text-right"><?= number_format($grandTotalSales, 2) ?></td>
                                                    <td style="width: 13%;" class="text-right"><?= number_format($grandTotalPaid, 2) ?></td>
                                                    <td style="width: 13%;" class="text-right"><?= number_format($grandTotalDiscount, 2) ?></td>
                                                    <td style="width: 18%;" class="text-right"><?= number_format($grandTotalBalance, 2) ?></td>
                                                    </tr>
                                                </table>
                                            </div>
                                            <!-- Detailed Print Button -->
                                            <div class="text-right" style="margin-top: 20px;">
                                                    <button id="printStatementBtn" class="btn btn-info printInv"  
                                                            data-date_from="<?= htmlspecialchars($date_from2) ?>"  
                                                            data-date_to="<?= htmlspecialchars($date_to2) ?>"                          
                                                            data-report_type="<?= htmlspecialchars($report_type) ?>" 
                                                            title="<?= htmlspecialchars($this->lang->line('print')) ?>">
                                                        <i class="fa fa-print"></i> Print Statement
                                                    </button>
                                                </div>
                                            </div>
                                                    <?php } ?>
                                                </div>  
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php } ?>
                                <script type="text/javascript">
                                    $(document).ready(function () {
                                        var date_format = '<?php echo $result = strtr($this->customlib->getSchoolDateFormat(), ['d' => 'dd', 'm' => 'mm', 'Y' => 'yyyy',]) ?>';
                                        $(".date").datepicker({
                                            format: date_format,
                                            autoclose: true,
                                            todayHighlight: true
                                        });

                                        $(document).on('click', '#printStatementBtwn', function () {
                                            var date_from = $(this).data('date_from');
                                            var date_to = $(this).data('date_to');
                                            var report_type = $(this).data('report_type');  // Get report type

                                            $.ajax({
                                                url: '<?php echo site_url("admin/outstanding/printTransactions") ?>',
                                                type: 'post',
                                                data: {
                                                    'date_from': date_from,
                                                    'date_to': date_to,
                                                    'report_type': report_type  // Send report type
                                                },
                                                success: function (response) {
                                                    Popup(response);
                                                }
                                            });
                                        });

                                    });
                                </script>
                                <script type="text/javascript">
                                    $(document).ready(function () {
                                        var date_format = '<?php echo $result = strtr($this->customlib->getSchoolDateFormat(), ['d' => 'dd', 'm' => 'mm', 'Y' => 'yyyy',]) ?>';
                                        $(".date").datepicker({
                                            format: date_format,
                                            autoclose: true,
                                            todayHighlight: true
                                        });

                                        $(document).on('click', '#printStatementBtn', function () {
                                            var date_from = $(this).data('date_from');
                                            var date_to = $(this).data('date_to');
                                            var report_type = $(this).data('report_type');  // Get report type

                                            $.ajax({
                                                url: '<?php echo site_url("admin/outstanding/printTransaction") ?>',
                                                type: 'post',
                                                data: {
                                                    'date_from': date_from,
                                                    'date_to': date_to,
                                                    'report_type': report_type  // Send report type
                                                },
                                                success: function (response) {
                                                    Popup(response);
                                                }
                                            });
                                        });

                                    });
                                </script>
                                <script type="text/javascript">
                                    $(document).ready(function () {
                                        var date_format = '<?php echo $result = strtr($this->customlib->getSchoolDateFormat(), ['d' => 'dd', 'm' => 'mm', 'Y' => 'yyyy',]) ?>';
                                        $(".date").datepicker({
                                            format: date_format,
                                            autoclose: true,
                                            todayHighlight: true
                                        });
                                    });
                                </script>

                                <script type="text/javascript">
                                    $(document).ready(function () {
                                        $.extend($.fn.dataTable.defaults, {
                                            ordering: false,
                                            paging: false,
                                            bSort: false,
                                            info: false
                                        });
                                    })
                                    $(document).ready(function () {
                                        $('.table-fixed-header').fixedHeader();
                                    });

                                    (function ($) {

                                        $.fn.fixedHeader = function (options) {
                                            var config = {
                                                topOffset: 50

                                            };
                                            if (options) {
                                                $.extend(config, options);
                                            }

                                            return this.each(function () {
                                                var o = $(this);

                                                var $win = $(window);
                                                var $head = $('thead.header', o);
                                                var isFixed = 0;
                                                var headTop = $head.length && $head.offset().top - config.topOffset;

                                                function processScroll() {
                                                    if (!o.is(':visible')) {
                                                        return;
                                                    }
                                                    if ($('thead.header-copy').size()) {
                                                        $('thead.header-copy').width($('thead.header').width());
                                                    }
                                                    var i;
                                                    var scrollTop = $win.scrollTop();
                                                    var t = $head.length && $head.offset().top - config.topOffset;
                                                    if (!isFixed && headTop !== t) {
                                                        headTop = t;
                                                    }
                                                    if (scrollTop >= headTop && !isFixed) {
                                                        isFixed = 1;
                                                    } else if (scrollTop <= headTop && isFixed) {
                                                        isFixed = 0;
                                                    }
                                                    isFixed ? $('thead.header-copy', o).offset({
                                                        left: $head.offset().left
                                                    }).removeClass('hide') : $('thead.header-copy', o).addClass('hide');
                                                }
                                                $win.on('scroll', processScroll);

                                                // hack sad times - holdover until rewrite for 2.1
                                                $head.on('click', function () {
                                                    if (!isFixed) {
                                                        setTimeout(function () {
                                                            $win.scrollTop($win.scrollTop() - 47);
                                                        }, 10);
                                                    }
                                                });

                                                $head.clone().removeClass('header').addClass('header-copy header-fixed').appendTo(o);
                                                var header_width = $head.width();
                                                o.find('thead.header-copy').width(header_width);
                                                o.find('thead.header > tr:first > th').each(function (i, h) {
                                                    var w = $(h).width();
                                                    o.find('thead.header-copy> tr > th:eq(' + i + ')').width(w);
                                                });
                                                $head.css({
                                                    margin: '0 auto',
                                                    width: o.width(),
                                                    'background-color': config.bgColor
                                                });
                                                processScroll();
                                            });
                                        };

                                    })(jQuery);

                                </script>

                                <script>

                                    var base_url = '<?php echo base_url() ?>';
                                    function Popup(data)
                                    {

                                        var frame1 = $('<iframe />');
                                        frame1[0].name = "frame1";
                                        frame1.css({"position": "absolute", "top": "-1000000px"});
                                        $("body").append(frame1);
                                        var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
                                        frameDoc.document.open();
                                        //Create a new HTML document.
                                        frameDoc.document.write('<html>');
                                        frameDoc.document.write('<head>');
                                        frameDoc.document.write('<title></title>');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/bootstrap/css/bootstrap.min.css">');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/font-awesome.min.css">');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/ionicons.min.css">');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/AdminLTE.min.css">');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/dist/css/skins/_all-skins.min.css">');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/iCheck/flat/blue.css">');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/morris/morris.css">');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/jvectormap/jquery-jvectormap-1.2.2.css">');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/datepicker/datepicker3.css">');
                                        frameDoc.document.write('<link rel="stylesheet" href="' + base_url + 'backend/plugins/daterangepicker/daterangepicker-bs3.css">');
                                        frameDoc.document.write('</head>');
                                        frameDoc.document.write('<body>');
                                        frameDoc.document.write(data);
                                        frameDoc.document.write('</body>');
                                        frameDoc.document.write('</html>');
                                        frameDoc.document.close();
                                        setTimeout(function () {
                                            window.frames["frame1"].focus();
                                            window.frames["frame1"].print();
                                            frame1.remove();
                                        }, 500);


                                        return true;
                                    }
                                    $(document).ready(function () {
                                        $('.delmodal').modal({
                                            backdrop: 'static',
                                            keyboard: false,
                                            show: false
                                        })
                                        $('#confirm-delete').on('show.bs.modal', function (e) {
                                            $('.invoice_no', this).text("");
                                            $('#main_invoice', this).val("");
                                            $('#sub_invoice', this).val("");

                                            $('.invoice_no', this).text($(e.relatedTarget).data('invoiceno'));
                                            $('#main_invoice', this).val($(e.relatedTarget).data('main_invoice'));
                                            $('#sub_invoice', this).val($(e.relatedTarget).data('sub_invoice'));


                                        });

                                        $('#confirm-discountdelete').on('show.bs.modal', function (e) {
                                            $('.discount_title', this).text("");
                                            $('#discount_id', this).val("");
                                            $('.discount_title', this).text($(e.relatedTarget).data('discounttitle'));
                                            $('#discount_id', this).val($(e.relatedTarget).data('discountid'));
                                        });

                                        $('#confirm-delete').on('click', '.btn-ok', function (e) {
                                            var $modalDiv = $(e.delegateTarget);
                                            var main_invoice = $('#main_invoice').val();
                                            var sub_invoice = $('#sub_invoice').val();

                                            $modalDiv.addClass('modalloading');
                                            $.ajax({
                                                type: "post",
                                                url: '<?php echo site_url("studentfee/deleteFee") ?>',
                                                dataType: 'JSON',
                                                data: {'main_invoice': main_invoice, 'sub_invoice': sub_invoice},
                                                success: function (data) {
                                                    $modalDiv.modal('hide').removeClass('modalloading');
                                                    location.reload(true);
                                                }
                                            });


                                        });

                                        $('#confirm-discountdelete').on('click', '.btn-discountdel', function (e) {
                                            var $modalDiv = $(e.delegateTarget);
                                            var discount_id = $('#discount_id').val();


                                            $modalDiv.addClass('modalloading');
                                            $.ajax({
                                                type: "post",
                                                url: '<?php echo site_url("studentfee/deleteStudentDiscount") ?>',
                                                dataType: 'JSON',
                                                data: {'discount_id': discount_id},
                                                success: function (data) {
                                                    $modalDiv.modal('hide').removeClass('modalloading');
                                                    location.reload(true);
                                                }
                                            });


                                        });


                                        $(document).on('click', '.btn-ok', function (e) {
                                            var $modalDiv = $(e.delegateTarget);
                                            var main_invoice = $('#main_invoice').val();
                                            var sub_invoice = $('#sub_invoice').val();

                                            $modalDiv.addClass('modalloading');
                                            $.ajax({
                                                type: "post",
                                                url: '<?php echo site_url("studentfee/deleteFee") ?>',
                                                dataType: 'JSON',
                                                data: {'main_invoice': main_invoice, 'sub_invoice': sub_invoice},
                                                success: function (data) {
                                                    $modalDiv.modal('hide').removeClass('modalloading');
                                                    location.reload(true);
                                                }
                                            });


                                        });

                                        $('.detail_popover').popover({
                                            placement: 'right',
                                            title: '',
                                            trigger: 'hover',
                                            container: 'body',
                                            html: true,
                                            content: function () {
                                                return $(this).closest('td').find('.fee_detail_popover').html();
                                            }
                                        });
                                    });



                                </script>

                                <script type="text/javascript">


                                    $("#myFeesModal").on('shown.bs.modal', function (e) {
                                        console.log("sdrere");
                                        e.stopPropagation();
                                        var discount_group_dropdown = '<option value=""><?php echo $this->lang->line('select'); ?></option>';
                                        var data = $(e.relatedTarget).data();
                                        $('#discount_group').html("");
                                        $("span[id$='_error']").html("");
                                        $('.fees_title').html("");
                                        $('#amount').val("");
                                        $('#amount_discount').val("0");
                                        $('#amount_fine').val("0");
                                        var type = data.type;
                                        var amount = data.amount;
                                        var group = data.group;
                                        var fee_groups_feetype_id = data.fee_groups_feetype_id;
                                        var student_fees_master_id = data.student_fees_master_id;
                                        var student_session_id = data.student_session_id;

                                        $('.fees_title').html("<b>" + group + ":</b> " + type);
                                        $('#fee_groups_feetype_id').val(fee_groups_feetype_id);
                                        $('#student_fees_master_id').val(student_fees_master_id);



                                        $.ajax({
                                            type: "post",
                                            url: '<?php echo site_url("studentfee/geBalanceFee") ?>',
                                            dataType: 'JSON',
                                            data: {'fee_groups_feetype_id': fee_groups_feetype_id,
                                                'student_fees_master_id': student_fees_master_id,
                                                'student_session_id': student_session_id
                                            },
                                            success: function (data) {

                                                if (data.status == "success") {
                                                    fee_amount = data.balance;

                                                    $('#amount').val(data.balance);
                                                    console.log(data.discount_not_applied);

                                                    $.each(data.discount_not_applied, function (i, obj)
                                                    {
                                                        discount_group_dropdown += "<option value=" + obj.student_fees_discount_id + " data-disamount=" + obj.amount + ">" + obj.code + "</option>";
                                                    });
                                                    $('#discount_group').append(discount_group_dropdown);




                                                }
                                            }
                                        });


                                    });

                                </script>

                                <script type="text/javascript">
                                    $(document).ready(function () {
                                        $(document).on('click', '.printSelected', function () {
                                            var array_to_print = [];
                                            $.each($("input[name='fee_checkbox']:checked"), function () {
                                                var section_id = $(this).data('section_id');
                                                var class_id = $(this).data('class_id');
                                                var student_id = $(this).data('student_id');
                                                item = {}
                                                item ["section_id"] = section_id;
                                                item ["class_id"] = class_id;
                                                item ["student_id"] = student_id;

                                                array_to_print.push(item);
                                            });
                                            if (array_to_print.length == 0) {
                                                alert("no record selected");
                                            } else {
                                                $.ajax({
                                                    url: '<?php echo site_url("studentfee/printFeesStatementByGroup") ?>',
                                                    type: 'post',
                                                    data: {'data': JSON.stringify(array_to_print)},
                                                    success: function (response) {
                                                        Popup(response);
                                                    }
                                                });
                                            }
                                        });
                                    });


                                    $(function () {
                                        $(document).on('change', "#discount_group", function () {
                                            var amount = $('option:selected', this).data('disamount');

                                            var balance_amount = (parseFloat(fee_amount) - parseFloat(amount)).toFixed(2);
                                            if (typeof amount !== typeof undefined && amount !== false) {
                                                $('div#myFeesModal').find('input#amount_discount').prop('readonly', true).val(amount);
                                                $('div#myFeesModal').find('input#amount').val(balance_amount);

                                            } else {
                                                $('div#myFeesModal').find('input#amount').val(fee_amount);
                                                $('div#myFeesModal').find('input#amount_discount').prop('readonly', false).val(0);
                                            }

                                        });
                                    });
                                </script>

                                        